context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // // Copyright (c) Microsoft. 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. namespace Relay.Tests.ScenarioTests { using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.Management.Relay; using Microsoft.Azure.Management.Relay.Models; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Relay.Tests.TestHelper; using Xunit; public partial class ScenarioTests { [Fact] public void HybridConnectionsCreateGetUpdateDeleteAuthorizationRules_Length() { using (MockContext context = MockContext.Start(this.GetType())) { InitializeClients(context); var location = this.ResourceManagementClient.GetLocationFromProvider(); var resourceGroup = this.ResourceManagementClient.TryGetResourceGroup(location); if (string.IsNullOrWhiteSpace(resourceGroup)) { resourceGroup = TestUtilities.GenerateName(RelayManagementHelper.ResourceGroupPrefix); this.ResourceManagementClient.TryRegisterResourceGroup(location, resourceGroup); } // Create Namespace var namespaceName = TestUtilities.GenerateName(RelayManagementHelper.NamespacePrefix); var createNamespaceResponse = this.RelayManagementClient.Namespaces.CreateOrUpdate(resourceGroup, namespaceName, new RelayNamespace() { Location = location, Tags = new Dictionary<string, string>() { {"tag1", "value1"}, {"tag2", "value2"} } }); Assert.NotNull(createNamespaceResponse); Assert.Equal(createNamespaceResponse.Name, namespaceName); Assert.Equal(2, createNamespaceResponse.Tags.Count); Assert.Equal("Microsoft.Relay/Namespaces", createNamespaceResponse.Type); TestUtilities.Wait(TimeSpan.FromSeconds(5)); // Get the created namespace var getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); if (string.Compare(getNamespaceResponse.ProvisioningState.ToString(), "Succeeded", true) != 0) TestUtilities.Wait(TimeSpan.FromSeconds(5)); getNamespaceResponse = RelayManagementClient.Namespaces.Get(resourceGroup, namespaceName); Assert.NotNull(getNamespaceResponse); Assert.Equal("Succeeded", getNamespaceResponse.ProvisioningState.ToString(), StringComparer.CurrentCultureIgnoreCase); Assert.Equal(location, getNamespaceResponse.Location, StringComparer.CurrentCultureIgnoreCase); // Get all namespaces created within a resourceGroup var getAllNamespacesResponse = RelayManagementClient.Namespaces.ListByResourceGroup(resourceGroup); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); Assert.True(getAllNamespacesResponse.All(ns => ns.Id.Contains(resourceGroup))); // Get all namespaces created within the subscription irrespective of the resourceGroup getAllNamespacesResponse = RelayManagementClient.Namespaces.List(); Assert.NotNull(getAllNamespacesResponse); Assert.True(getAllNamespacesResponse.Count() >= 1); Assert.Contains(getAllNamespacesResponse, ns => ns.Name == namespaceName); // Create Relay HybridConnections - var hybridConnectionsName =RelayManagementHelper.HybridPrefix + "thisisthenamewithmorethan53charschecktoverifytheremovlaof50charsnamelengthlimit"; var createdWCFRelayResponse = RelayManagementClient.HybridConnections.CreateOrUpdate(resourceGroup, namespaceName, hybridConnectionsName, new HybridConnection() { RequiresClientAuthorization = true, }); Assert.NotNull(createdWCFRelayResponse); Assert.Equal(createdWCFRelayResponse.Name, hybridConnectionsName); Assert.True(createdWCFRelayResponse.RequiresClientAuthorization); var getWCFRelaysResponse = RelayManagementClient.HybridConnections.Get(resourceGroup, namespaceName, hybridConnectionsName); // Create a HybridConnections AuthorizationRule var authorizationRuleName = RelayManagementHelper.AuthorizationRulesPrefix + "thisisthenamewithmorethan53charschecktoverifytheremovlaof50charsnamelengthlimit"; string createPrimaryKey = HttpMockServer.GetVariable("CreatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); var createAutorizationRuleParameter = new AuthorizationRule() { Rights = new List<AccessRights?>() { AccessRights.Listen, AccessRights.Send } }; var jsonStr = RelayManagementHelper.ConvertObjectToJSon(createAutorizationRuleParameter); var test = RelayManagementClient.HybridConnections.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName, createAutorizationRuleParameter); var createNamespaceAuthorizationRuleResponse = RelayManagementClient.HybridConnections.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName, createAutorizationRuleParameter); Assert.NotNull(createNamespaceAuthorizationRuleResponse); Assert.True(createNamespaceAuthorizationRuleResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(createNamespaceAuthorizationRuleResponse.Rights, r => r == right); } // Get created HybridConnections AuthorizationRules var getNamespaceAuthorizationRulesResponse = RelayManagementClient.HybridConnections.GetAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRulesResponse); Assert.True(getNamespaceAuthorizationRulesResponse.Rights.Count == createAutorizationRuleParameter.Rights.Count); foreach (var right in createAutorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRulesResponse.Rights, r => r == right); } // Get all HybridConnections AuthorizationRules var getAllNamespaceAuthorizationRulesResponse = RelayManagementClient.HybridConnections.ListAuthorizationRules(resourceGroup, namespaceName, hybridConnectionsName); Assert.NotNull(getAllNamespaceAuthorizationRulesResponse); Assert.True(getAllNamespaceAuthorizationRulesResponse.Count() >= 1); Assert.Contains(getAllNamespaceAuthorizationRulesResponse, ns => ns.Name == authorizationRuleName); // Update HybridConnections authorizationRule string updatePrimaryKey = HttpMockServer.GetVariable("UpdatePrimaryKey", RelayManagementHelper.GenerateRandomKey()); AuthorizationRule updateNamespaceAuthorizationRuleParameter = new AuthorizationRule(); updateNamespaceAuthorizationRuleParameter.Rights = new List<AccessRights?>() { AccessRights.Listen }; var updateNamespaceAuthorizationRuleResponse = RelayManagementClient.HybridConnections.CreateOrUpdateAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName, updateNamespaceAuthorizationRuleParameter); Assert.NotNull(updateNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, updateNamespaceAuthorizationRuleResponse.Name); Assert.True(updateNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(updateNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the HybridConnections namespace AuthorizationRule var getNamespaceAuthorizationRuleResponse = RelayManagementClient.HybridConnections.GetAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName); Assert.NotNull(getNamespaceAuthorizationRuleResponse); Assert.Equal(authorizationRuleName, getNamespaceAuthorizationRuleResponse.Name); Assert.True(getNamespaceAuthorizationRuleResponse.Rights.Count == updateNamespaceAuthorizationRuleParameter.Rights.Count); foreach (var right in updateNamespaceAuthorizationRuleParameter.Rights) { Assert.Contains(getNamespaceAuthorizationRuleResponse.Rights, r => r.Equals(right)); } // Get the connectionString to the HybridConnections for a Authorization rule created var listKeysResponse = RelayManagementClient.HybridConnections.ListKeys(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName); Assert.NotNull(listKeysResponse); Assert.NotNull(listKeysResponse.PrimaryConnectionString); Assert.NotNull(listKeysResponse.SecondaryConnectionString); // Regenerate AuthorizationRules var regenerateKeysParameters = new RegenerateAccessKeyParameters(); regenerateKeysParameters.KeyType = KeyType.PrimaryKey; //Primary Key var regenerateKeysPrimaryResponse = RelayManagementClient.HybridConnections.RegenerateKeys(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysPrimaryResponse); Assert.NotEqual(regenerateKeysPrimaryResponse.PrimaryKey, listKeysResponse.PrimaryKey); Assert.Equal(regenerateKeysPrimaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); regenerateKeysParameters.KeyType = KeyType.SecondaryKey; //Secondary Key var regenerateKeysSecondaryResponse = RelayManagementClient.HybridConnections.RegenerateKeys(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName, regenerateKeysParameters); Assert.NotNull(regenerateKeysSecondaryResponse); Assert.NotEqual(regenerateKeysSecondaryResponse.SecondaryKey, listKeysResponse.SecondaryKey); Assert.Equal(regenerateKeysSecondaryResponse.PrimaryKey, regenerateKeysPrimaryResponse.PrimaryKey); // Delete HybridConnections authorizationRule RelayManagementClient.HybridConnections.DeleteAuthorizationRule(resourceGroup, namespaceName, hybridConnectionsName, authorizationRuleName); try { RelayManagementClient.HybridConnections.Delete(resourceGroup, namespaceName, hybridConnectionsName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } try { // Delete namespace RelayManagementClient.Namespaces.Delete(resourceGroup, namespaceName); } catch (Exception ex) { Assert.Contains("NotFound", ex.Message); } } } } }
using System.Linq; using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Formatting; namespace RefactoringEssentials.CSharp.CodeRefactorings { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Use 'as' and check for null")] public class UseAsAndNullCheckCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var isExpression = root.FindNode(span) as BinaryExpressionSyntax; if (!isExpression.IsKind(SyntaxKind.IsExpression) || !isExpression.OperatorToken.Span.Contains(span)) return; var ifElseStatement = isExpression.Parent.AncestorsAndSelf().FirstOrDefault(e => !(e is ParenthesizedExpressionSyntax) && !(e is BinaryExpressionSyntax)) as IfStatementSyntax; var expr = isExpression.Parent as ExpressionSyntax; if (expr != null) { var p = expr.AncestorsAndSelf().FirstOrDefault(e => !(e is ParenthesizedExpressionSyntax)); if (p.IsKind(SyntaxKind.LogicalNotExpression)) { ifElseStatement = p.Parent as IfStatementSyntax; } } if (ifElseStatement == null) return; int foundCasts; foreach (var action in ScanIfElse(model, document, root, ifElseStatement, isExpression, out foundCasts)) context.RegisterRefactoring(action); } internal static bool IsCast(SemanticModel model, SyntaxNode n, ITypeSymbol type) { var expr = n as ExpressionSyntax; if (expr == null) return false; expr = expr.SkipParens(); var castExpr = expr as CastExpressionSyntax; if (castExpr != null) { return model.GetTypeInfo(castExpr.Type).Type == type; } var binExpr = expr as BinaryExpressionSyntax; if (binExpr != null) { return binExpr.IsKind(SyntaxKind.AsExpression) && model.GetTypeInfo(binExpr.Right).Type == type; } return false; } internal static IEnumerable<CodeAction> ScanIfElse(SemanticModel ctx, Document document, SyntaxNode root, IfStatementSyntax ifElseStatement, BinaryExpressionSyntax isExpression, out int foundCastCount) { foundCastCount = 0; var innerCondition = ifElseStatement.Condition.SkipParens(); if (innerCondition != null && innerCondition.IsKind(SyntaxKind.LogicalNotExpression)) { var c2 = ((PrefixUnaryExpressionSyntax)innerCondition).Operand.SkipParens(); if (c2.IsKind(SyntaxKind.IsExpression)) { return HandleNegatedCase(ctx, document, root, ifElseStatement, ifElseStatement.Condition, isExpression, out foundCastCount); } return Enumerable.Empty<CodeAction>(); } var castToType = isExpression.Right; var embeddedStatment = ifElseStatement.Statement; var rr = ctx.GetTypeInfo(castToType); if (rr.Type == null || !rr.Type.IsReferenceType) return Enumerable.Empty<CodeAction>(); List<SyntaxNode> foundCasts; foundCasts = embeddedStatment.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => IsCast(ctx, arg, rr.Type)).ToList(); foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > isExpression.Span.End && IsCast(ctx, arg, rr.Type))); foundCastCount = foundCasts.Count; return new[] { CodeActionFactory.Create( isExpression.Span, DiagnosticSeverity.Info, GettextCatalog.GetString ("Use 'as' and check for null"), t2 => { var varName = ReplaceAutoPropertyWithPropertyAndBackingFieldCodeRefactoringProvider.GetNameProposal(RefactoringHelpers.GuessNameFromType(rr.Type), ctx, isExpression); var varDec = SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SeparatedList(new [] { SyntaxFactory.VariableDeclarator(varName) .WithInitializer(SyntaxFactory.EqualsValueClause( SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, isExpression.Left, isExpression.Right) )) }) )); var outerIs = isExpression.AncestorsAndSelf().FirstOrDefault(e => !(e.Parent is ParenthesizedExpressionSyntax)); var binaryOperatorExpression = SyntaxFactory.BinaryExpression(SyntaxKind.NotEqualsExpression, SyntaxFactory.IdentifierName(varName), SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); SyntaxNode newRoot; if (IsEmbeddedStatement(ifElseStatement)) { foundCasts = ifElseStatement.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => IsCast(ctx, arg, rr.Type)).ToList(); var newIf = ifElseStatement.TrackNodes(foundCasts.Concat(new [] { outerIs })); newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(outerIs), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation)); foreach (var c in foundCasts) { newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation)); } var block = SyntaxFactory.Block(new StatementSyntax[] { varDec, newIf }); newRoot = root.ReplaceNode((SyntaxNode)ifElseStatement, block.WithAdditionalAnnotations(Formatter.Annotation)); } else { newRoot = root.TrackNodes(foundCasts.Concat(new SyntaxNode[] { ifElseStatement, outerIs }) ); newRoot = newRoot.InsertNodesBefore(newRoot.GetCurrentNode(ifElseStatement), new [] { varDec.WithAdditionalAnnotations(Formatter.Annotation) }); newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(outerIs), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation)); foreach (var c in foundCasts) { newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation)); } } return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) }; } internal static bool IsEmbeddedStatement(SyntaxNode stmt) { return !(stmt.Parent is BlockSyntax); } internal static IEnumerable<CodeAction> HandleNegatedCase(SemanticModel ctx, Document document, SyntaxNode root, IfStatementSyntax ifElseStatement, ExpressionSyntax c2, BinaryExpressionSyntax isExpression, out int foundCastCount) { foundCastCount = 0; var condition = isExpression; var castToType = isExpression.Right; var embeddedStatment = ifElseStatement.Statement; var rr = ctx.GetTypeInfo(castToType); if (rr.Type == null || !rr.Type.IsReferenceType) return Enumerable.Empty<CodeAction>(); List<SyntaxNode> foundCasts; SyntaxNode searchStmt = embeddedStatment; if (IsControlFlowChangingStatement(searchStmt)) { searchStmt = ifElseStatement.Parent; foundCasts = searchStmt.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart >= ifElseStatement.SpanStart && IsCast(ctx, arg, rr.Type)).ToList(); foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > isExpression.Span.End && IsCast(ctx, arg, rr.Type))); } else { foundCasts = new List<SyntaxNode>(); } foundCastCount = foundCasts.Count; return new[] { CodeActionFactory.Create( isExpression.Span, DiagnosticSeverity.Info, GettextCatalog.GetString ("Use 'as' and check for null"), t2 => { var varName = ReplaceAutoPropertyWithPropertyAndBackingFieldCodeRefactoringProvider.GetNameProposal(RefactoringHelpers.GuessNameFromType(rr.Type), ctx, condition); var varDec = SyntaxFactory.LocalDeclarationStatement( SyntaxFactory.VariableDeclaration( SyntaxFactory.ParseTypeName("var"), SyntaxFactory.SeparatedList(new [] { SyntaxFactory.VariableDeclarator(varName) .WithInitializer(SyntaxFactory.EqualsValueClause( SyntaxFactory.BinaryExpression(SyntaxKind.AsExpression, condition.Left, condition.Right) )) }) )); //var outerIs = isExpression.AncestorsAndSelf().FirstOrDefault(e => !(e.Parent is ParenthesizedExpressionSyntax)); var binaryOperatorExpression = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.IdentifierName(varName), SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)); SyntaxNode newRoot; if (IsEmbeddedStatement(ifElseStatement)) { var newIf = ifElseStatement.ReplaceNode((SyntaxNode)c2, binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation)); foreach (var c in foundCasts) { newIf = newIf.ReplaceNode((SyntaxNode)newIf.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation)); } var block = SyntaxFactory.Block(new StatementSyntax[] { varDec, newIf }); newRoot = root.ReplaceNode((SyntaxNode)ifElseStatement, block.WithAdditionalAnnotations(Formatter.Annotation)); } else { newRoot = root.TrackNodes(foundCasts.Concat(new SyntaxNode[] { ifElseStatement, c2 }) ); newRoot = newRoot.InsertNodesBefore(newRoot.GetCurrentNode(ifElseStatement), new [] { varDec.WithAdditionalAnnotations(Formatter.Annotation) }); newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c2), binaryOperatorExpression.WithAdditionalAnnotations(Formatter.Annotation)); foreach (var c in foundCasts) { newRoot = newRoot.ReplaceNode((SyntaxNode)newRoot.GetCurrentNode(c), SyntaxFactory.IdentifierName(varName).WithAdditionalAnnotations(Formatter.Annotation)); } } return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) }; } internal static bool IsControlFlowChangingStatement(SyntaxNode searchStmt) { if (searchStmt is ReturnStatementSyntax || searchStmt is BreakStatementSyntax || searchStmt is ContinueStatementSyntax || searchStmt is GotoStatementSyntax) return true; var block = searchStmt as BlockSyntax; if (block != null) { return IsControlFlowChangingStatement(block.Statements.LastOrDefault()); } return false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using Validation; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableSortedDictionary{TKey, TValue}"/>. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] public static class ImmutableSortedDictionary { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>() { return ImmutableSortedDictionary<TKey, TValue>.Empty; } /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer); } /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> Create<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer).AddRange(items); } /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> CreateRange<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer, IEnumerable<KeyValuePair<TKey, TValue>> items) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(items); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>() { return Create<TKey, TValue>().ToBuilder(); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer) { return Create<TKey, TValue>(keyComparer).ToBuilder(); } /// <summary> /// Creates a new immutable sorted dictionary builder. /// </summary> /// <typeparam name="TKey">The type of keys stored by the dictionary.</typeparam> /// <typeparam name="TValue">The type of values stored by the dictionary.</typeparam> /// <param name="keyComparer">The key comparer.</param> /// <param name="valueComparer">The value comparer.</param> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue>.Builder CreateBuilder<TKey, TValue>(IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { return Create<TKey, TValue>(keyComparer, valueComparer).ToBuilder(); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <param name="valueComparer">The value comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer) .AddRange(source.Select(element => new KeyValuePair<TKey, TValue>(keySelector(element), elementSelector(element)))); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <param name="keyComparer">The key comparer to use for the map.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector, IComparer<TKey> keyComparer) { return ToImmutableSortedDictionary(source, keySelector, elementSelector, keyComparer, null); } /// <summary> /// Constructs an immutable sorted dictionary based on some transformation of a sequence. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <typeparam name="TKey">The type of key in the resulting map.</typeparam> /// <typeparam name="TValue">The type of value in the resulting map.</typeparam> /// <param name="source">The sequence to enumerate to generate the map.</param> /// <param name="keySelector">The function that will produce the key for the map from each sequence element.</param> /// <param name="elementSelector">The function that will produce the value for the map from each sequence element.</param> /// <returns>The immutable map.</returns> [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TValue> elementSelector) { return ToImmutableSortedDictionary(source, keySelector, elementSelector, null, null); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <param name="valueComparer">The value comparer to use for the immutable map.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer, IEqualityComparer<TValue> valueComparer) { Requires.NotNull(source, "source"); Contract.Ensures(Contract.Result<ImmutableDictionary<TKey, TValue>>() != null); var existingDictionary = source as ImmutableSortedDictionary<TKey, TValue>; if (existingDictionary != null) { return existingDictionary.WithComparers(keyComparer, valueComparer); } return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer).AddRange(source); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <param name="keyComparer">The key comparer to use when building the immutable map.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IComparer<TKey> keyComparer) { return ToImmutableSortedDictionary(source, keyComparer, null); } /// <summary> /// Creates an immutable sorted dictionary given a sequence of key=value pairs. /// </summary> /// <typeparam name="TKey">The type of key in the map.</typeparam> /// <typeparam name="TValue">The type of value in the map.</typeparam> /// <param name="source">The sequence of key=value pairs.</param> /// <returns>An immutable map.</returns> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] [Pure] public static ImmutableSortedDictionary<TKey, TValue> ToImmutableSortedDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { return ToImmutableSortedDictionary(source, null, null); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // // // Based on "libbzip2", Copyright (C) 1996-2007 Julian R Seward. // namespace DiscUtils.Compression { using System; using System.IO; /// <summary> /// Implementation of a BZip2 decoder. /// </summary> public sealed class BZip2DecoderStream : Stream { private long _position; private Stream _compressedStream; private Ownership _ownsCompressed; private BitStream _bitstream; private BZip2RleStream _rleStream; private BZip2BlockDecoder _blockDecoder; private Crc32 _calcBlockCrc; private byte[] _blockBuffer; private uint _blockCrc; private uint _compoundCrc; private uint _calcCompoundCrc; private bool _eof; /// <summary> /// Initializes a new instance of the BZip2DecoderStream class. /// </summary> /// <param name="stream">The compressed input stream.</param> /// <param name="ownsStream">Whether ownership of stream passes to the new instance.</param> public BZip2DecoderStream(Stream stream, Ownership ownsStream) { _compressedStream = stream; _ownsCompressed = ownsStream; _bitstream = new BigEndianBitStream(new BufferedStream(stream)); // The Magic BZh byte[] magic = new byte[3]; magic[0] = (byte)_bitstream.Read(8); magic[1] = (byte)_bitstream.Read(8); magic[2] = (byte)_bitstream.Read(8); if (magic[0] != 0x42 || magic[1] != 0x5A || magic[2] != 0x68) { throw new InvalidDataException("Bad magic at start of stream"); } // The size of the decompression blocks in multiples of 100,000 int blockSize = (int)_bitstream.Read(8) - 0x30; if (blockSize < 1 || blockSize > 9) { throw new InvalidDataException("Unexpected block size in header: " + blockSize); } blockSize *= 100000; _rleStream = new BZip2RleStream(); _blockDecoder = new BZip2BlockDecoder(blockSize); _blockBuffer = new byte[blockSize]; if (ReadBlock() == 0) { _eof = true; } } /// <summary> /// Gets an indication of whether read access is permitted. /// </summary> public override bool CanRead { get { return true; } } /// <summary> /// Gets an indication of whether seeking is permitted. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets an indication of whether write access is permitted. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Gets the length of the stream (the capacity of the underlying buffer). /// </summary> public override long Length { get { throw new NotSupportedException(); } } /// <summary> /// Gets and sets the current position within the stream. /// </summary> public override long Position { get { return _position; } set { throw new NotSupportedException(); } } /// <summary> /// Flushes all data to the underlying storage. /// </summary> public override void Flush() { throw new NotSupportedException(); } /// <summary> /// Reads a number of bytes from the stream. /// </summary> /// <param name="buffer">The destination buffer.</param> /// <param name="offset">The start offset within the destination buffer.</param> /// <param name="count">The number of bytes to read.</param> /// <returns>The number of bytes read.</returns> public override int Read(byte[] buffer, int offset, int count) { if (buffer.Length < offset + count) { throw new ArgumentException("Buffer smaller than declared"); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentException("Offset less than zero", "offset"); } if (count < 0) { throw new ArgumentException("Count less than zero", "count"); } if (_eof) { throw new IOException("Attempt to read beyond end of stream"); } if (count == 0) { return 0; } int numRead = _rleStream.Read(buffer, offset, count); if (numRead == 0) { // If there was an existing block, check it's crc. if (_calcBlockCrc != null) { if (_blockCrc != _calcBlockCrc.Value) { throw new InvalidDataException("Decompression failed - block CRC mismatch"); } _calcCompoundCrc = ((_calcCompoundCrc << 1) | (_calcCompoundCrc >> 31)) ^ _blockCrc; } // Read a new block (if any), if none - check the overall CRC before returning if (ReadBlock() == 0) { _eof = true; if (_calcCompoundCrc != _compoundCrc) { throw new InvalidDataException("Decompression failed - compound CRC"); } return 0; } numRead = _rleStream.Read(buffer, offset, count); } _calcBlockCrc.Process(buffer, offset, numRead); // Pre-read next block, so a client that knows the decompressed length will still // have the overall CRC calculated. if (_rleStream.AtEof) { // If there was an existing block, check it's crc. if (_calcBlockCrc != null) { if (_blockCrc != _calcBlockCrc.Value) { throw new InvalidDataException("Decompression failed - block CRC mismatch"); } } _calcCompoundCrc = ((_calcCompoundCrc << 1) | (_calcCompoundCrc >> 31)) ^ _blockCrc; if (ReadBlock() == 0) { _eof = true; if (_calcCompoundCrc != _compoundCrc) { throw new InvalidDataException("Decompression failed - compound CRC mismatch"); } return numRead; } } _position += numRead; return numRead; } /// <summary> /// Changes the current stream position. /// </summary> /// <param name="offset">The origin-relative stream position.</param> /// <param name="origin">The origin for the stream position.</param> /// <returns>The new stream position</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } /// <summary> /// Sets the length of the stream (the underlying buffer's capacity). /// </summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { throw new NotSupportedException(); } /// <summary> /// Writes a buffer to the stream. /// </summary> /// <param name="buffer">The buffer to write.</param> /// <param name="offset">The starting offset within buffer.</param> /// <param name="count">The number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } /// <summary> /// Releases underlying resources. /// </summary> /// <param name="disposing">Whether this method is called from Dispose.</param> protected override void Dispose(bool disposing) { try { if (disposing) { if (_compressedStream != null && _ownsCompressed == Ownership.Dispose) { _compressedStream.Dispose(); } _compressedStream = null; if (_rleStream != null) { _rleStream.Dispose(); _rleStream = null; } } } finally { base.Dispose(disposing); } } private int ReadBlock() { ulong marker = ReadMarker(); if (marker == 0x314159265359) { int blockSize = _blockDecoder.Process(_bitstream, _blockBuffer, 0); _rleStream.Reset(_blockBuffer, 0, blockSize); _blockCrc = _blockDecoder.Crc; _calcBlockCrc = new Crc32BigEndian(Crc32Algorithm.Common); return blockSize; } else if (marker == 0x177245385090) { _compoundCrc = ReadUint(); return 0; } else { throw new InvalidDataException("Found invalid marker in stream"); } } private uint ReadUint() { uint val = 0; for (int i = 0; i < 4; ++i) { val = (val << 8) | _bitstream.Read(8); } return val; } private ulong ReadMarker() { ulong marker = 0; for (int i = 0; i < 6; ++i) { marker = (marker << 8) | _bitstream.Read(8); } return marker; } } }
//Copyright (C) 2005 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the TwoPassDataIndexer.java source file found in the //original java implementation of MaxEnt. That source file contains the following header: //Copyright (C) 2003 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections.Generic; using System.IO; using System.Text; namespace SharpEntropy { /// <summary> /// Collecting event and context counts by making two passes over the events. /// The first pass determines which contexts will be used by the model, and the second /// pass creates the events in memory containing only the contexts which will be used. /// This greatly reduces the amount of memory required for storing the events. /// During the first pass a temporary event file is created which is read during the second pass. /// </summary> /// /// <author> /// Tom Morton /// </author> /// /// /// <author> /// Richard J. Northedge /// </author> public class TwoPassDataIndexer : AbstractDataIndexer { /// <summary> /// One argument constructor for DataIndexer which calls the two argument /// constructor assuming no cutoff. /// </summary> /// <param name="eventReader"> /// An ITrainingEventReader which contains the list of all the events /// seen in the training data. /// </param> public TwoPassDataIndexer(ITrainingEventReader eventReader): this(eventReader, 0){} /// <summary> /// Two argument constructor for TwoPassDataIndexer. /// </summary> /// <param name="eventReader"> /// An ITrainingEventReader which contains the a list of all the events /// seen in the training data. /// </param> /// <param name="cutoff"> /// The minimum number of times a predicate must have been /// observed in order to be included in the model. /// </param> public TwoPassDataIndexer(ITrainingEventReader eventReader, int cutoff) { List<ComparableEvent> eventsToCompare; var predicateIndex = new Dictionary<string, int>(); //NotifyProgress("Indexing events using cutoff of " + cutoff + "\n"); //NotifyProgress("\tComputing event counts... "); string tempFile = new FileInfo(Path.GetTempFileName()).FullName; int eventCount = ComputeEventCounts(eventReader, tempFile, predicateIndex, cutoff); //NotifyProgress("done. " + eventCount + " events"); //NotifyProgress("\tIndexing... "); using (var fileEventReader = new FileEventReader(tempFile)) { eventsToCompare = Index(eventCount, fileEventReader, predicateIndex); } if (File.Exists(tempFile)) { File.Delete(tempFile); } //NotifyProgress("done."); //NotifyProgress("Sorting and merging events... "); SortAndMerge(eventsToCompare); //NotifyProgress("Done indexing."); } /// <summary> /// Reads events from <tt>eventStream</tt> into a dictionary. The /// predicates associated with each event are counted and any which /// occur at least <tt>cutoff</tt> times are added to the /// <tt>predicatesInOut</tt> map along with a unique integer index. /// </summary> /// <param name="eventReader"> /// an <code>ITrainingEventReader</code> value /// </param> /// <param name="eventStoreFile"> /// a file name to which the events are written to for later processing. /// </param> /// <param name="predicatesInOut"> /// a <code>Dictionary</code> value /// </param> /// <param name="cutoff"> /// an <code>int</code> value /// </param> private int ComputeEventCounts(ITrainingEventReader eventReader, string eventStoreFile, Dictionary<string, int> predicatesInOut, int cutoff) { var counter = new Dictionary<string, int>(); int predicateIndex = 0; int eventCount = 0; using (var eventStoreWriter = new StreamWriter(eventStoreFile)) { while (eventReader.HasNext()) { TrainingEvent currentTrainingEvent = eventReader.ReadNextEvent(); eventCount++; eventStoreWriter.Write(FileEventReader.ToLine(currentTrainingEvent)); string[] eventContext = currentTrainingEvent.Context; for (int currentPredicate = 0; currentPredicate < eventContext.Length; currentPredicate++) { if (!predicatesInOut.ContainsKey(eventContext[currentPredicate])) { if (counter.ContainsKey(eventContext[currentPredicate])) { counter[eventContext[currentPredicate]]++; } else { counter.Add(eventContext[currentPredicate], 1); } if (counter[eventContext[currentPredicate]] >= cutoff) { predicatesInOut.Add(eventContext[currentPredicate], predicateIndex++); counter.Remove(eventContext[currentPredicate]); } } } } } return eventCount; } private List<ComparableEvent> Index(int eventCount, ITrainingEventReader eventReader, Dictionary<string, int> predicateIndex) { var outcomeMap = new Dictionary<string, int>(); int outcomeCount = 0; var eventsToCompare = new List<ComparableEvent>(eventCount); var indexedContext = new List<int>(); while (eventReader.HasNext()) { TrainingEvent currentTrainingEvent = eventReader.ReadNextEvent(); string[] eventContext = currentTrainingEvent.Context; ComparableEvent comparableEvent; int outcomeId; string outcome = currentTrainingEvent.Outcome; if (outcomeMap.ContainsKey(outcome)) { outcomeId = outcomeMap[outcome]; } else { outcomeId = outcomeCount++; outcomeMap.Add(outcome, outcomeId); } for (int currentPredicate = 0; currentPredicate < eventContext.Length; currentPredicate++) { string predicate = eventContext[currentPredicate]; if (predicateIndex.ContainsKey(predicate)) { indexedContext.Add(predicateIndex[predicate]); } } // drop events with no active features if (indexedContext.Count > 0) { comparableEvent = new ComparableEvent(outcomeId, indexedContext.ToArray()); eventsToCompare.Add(comparableEvent); } else { //"Dropped event " + currentTrainingEvent.Outcome + ":" + currentTrainingEvent.Context); } // recycle the list indexedContext.Clear(); } SetOutcomeLabels(ToIndexedStringArray(outcomeMap)); SetPredicateLabels(ToIndexedStringArray(predicateIndex)); return eventsToCompare; } } class FileEventReader : ITrainingEventReader, IDisposable { private StreamReader mReader; private string mCurrentLine; private char[] mWhitespace; public FileEventReader(string fileName) { mReader = new StreamReader(fileName, Encoding.UTF7); mWhitespace = new char[] {'\t', '\n', '\r', ' '}; } public virtual bool HasNext() { mCurrentLine = mReader.ReadLine(); return (mCurrentLine != null); } public virtual TrainingEvent ReadNextEvent() { string[] tokens = mCurrentLine.Split(mWhitespace); string outcome = tokens[0]; var context = new string[tokens.Length - 1]; Array.Copy(tokens, 1, context, 0, tokens.Length - 1); return (new TrainingEvent(outcome, context)); } public static string ToLine(TrainingEvent eventToConvert) { var lineBuilder = new StringBuilder(); lineBuilder.Append(eventToConvert.Outcome); string[] context = eventToConvert.Context; for (int contextIndex = 0, contextLength = context.Length; contextIndex < contextLength; contextIndex++) { lineBuilder.Append(" " + context[contextIndex]); } lineBuilder.Append(System.Environment.NewLine); return lineBuilder.ToString(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { mReader.Close(); } } ~FileEventReader() { Dispose (false); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace BullsAndCows.Web.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Hydra.Framework.Extensions { /// <summary> /// ExtensionMethods to all Intefaces that require specific implementation of generic declarations /// </summary> public static class InterfaceExtensions { #region Static Methods /// <summary> /// Checks if an object implements the specified interface /// </summary> /// <param name = "obj">The object to check</param> /// <param name = "interfaceType">The interface type (can be generic, either specific or open)</param> /// <returns>True if the interface is implemented by the object, otherwise false</returns> public static bool Implements(this object obj, Type interfaceType) { Guard.Against.Null(obj, "obj"); Type objectType = obj.GetType(); return objectType.Implements(interfaceType); } /// <summary> /// Checks if a type implements the specified interface /// </summary> /// <typeparam name = "T">The interface type (can be generic, either specific or open)</typeparam> /// <param name = "objectType">The type to check</param> /// <returns>True if the interface is implemented by the type, otherwise false</returns> //public static bool Implements<T>(this Type objectType) //{ // return objectType.Implements(typeof(T)); //} /// <summary> /// Implementses the specified instance. /// </summary> /// <param name="instance">The instance.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> //public static bool Implements(this object instance, Type interfaceType) //{ // return interfaceType.IsGenericTypeDefinition // ? instance.ImplementsGeneric(interfaceType) // : interfaceType.IsAssignableFrom(instance.GetType()); //} /// <summary> /// Implementses the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static bool Implements(this Type type, Type interfaceType) { return interfaceType.IsGenericTypeDefinition ? type.ImplementsGeneric(interfaceType) : interfaceType.IsAssignableFrom(type); } /// <summary> /// Implementses the specified instance. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <returns></returns> public static bool Implements<T>(this object instance) { var interfaceType = typeof(T); return instance.Implements(interfaceType); } /// <summary> /// Implementses the specified type. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">The type.</param> /// <returns></returns> public static bool Implements<T>(this Type type) { var interfaceType = typeof(T); return interfaceType.IsGenericTypeDefinition ? type.ImplementsGeneric(interfaceType) : interfaceType.IsAssignableFrom(type); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <param name="instance">The instance.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric(this object instance, Type interfaceType) { return instance.GetType().GetDeclaredTypeForGeneric(interfaceType); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric<T>(this object instance) { var interfaceType = typeof(T); return instance.GetDeclaredTypeForGeneric(interfaceType); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric<T>(this object instance, T interfaceType) { return instance.GetDeclaredTypeForGeneric(typeof(T)); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">The type.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric<T>(this Type type) { var interfaceType = typeof(T); return type.GetDeclaredTypeForGeneric(interfaceType); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric<T>(this Type type, T interfaceType) { return type.GetDeclaredTypeForGeneric(typeof(T)); } /// <summary> /// Gets the declared type for generic. /// </summary> /// <param name="baseType">Type of the base.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static Type GetDeclaredTypeForGeneric(this Type baseType, Type interfaceType) { var type = default(Type); if (baseType.ImplementsGeneric(interfaceType)) { var generic = baseType.GetInterface(interfaceType.FullName); if (generic.IsGenericType) { var args = generic.GetGenericArguments(); if (args.Length == 1) type = args[0]; } } return type; } /// <summary> /// Gets the declared types for generic. /// </summary> /// <param name="instance">The instance.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric(this object instance, Type interfaceType) { return instance.GetType().GetDeclaredTypesForGeneric(interfaceType); } /// <summary> /// Gets the declared types for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric<T>(this object instance) { var interfaceType = typeof(T); return instance.GetType().GetDeclaredTypesForGeneric(interfaceType); } /// <summary> /// Gets the declared types for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric<T>(this object instance, T interfaceType) { return instance.GetDeclaredTypesForGeneric<T>(); } /// <summary> /// Gets the declared types for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">The type.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric<T>(this Type type) { var interfaceType = typeof(T); return type.GetDeclaredTypesForGeneric(interfaceType); } /// <summary> /// Gets the declared types for generic. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric<T>(this Type type, T interfaceType) { return type.GetDeclaredTypesForGeneric(typeof(T)); } /// <summary> /// Gets the declared types for generic. /// </summary> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> public static IEnumerable<Type> GetDeclaredTypesForGeneric(this Type type, Type interfaceType) { IEnumerable<Type> source = interfaceType.IsInterface ? type.GetGenericInterfacesFor(interfaceType) : type.GetGenericFor(interfaceType); foreach (var generic in source) foreach (var arg in generic.GetGenericArguments()) yield return arg; } #endregion #region Private Static Methods /// <summary> /// Gets the generic interfaces for. /// </summary> /// <param name="type">The type.</param> /// <param name="interfaceType">Type of the interface.</param> /// <returns></returns> private static IEnumerable<Type> GetGenericInterfacesFor(this Type type, Type interfaceType) { var candidates = type.GetInterfaces(); foreach (var candidate in candidates) { if (!candidate.IsGenericType) continue; var definition = candidate.GetGenericTypeDefinition(); if (definition == interfaceType) yield return candidate; } } /// <summary> /// Gets the generic for. /// </summary> /// <param name="type">The type.</param> /// <param name="targetType">Type of the target.</param> /// <returns></returns> private static IEnumerable<Type> GetGenericFor(this Type type, Type targetType) { var baseType = type; while (baseType != null) { if (baseType.IsGenericType) if (baseType.GetGenericTypeDefinition() == targetType) yield return baseType; baseType = baseType.BaseType; } } /// <summary> /// Implementses the generic. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static bool ImplementsGeneric(this Type type) { var impGeneric = false; var interfaceTypes = type.GetInterfaces(); foreach (var interfaceType in interfaceTypes) { if (!interfaceType.IsGenericType) continue; impGeneric = true; break; } return impGeneric; } /// <summary> /// Implementses the generic. /// </summary> /// <param name="type">The type.</param> /// <param name="targetType">Type of the target.</param> /// <returns></returns> public static bool ImplementsGeneric(this Type type, Type targetType) { var interfaceTypes = type.GetInterfaces(); foreach (var interfaceType in interfaceTypes) { if (!interfaceType.IsGenericType) continue; if (interfaceType.GetGenericTypeDefinition() == targetType) return true; } var baseType = type.BaseType; if (baseType == null) return false; return baseType.IsGenericType ? baseType.GetGenericTypeDefinition() == targetType : baseType.ImplementsGeneric(targetType); } /// <summary> /// Checks if a type implements an open generic at any level of the inheritance chain, including all /// base classes /// </summary> /// <param name = "objectType">The type to check</param> /// <param name = "interfaceType">The interface type (must be a generic type definition)</param> /// <param name = "matchedType">The matching type that was found for the interface type</param> /// <returns>True if the interface is implemented by the type, otherwise false</returns> public static bool ImplementsGeneric(this Type objectType, Type interfaceType, out Type matchedType) { Guard.Against.Null(objectType, "Expected a valid object type to be provided"); Guard.Against.Null(interfaceType, "Expected a valid interface type to be provided"); Guard.IsTrue(x => x.IsGenericType, interfaceType, "interfaceType", "Must be a generic type"); Guard.IsTrue(x => x.IsGenericTypeDefinition, interfaceType, "interfaceType", "Must be a generic type definition"); matchedType = null; if (interfaceType.IsInterface) { matchedType = objectType.GetInterfaces() .Where(x => x.IsGenericType && x.GetGenericTypeDefinition() == interfaceType) .FirstOrDefault(); if (matchedType != null) return true; } if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == interfaceType) { matchedType = objectType; return true; } Type baseType = objectType.BaseType; if (baseType == null) return false; return baseType.ImplementsGeneric(interfaceType, out matchedType); } /// <summary> /// Gets all interfaces. /// </summary> /// <param name="type">The type.</param> /// <returns></returns> public static IEnumerable<Type> GetAllInterfaces(this Type type) { foreach (Type interfaceType in type.GetInterfaces()) yield return interfaceType; } #endregion } }
/* * 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.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Xml; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Mono.Addins; using OpenSim.Services.Connectors.Hypergrid; namespace OpenSim.Region.OptionalModules.Avatar.UserProfiles { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserProfilesModule")] public class UserProfileModule : IProfileModule, INonSharedRegionModule { /// <summary> /// Logging /// </summary> static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // The pair of Dictionaries are used to handle the switching of classified ads // by maintaining a cache of classified id to creator id mappings and an interest // count. The entries are removed when the interest count reaches 0. Dictionary<UUID, UUID> m_classifiedCache = new Dictionary<UUID, UUID>(); Dictionary<UUID, int> m_classifiedInterest = new Dictionary<UUID, int>(); public Scene Scene { get; private set; } /// <summary> /// Gets or sets the ConfigSource. /// </summary> /// <value> /// The configuration /// </value> public IConfigSource Config { get; set; } /// <summary> /// Gets or sets the URI to the profile server. /// </summary> /// <value> /// The profile server URI. /// </value> public string ProfileServerUri { get; set; } IProfileModule ProfileModule { get; set; } IUserManagement UserManagementModule { get; set; } /// <summary> /// Gets or sets a value indicating whether this /// <see cref="OpenSim.Region.Coremodules.UserProfiles.UserProfileModule"/> is enabled. /// </summary> /// <value> /// <c>true</c> if enabled; otherwise, <c>false</c>. /// </value> public bool Enabled { get; set; } #region IRegionModuleBase implementation /// <summary> /// This is called to initialize the region module. For shared modules, this is called exactly once, after /// creating the single (shared) instance. For non-shared modules, this is called once on each instance, after /// the instace for the region has been created. /// </summary> /// <param name='source'> /// Source. /// </param> public void Initialise(IConfigSource source) { Config = source; ReplaceableInterface = typeof(IProfileModule); IConfig profileConfig = Config.Configs["UserProfiles"]; if (profileConfig == null) { m_log.Debug("[PROFILES]: UserProfiles disabled, no configuration"); Enabled = false; return; } // If we find ProfileURL then we configure for FULL support // else we setup for BASIC support ProfileServerUri = profileConfig.GetString("ProfileServiceURL", ""); if (ProfileServerUri == "") { Enabled = false; return; } m_log.Debug("[PROFILES]: Full Profiles Enabled"); ReplaceableInterface = null; Enabled = true; } /// <summary> /// Adds the region. /// </summary> /// <param name='scene'> /// Scene. /// </param> public void AddRegion(Scene scene) { if(!Enabled) return; Scene = scene; Scene.RegisterModuleInterface<IProfileModule>(this); Scene.EventManager.OnNewClient += OnNewClient; Scene.EventManager.OnMakeRootAgent += HandleOnMakeRootAgent; UserManagementModule = Scene.RequestModuleInterface<IUserManagement>(); } void HandleOnMakeRootAgent (ScenePresence obj) { if(obj.PresenceType == PresenceType.Npc) return; Util.FireAndForget(delegate { GetImageAssets(((IScenePresence)obj).UUID); }); } /// <summary> /// Removes the region. /// </summary> /// <param name='scene'> /// Scene. /// </param> public void RemoveRegion(Scene scene) { if(!Enabled) return; } /// <summary> /// This will be called once for every scene loaded. In a shared module this will be multiple times in one /// instance, while a nonshared module instance will only be called once. This method is called after AddRegion /// has been called in all modules for that scene, providing an opportunity to request another module's /// interface, or hook an event from another module. /// </summary> /// <param name='scene'> /// Scene. /// </param> public void RegionLoaded(Scene scene) { if(!Enabled) return; } /// <summary> /// If this returns non-null, it is the type of an interface that this module intends to register. This will /// cause the loader to defer loading of this module until all other modules have been loaded. If no other /// module has registered the interface by then, this module will be activated, else it will remain inactive, /// letting the other module take over. This should return non-null ONLY in modules that are intended to be /// easily replaceable, e.g. stub implementations that the developer expects to be replaced by third party /// provided modules. /// </summary> /// <value> /// The replaceable interface. /// </value> public Type ReplaceableInterface { get; private set; } /// <summary> /// Called as the instance is closed. /// </summary> public void Close() { } /// <value> /// The name of the module /// </value> /// <summary> /// Gets the module name. /// </summary> public string Name { get { return "UserProfileModule"; } } #endregion IRegionModuleBase implementation #region Region Event Handlers /// <summary> /// Raises the new client event. /// </summary> /// <param name='client'> /// Client. /// </param> void OnNewClient(IClientAPI client) { //Profile client.OnRequestAvatarProperties += RequestAvatarProperties; client.OnUpdateAvatarProperties += AvatarPropertiesUpdate; client.OnAvatarInterestUpdate += AvatarInterestsUpdate; // Classifieds client.AddGenericPacketHandler("avatarclassifiedsrequest", ClassifiedsRequest); client.OnClassifiedInfoUpdate += ClassifiedInfoUpdate; client.OnClassifiedInfoRequest += ClassifiedInfoRequest; client.OnClassifiedDelete += ClassifiedDelete; // Picks client.AddGenericPacketHandler("avatarpicksrequest", PicksRequest); client.AddGenericPacketHandler("pickinforequest", PickInfoRequest); client.OnPickInfoUpdate += PickInfoUpdate; client.OnPickDelete += PickDelete; // Notes client.AddGenericPacketHandler("avatarnotesrequest", NotesRequest); client.OnAvatarNotesUpdate += NotesUpdate; // Preferences client.OnUserInfoRequest += UserPreferencesRequest; client.OnUpdateUserInfo += UpdateUserPreferences; } #endregion Region Event Handlers #region Classified /// /// <summary> /// Handles the avatar classifieds request. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='method'> /// Method. /// </param> /// <param name='args'> /// Arguments. /// </param> public void ClassifiedsRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID targetID; UUID.TryParse(args[0], out targetID); // Can't handle NPC yet... ScenePresence p = FindPresence(targetID); if (null != p) { if (p.PresenceType == PresenceType.Npc) return; } string serverURI = string.Empty; GetUserProfileServerURI(targetID, out serverURI); UUID creatorId = UUID.Zero; OSDMap parameters= new OSDMap(); UUID.TryParse(args[0], out creatorId); parameters.Add("creatorId", OSD.FromUUID(creatorId)); OSD Params = (OSD)parameters; if(!JsonRpcRequest(ref Params, "avatarclassifiedsrequest", serverURI, UUID.Random().ToString())) { // Error Handling here! // if(parameters.ContainsKey("message") } parameters = (OSDMap)Params; OSDArray list = (OSDArray)parameters["result"]; Dictionary<UUID, string> classifieds = new Dictionary<UUID, string>(); foreach(OSD map in list) { OSDMap m = (OSDMap)map; UUID cid = m["classifieduuid"].AsUUID(); string name = m["name"].AsString(); classifieds[cid] = name; lock (m_classifiedCache) { if (!m_classifiedCache.ContainsKey(cid)) { m_classifiedCache.Add(cid,creatorId); m_classifiedInterest.Add(cid, 0); } m_classifiedInterest[cid]++; } } remoteClient.SendAvatarClassifiedReply(new UUID(args[0]), classifieds); } public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient) { UUID target = remoteClient.AgentId; UserClassifiedAdd ad = new UserClassifiedAdd(); ad.ClassifiedId = queryClassifiedID; lock (m_classifiedCache) { if (m_classifiedCache.ContainsKey(queryClassifiedID)) { target = m_classifiedCache[queryClassifiedID]; m_classifiedInterest[queryClassifiedID] --; if (m_classifiedInterest[queryClassifiedID] == 0) { m_classifiedInterest.Remove(queryClassifiedID); m_classifiedCache.Remove(queryClassifiedID); } } } string serverURI = string.Empty; GetUserProfileServerURI(target, out serverURI); object Ad = (object)ad; if(!JsonRpcRequest(ref Ad, "classifieds_info_query", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error getting classified info", false); return; } ad = (UserClassifiedAdd) Ad; if(ad.CreatorId == UUID.Zero) return; Vector3 globalPos = new Vector3(); Vector3.TryParse(ad.GlobalPos, out globalPos); remoteClient.SendClassifiedInfoReply(ad.ClassifiedId, ad.CreatorId, (uint)ad.CreationDate, (uint)ad.ExpirationDate, (uint)ad.Category, ad.Name, ad.Description, ad.ParcelId, (uint)ad.ParentEstate, ad.SnapshotId, ad.SimName, globalPos, ad.ParcelName, ad.Flags, ad.Price); } /// <summary> /// Classifieds info update. /// </summary> /// <param name='queryclassifiedID'> /// Queryclassified I. /// </param> /// <param name='queryCategory'> /// Query category. /// </param> /// <param name='queryName'> /// Query name. /// </param> /// <param name='queryDescription'> /// Query description. /// </param> /// <param name='queryParcelID'> /// Query parcel I. /// </param> /// <param name='queryParentEstate'> /// Query parent estate. /// </param> /// <param name='querySnapshotID'> /// Query snapshot I. /// </param> /// <param name='queryGlobalPos'> /// Query global position. /// </param> /// <param name='queryclassifiedFlags'> /// Queryclassified flags. /// </param> /// <param name='queryclassifiedPrice'> /// Queryclassified price. /// </param> /// <param name='remoteClient'> /// Remote client. /// </param> public void ClassifiedInfoUpdate(UUID queryclassifiedID, uint queryCategory, string queryName, string queryDescription, UUID queryParcelID, uint queryParentEstate, UUID querySnapshotID, Vector3 queryGlobalPos, byte queryclassifiedFlags, int queryclassifiedPrice, IClientAPI remoteClient) { UserClassifiedAdd ad = new UserClassifiedAdd(); Scene s = (Scene) remoteClient.Scene; Vector3 pos = remoteClient.SceneAgent.AbsolutePosition; ILandObject land = s.LandChannel.GetLandObject(pos.X, pos.Y); ScenePresence p = FindPresence(remoteClient.AgentId); // Vector3 avaPos = p.AbsolutePosition; string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); if (land == null) { ad.ParcelName = string.Empty; } else { ad.ParcelName = land.LandData.Name; } ad.CreatorId = remoteClient.AgentId; ad.ClassifiedId = queryclassifiedID; ad.Category = Convert.ToInt32(queryCategory); ad.Name = queryName; ad.Description = queryDescription; ad.ParentEstate = Convert.ToInt32(queryParentEstate); ad.SnapshotId = querySnapshotID; ad.SimName = remoteClient.Scene.RegionInfo.RegionName; ad.GlobalPos = queryGlobalPos.ToString (); ad.Flags = queryclassifiedFlags; ad.Price = queryclassifiedPrice; ad.ParcelId = p.currentParcelUUID; object Ad = ad; OSD.SerializeMembers(Ad); if(!JsonRpcRequest(ref Ad, "classified_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating classified", false); } } /// <summary> /// Classifieds delete. /// </summary> /// <param name='queryClassifiedID'> /// Query classified I. /// </param> /// <param name='remoteClient'> /// Remote client. /// </param> public void ClassifiedDelete(UUID queryClassifiedID, IClientAPI remoteClient) { string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); UUID classifiedId; OSDMap parameters= new OSDMap(); UUID.TryParse(queryClassifiedID.ToString(), out classifiedId); parameters.Add("classifiedId", OSD.FromUUID(classifiedId)); OSD Params = (OSD)parameters; if(!JsonRpcRequest(ref Params, "classified_delete", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error classified delete", false); } parameters = (OSDMap)Params; } #endregion Classified #region Picks /// <summary> /// Handles the avatar picks request. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='method'> /// Method. /// </param> /// <param name='args'> /// Arguments. /// </param> public void PicksRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; UUID targetId; UUID.TryParse(args[0], out targetId); // Can't handle NPC yet... ScenePresence p = FindPresence(targetId); if (null != p) { if (p.PresenceType == PresenceType.Npc) return; } string serverURI = string.Empty; GetUserProfileServerURI(targetId, out serverURI); OSDMap parameters= new OSDMap(); parameters.Add("creatorId", OSD.FromUUID(targetId)); OSD Params = (OSD)parameters; if(!JsonRpcRequest(ref Params, "avatarpicksrequest", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error requesting picks", false); return; } parameters = (OSDMap)Params; OSDArray list = (OSDArray)parameters["result"]; Dictionary<UUID, string> picks = new Dictionary<UUID, string>(); foreach(OSD map in list) { OSDMap m = (OSDMap)map; UUID cid = m["pickuuid"].AsUUID(); string name = m["name"].AsString(); m_log.DebugFormat("[PROFILES]: PicksRequest {0}", name); picks[cid] = name; } remoteClient.SendAvatarPicksReply(new UUID(args[0]), picks); } /// <summary> /// Handles the pick info request. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='method'> /// Method. /// </param> /// <param name='args'> /// Arguments. /// </param> public void PickInfoRequest(Object sender, string method, List<String> args) { if (!(sender is IClientAPI)) return; UUID targetID; UUID.TryParse(args[0], out targetID); string serverURI = string.Empty; GetUserProfileServerURI(targetID, out serverURI); IClientAPI remoteClient = (IClientAPI)sender; UserProfilePick pick = new UserProfilePick(); UUID.TryParse(args[0], out pick.CreatorId); UUID.TryParse(args[1], out pick.PickId); object Pick = (object)pick; if(!JsonRpcRequest(ref Pick, "pickinforequest", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error selecting pick", false); } pick = (UserProfilePick) Pick; if(pick.SnapshotId == UUID.Zero) { // In case of a new UserPick, the data may not be ready and we would send wrong data, skip it... m_log.DebugFormat("[PROFILES]: PickInfoRequest: SnapshotID is {0}", UUID.Zero.ToString()); return; } Vector3 globalPos; Vector3.TryParse(pick.GlobalPos,out globalPos); m_log.DebugFormat("[PROFILES]: PickInfoRequest: {0} : {1}", pick.Name.ToString(), pick.SnapshotId.ToString()); remoteClient.SendPickInfoReply(pick.PickId,pick.CreatorId,pick.TopPick,pick.ParcelId,pick.Name, pick.Desc,pick.SnapshotId,pick.User,pick.OriginalName,pick.SimName, globalPos,pick.SortOrder,pick.Enabled); } /// <summary> /// Updates the userpicks /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='pickID'> /// Pick I. /// </param> /// <param name='creatorID'> /// the creator of the pick /// </param> /// <param name='topPick'> /// Top pick. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='desc'> /// Desc. /// </param> /// <param name='snapshotID'> /// Snapshot I. /// </param> /// <param name='sortOrder'> /// Sort order. /// </param> /// <param name='enabled'> /// Enabled. /// </param> public void PickInfoUpdate(IClientAPI remoteClient, UUID pickID, UUID creatorID, bool topPick, string name, string desc, UUID snapshotID, int sortOrder, bool enabled) { m_log.DebugFormat("[PROFILES]: Start PickInfoUpdate Name: {0} PickId: {1} SnapshotId: {2}", name, pickID.ToString(), snapshotID.ToString()); UserProfilePick pick = new UserProfilePick(); string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); ScenePresence p = FindPresence(remoteClient.AgentId); Vector3 avaPos = p.AbsolutePosition; // Getting the global position for the Avatar Vector3 posGlobal = new Vector3(remoteClient.Scene.RegionInfo.RegionLocX*Constants.RegionSize + avaPos.X, remoteClient.Scene.RegionInfo.RegionLocY*Constants.RegionSize + avaPos.Y, avaPos.Z); string landOwnerName = string.Empty; ILandObject land = p.Scene.LandChannel.GetLandObject(avaPos.X, avaPos.Y); if(land.LandData.IsGroupOwned) { IGroupsModule groupMod = p.Scene.RequestModuleInterface<IGroupsModule>(); UUID groupId = land.LandData.GroupID; GroupRecord groupRecord = groupMod.GetGroupRecord(groupId); landOwnerName = groupRecord.GroupName; } else { IUserAccountService accounts = p.Scene.RequestModuleInterface<IUserAccountService>(); UserAccount user = accounts.GetUserAccount(p.Scene.RegionInfo.ScopeID, land.LandData.OwnerID); landOwnerName = user.Name; } pick.PickId = pickID; pick.CreatorId = creatorID; pick.TopPick = topPick; pick.Name = name; pick.Desc = desc; pick.ParcelId = p.currentParcelUUID; pick.SnapshotId = snapshotID; pick.User = landOwnerName; pick.SimName = remoteClient.Scene.RegionInfo.RegionName; pick.GlobalPos = posGlobal.ToString(); pick.SortOrder = sortOrder; pick.Enabled = enabled; object Pick = (object)pick; if(!JsonRpcRequest(ref Pick, "picks_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating pick", false); } m_log.DebugFormat("[PROFILES]: Finish PickInfoUpdate {0} {1}", pick.Name, pick.PickId.ToString()); } /// <summary> /// Delete a Pick /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='queryPickID'> /// Query pick I. /// </param> public void PickDelete(IClientAPI remoteClient, UUID queryPickID) { string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); OSDMap parameters= new OSDMap(); parameters.Add("pickId", OSD.FromUUID(queryPickID)); OSD Params = (OSD)parameters; if(!JsonRpcRequest(ref Params, "picks_delete", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error picks delete", false); } } #endregion Picks #region Notes /// <summary> /// Handles the avatar notes request. /// </summary> /// <param name='sender'> /// Sender. /// </param> /// <param name='method'> /// Method. /// </param> /// <param name='args'> /// Arguments. /// </param> public void NotesRequest(Object sender, string method, List<String> args) { UserProfileNotes note = new UserProfileNotes(); if (!(sender is IClientAPI)) return; IClientAPI remoteClient = (IClientAPI)sender; string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); note.UserId = remoteClient.AgentId; UUID.TryParse(args[0], out note.TargetId); object Note = (object)note; if(!JsonRpcRequest(ref Note, "avatarnotesrequest", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error requesting note", false); } note = (UserProfileNotes) Note; remoteClient.SendAvatarNotesReply(note.TargetId, note.Notes); } /// <summary> /// Avatars the notes update. /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='queryTargetID'> /// Query target I. /// </param> /// <param name='queryNotes'> /// Query notes. /// </param> public void NotesUpdate(IClientAPI remoteClient, UUID queryTargetID, string queryNotes) { UserProfileNotes note = new UserProfileNotes(); note.UserId = remoteClient.AgentId; note.TargetId = queryTargetID; note.Notes = queryNotes; string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); object Note = note; if(!JsonRpcRequest(ref Note, "avatar_notes_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating note", false); } } #endregion Notes #region User Preferences /// <summary> /// Updates the user preferences. /// </summary> /// <param name='imViaEmail'> /// Im via email. /// </param> /// <param name='visible'> /// Visible. /// </param> /// <param name='remoteClient'> /// Remote client. /// </param> public void UpdateUserPreferences(bool imViaEmail, bool visible, IClientAPI remoteClient) { UserPreferences pref = new UserPreferences(); pref.UserId = remoteClient.AgentId; pref.IMViaEmail = imViaEmail; pref.Visible = visible; string serverURI = string.Empty; bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI); object Pref = pref; if(!JsonRpcRequest(ref Pref, "user_preferences_update", serverURI, UUID.Random().ToString())) { m_log.InfoFormat("[PROFILES]: UserPreferences update error"); remoteClient.SendAgentAlertMessage("Error updating preferences", false); return; } } /// <summary> /// Users the preferences request. /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> public void UserPreferencesRequest(IClientAPI remoteClient) { UserPreferences pref = new UserPreferences(); pref.UserId = remoteClient.AgentId; string serverURI = string.Empty; bool foreign = GetUserProfileServerURI(remoteClient.AgentId, out serverURI); object Pref = (object)pref; if(!JsonRpcRequest(ref Pref, "user_preferences_request", serverURI, UUID.Random().ToString())) { m_log.InfoFormat("[PROFILES]: UserPreferences request error"); remoteClient.SendAgentAlertMessage("Error requesting preferences", false); return; } pref = (UserPreferences) Pref; remoteClient.SendUserInfoReply(pref.IMViaEmail, pref.Visible, pref.EMail); } #endregion User Preferences #region Avatar Properties /// <summary> /// Update the avatars interests . /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='wantmask'> /// Wantmask. /// </param> /// <param name='wanttext'> /// Wanttext. /// </param> /// <param name='skillsmask'> /// Skillsmask. /// </param> /// <param name='skillstext'> /// Skillstext. /// </param> /// <param name='languages'> /// Languages. /// </param> public void AvatarInterestsUpdate(IClientAPI remoteClient, uint wantmask, string wanttext, uint skillsmask, string skillstext, string languages) { UserProfileProperties prop = new UserProfileProperties(); prop.UserId = remoteClient.AgentId; prop.WantToMask = (int)wantmask; prop.WantToText = wanttext; prop.SkillsMask = (int)skillsmask; prop.SkillsText = skillstext; prop.Language = languages; string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); object Param = prop; if(!JsonRpcRequest(ref Param, "avatar_interests_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating interests", false); } } public void RequestAvatarProperties(IClientAPI remoteClient, UUID avatarID) { if ( String.IsNullOrEmpty(avatarID.ToString()) || String.IsNullOrEmpty(remoteClient.AgentId.ToString())) { // Looking for a reason that some viewers are sending null Id's m_log.DebugFormat("[PROFILES]: This should not happen remoteClient.AgentId {0} - avatarID {1}", remoteClient.AgentId, avatarID); return; } // Can't handle NPC yet... ScenePresence p = FindPresence(avatarID); if (null != p) { if (p.PresenceType == PresenceType.Npc) return; } string serverURI = string.Empty; bool foreign = GetUserProfileServerURI(avatarID, out serverURI); UserAccount account = null; Dictionary<string,object> userInfo; if (!foreign) { account = Scene.UserAccountService.GetUserAccount(Scene.RegionInfo.ScopeID, avatarID); } else { userInfo = new Dictionary<string, object>(); } Byte[] charterMember = new Byte[1]; string born = String.Empty; uint flags = 0x00; if (null != account) { if (account.UserTitle == "") { charterMember[0] = (Byte)((account.UserFlags & 0xf00) >> 8); } else { charterMember = Utils.StringToBytes(account.UserTitle); } born = Util.ToDateTime(account.Created).ToString( "M/d/yyyy", CultureInfo.InvariantCulture); flags = (uint)(account.UserFlags & 0xff); } else { if (GetUserAccountData(avatarID, out userInfo) == true) { if ((string)userInfo["user_title"] == "") { charterMember[0] = (Byte)(((Byte)userInfo["user_flags"] & 0xf00) >> 8); } else { charterMember = Utils.StringToBytes((string)userInfo["user_title"]); } int val_born = (int)userInfo["user_created"]; born = Util.ToDateTime(val_born).ToString( "M/d/yyyy", CultureInfo.InvariantCulture); // picky, picky int val_flags = (int)userInfo["user_flags"]; flags = (uint)(val_flags & 0xff); } } UserProfileProperties props = new UserProfileProperties(); string result = string.Empty; props.UserId = avatarID; GetProfileData(ref props, out result); remoteClient.SendAvatarProperties(props.UserId, props.AboutText, born, charterMember , props.FirstLifeText, flags, props.FirstLifeImageId, props.ImageId, props.WebUrl, props.PartnerId); remoteClient.SendAvatarInterestsReply(props.UserId, (uint)props.WantToMask, props.WantToText, (uint)props.SkillsMask, props.SkillsText, props.Language); } /// <summary> /// Updates the avatar properties. /// </summary> /// <param name='remoteClient'> /// Remote client. /// </param> /// <param name='newProfile'> /// New profile. /// </param> public void AvatarPropertiesUpdate(IClientAPI remoteClient, UserProfileData newProfile) { if (remoteClient.AgentId == newProfile.ID) { UserProfileProperties prop = new UserProfileProperties(); prop.UserId = remoteClient.AgentId; prop.WebUrl = newProfile.ProfileUrl; prop.ImageId = newProfile.Image; prop.AboutText = newProfile.AboutText; prop.FirstLifeImageId = newProfile.FirstLifeImage; prop.FirstLifeText = newProfile.FirstLifeAboutText; string serverURI = string.Empty; GetUserProfileServerURI(remoteClient.AgentId, out serverURI); object Prop = prop; if(!JsonRpcRequest(ref Prop, "avatar_properties_update", serverURI, UUID.Random().ToString())) { remoteClient.SendAgentAlertMessage( "Error updating properties", false); } RequestAvatarProperties(remoteClient, newProfile.ID); } } /// <summary> /// Gets the profile data. /// </summary> /// <returns> /// The profile data. /// </returns> /// <param name='userID'> /// User I. /// </param> bool GetProfileData(ref UserProfileProperties properties, out string message) { // Can't handle NPC yet... ScenePresence p = FindPresence(properties.UserId); if (null != p) { if (p.PresenceType == PresenceType.Npc) { message = "Id points to NPC"; return false; } } string serverURI = string.Empty; GetUserProfileServerURI(properties.UserId, out serverURI); // This is checking a friend on the home grid // Not HG friend if ( String.IsNullOrEmpty(serverURI)) { message = "No Presence - foreign friend"; return false; } object Prop = (object)properties; JsonRpcRequest(ref Prop, "avatar_properties_request", serverURI, UUID.Random().ToString()); properties = (UserProfileProperties)Prop; message = "Success"; return true; } #endregion Avatar Properties #region Utils bool GetImageAssets(UUID avatarId) { string profileServerURI = string.Empty; string assetServerURI = string.Empty; bool foreign = GetUserProfileServerURI(avatarId, out profileServerURI); if(!foreign) return true; assetServerURI = UserManagementModule.GetUserServerURL(avatarId, "AssetServerURI"); OSDMap parameters= new OSDMap(); parameters.Add("avatarId", OSD.FromUUID(avatarId)); OSD Params = (OSD)parameters; if(!JsonRpcRequest(ref Params, "image_assets_request", profileServerURI, UUID.Random().ToString())) { // Error Handling here! // if(parameters.ContainsKey("message") return false; } parameters = (OSDMap)Params; OSDArray list = (OSDArray)parameters["result"]; foreach(OSD asset in list) { OSDString assetId = (OSDString)asset; Scene.AssetService.Get(string.Format("{0}/{1}",assetServerURI, assetId.AsString())); } return true; } /// <summary> /// Gets the user account data. /// </summary> /// <returns> /// The user profile data. /// </returns> /// <param name='userID'> /// If set to <c>true</c> user I. /// </param> /// <param name='userInfo'> /// If set to <c>true</c> user info. /// </param> bool GetUserAccountData(UUID userID, out Dictionary<string, object> userInfo) { Dictionary<string,object> info = new Dictionary<string, object>(); if (UserManagementModule.IsLocalGridUser(userID)) { // Is local IUserAccountService uas = Scene.UserAccountService; UserAccount account = uas.GetUserAccount(Scene.RegionInfo.ScopeID, userID); info["user_flags"] = account.UserFlags; info["user_created"] = account.Created; if (!String.IsNullOrEmpty(account.UserTitle)) info["user_title"] = account.UserTitle; else info["user_title"] = ""; userInfo = info; return false; } else { // Is Foreign string home_url = UserManagementModule.GetUserServerURL(userID, "HomeURI"); if (String.IsNullOrEmpty(home_url)) { info["user_flags"] = 0; info["user_created"] = 0; info["user_title"] = "Unavailable"; userInfo = info; return true; } UserAgentServiceConnector uConn = new UserAgentServiceConnector(home_url); Dictionary<string, object> account = uConn.GetUserInfo(userID); if (account.Count > 0) { if (account.ContainsKey("user_flags")) info["user_flags"] = account["user_flags"]; else info["user_flags"] = ""; if (account.ContainsKey("user_created")) info["user_created"] = account["user_created"]; else info["user_created"] = ""; info["user_title"] = "HG Visitor"; } else { info["user_flags"] = 0; info["user_created"] = 0; info["user_title"] = "HG Visitor"; } userInfo = info; return true; } } /// <summary> /// Gets the user profile server UR. /// </summary> /// <returns> /// The user profile server UR. /// </returns> /// <param name='userID'> /// If set to <c>true</c> user I. /// </param> /// <param name='serverURI'> /// If set to <c>true</c> server UR. /// </param> bool GetUserProfileServerURI(UUID userID, out string serverURI) { bool local; local = UserManagementModule.IsLocalGridUser(userID); if (!local) { serverURI = UserManagementModule.GetUserServerURL(userID, "ProfileServerURI"); // Is Foreign return true; } else { serverURI = ProfileServerUri; // Is local return false; } } /// <summary> /// Finds the presence. /// </summary> /// <returns> /// The presence. /// </returns> /// <param name='clientID'> /// Client I. /// </param> ScenePresence FindPresence(UUID clientID) { ScenePresence p; p = Scene.GetScenePresence(clientID); if (p != null && !p.IsChildAgent) return p; return null; } #endregion Util #region Web Util /// <summary> /// Sends json-rpc request with a serializable type. /// </summary> /// <returns> /// OSD Map. /// </returns> /// <param name='parameters'> /// Serializable type . /// </param> /// <param name='method'> /// Json-rpc method to call. /// </param> /// <param name='uri'> /// URI of json-rpc service. /// </param> /// <param name='jsonId'> /// Id for our call. /// </param> bool JsonRpcRequest(ref object parameters, string method, string uri, string jsonId) { if (jsonId == null) throw new ArgumentNullException ("jsonId"); if (uri == null) throw new ArgumentNullException ("uri"); if (method == null) throw new ArgumentNullException ("method"); if (parameters == null) throw new ArgumentNullException ("parameters"); // Prep our payload OSDMap json = new OSDMap(); json.Add("jsonrpc", OSD.FromString("2.0")); json.Add("id", OSD.FromString(jsonId)); json.Add("method", OSD.FromString(method)); // Experiment json.Add("params", OSD.SerializeMembers(parameters)); string jsonRequestData = OSDParser.SerializeJsonString(json); byte[] content = Encoding.UTF8.GetBytes(jsonRequestData); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); // webRequest.Credentials = new NetworkCredential(rpcUser, rpcPass); webRequest.ContentType = "application/json-rpc"; webRequest.Method = "POST"; Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(content, 0, content.Length); dataStream.Close(); WebResponse webResponse = null; try { webResponse = webRequest.GetResponse(); } catch (WebException e) { Console.WriteLine("Web Error" + e.Message); Console.WriteLine ("Please check input"); return false; } Stream rstream = webResponse.GetResponseStream(); OSDMap mret = (OSDMap)OSDParser.DeserializeJson(rstream); if (mret.ContainsKey("error")) return false; // get params... OSD.DeserializeMembers(ref parameters, (OSDMap) mret["result"]); return true; } /// <summary> /// Sends json-rpc request with OSD parameter. /// </summary> /// <returns> /// The rpc request. /// </returns> /// <param name='data'> /// data - incoming as parameters, outgong as result/error /// </param> /// <param name='method'> /// Json-rpc method to call. /// </param> /// <param name='uri'> /// URI of json-rpc service. /// </param> /// <param name='jsonId'> /// If set to <c>true</c> json identifier. /// </param> bool JsonRpcRequest(ref OSD data, string method, string uri, string jsonId) { OSDMap map = new OSDMap(); map["jsonrpc"] = "2.0"; if(string.IsNullOrEmpty(jsonId)) map["id"] = UUID.Random().ToString(); else map["id"] = jsonId; map["method"] = method; map["params"] = data; string jsonRequestData = OSDParser.SerializeJsonString(map); byte[] content = Encoding.UTF8.GetBytes(jsonRequestData); HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.ContentType = "application/json-rpc"; webRequest.Method = "POST"; Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(content, 0, content.Length); dataStream.Close(); WebResponse webResponse = null; try { webResponse = webRequest.GetResponse(); } catch (WebException e) { Console.WriteLine("Web Error" + e.Message); Console.WriteLine ("Please check input"); return false; } Stream rstream = webResponse.GetResponseStream(); OSDMap response = new OSDMap(); try { response = (OSDMap)OSDParser.DeserializeJson(rstream); } catch (Exception e) { m_log.DebugFormat("[PROFILES]: JsonRpcRequest Error {0} - remote user with legacy profiles?", e.Message); return false; } if(response.ContainsKey("error")) { data = response["error"]; return false; } data = response; return true; } #endregion Web Util } }
// created on 18/5/2002 at 01:25 // Npgsql.NpgsqlParameter.cs // // Author: // Francisco Jr. (fxjrlists@yahoo.com.br) // // Copyright (C) 2002 The Npgsql Development Team // npgsql-general@gborg.postgresql.org // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Reflection; using System.Resources; using Revenj.DatabasePersistence.Postgres.NpgsqlTypes; namespace Revenj.DatabasePersistence.Postgres.Npgsql { ///<summary> /// This class represents a parameter to a command that will be sent to server ///</summary> public sealed class NpgsqlParameter : DbParameter, ICloneable { // Fields to implement IDbDataParameter interface. private byte precision = 0; private byte scale = 0; private Int32 size = 0; // Fields to implement IDataParameter //private NpgsqlDbType npgsqldb_type = NpgsqlDbType.Text; //private DbType db_type = DbType.String; private NpgsqlNativeTypeInfo type_info; private NpgsqlBackendTypeInfo backendTypeInfo; private ParameterDirection direction = ParameterDirection.Input; private Boolean is_nullable = false; private String m_Name = String.Empty; private String source_column = String.Empty; private DataRowVersion source_version = DataRowVersion.Current; private Object value = null; private Object npgsqlValue = null; private Boolean sourceColumnNullMapping; private static readonly ResourceManager resman = new ResourceManager(MethodBase.GetCurrentMethod().DeclaringType); private Boolean useCast = false; private static readonly NpgsqlNativeTypeInfo defaultTypeInfo = NpgsqlTypesHelper.GetNativeTypeInfo(typeof(String)); private const string Exception_ImpossibleToCast = "Can't cast {0} into any valid DbType."; private const string Exception_ParameterTypeIsOnlyArray = "Cannot set NpgsqlDbType to just Array, Binary-Or with the element type (e.g. Array of Box is NpgsqlDbType.Array | NpgsqlDbType.Box)."; /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> class. /// </summary> public NpgsqlParameter() { } /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// class with the parameter m_Name and a value of the new <b>NpgsqlParameter</b>. /// </summary> /// <param m_Name="parameterName">The m_Name of the parameter to map.</param> /// <param m_Name="value">An <see cref="System.Object">Object</see> that is the value of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see>.</param> /// <remarks> /// <p>When you specify an <see cref="System.Object">Object</see> /// in the value parameter, the <see cref="System.Data.DbType">DbType</see> is /// inferred from the .NET Framework type of the <b>Object</b>.</p> /// <p>When using this constructor, you must be aware of a possible misuse of the constructor which takes a DbType parameter. /// This happens when calling this constructor passing an int 0 and the compiler thinks you are passing a value of DbType. /// Use <code> Convert.ToInt32(value) </code> for example to have compiler calling the correct constructor.</p> /// </remarks> public NpgsqlParameter(String parameterName, object value) { this.ParameterName = parameterName; this.Value = value; } /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// class with the parameter m_Name and the data type. /// </summary> /// <param m_Name="parameterName">The m_Name of the parameter to map.</param> /// <param m_Name="parameterType">One of the <see cref="System.Data.DbType">DbType</see> values.</param> public NpgsqlParameter(String parameterName, NpgsqlDbType parameterType) : this(parameterName, parameterType, 0, String.Empty) { } public NpgsqlParameter(String parameterName, DbType parameterType) : this(parameterName, NpgsqlTypesHelper.GetNativeTypeInfo(parameterType).NpgsqlDbType, 0, String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// class with the parameter m_Name, the <see cref="System.Data.DbType">DbType</see>, and the size. /// </summary> /// <param m_Name="parameterName">The m_Name of the parameter to map.</param> /// <param m_Name="parameterType">One of the <see cref="System.Data.DbType">DbType</see> values.</param> /// <param m_Name="size">The length of the parameter.</param> public NpgsqlParameter(String parameterName, NpgsqlDbType parameterType, Int32 size) : this(parameterName, parameterType, size, String.Empty) { } public NpgsqlParameter(String parameterName, DbType parameterType, Int32 size) : this(parameterName, NpgsqlTypesHelper.GetNativeTypeInfo(parameterType).NpgsqlDbType, size, String.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// class with the parameter m_Name, the <see cref="System.Data.DbType">DbType</see>, the size, /// and the source column m_Name. /// </summary> /// <param m_Name="parameterName">The m_Name of the parameter to map.</param> /// <param m_Name="parameterType">One of the <see cref="System.Data.DbType">DbType</see> values.</param> /// <param m_Name="size">The length of the parameter.</param> /// <param m_Name="sourceColumn">The m_Name of the source column.</param> public NpgsqlParameter(String parameterName, NpgsqlDbType parameterType, Int32 size, String sourceColumn) { this.ParameterName = parameterName; NpgsqlDbType = parameterType; //Allow the setter to catch any exceptions. this.size = size; source_column = sourceColumn; } public NpgsqlParameter(String parameterName, DbType parameterType, Int32 size, String sourceColumn) : this(parameterName, NpgsqlTypesHelper.GetNativeTypeInfo(parameterType).NpgsqlDbType, size, sourceColumn) { } /// <summary> /// Initializes a new instance of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// class with the parameter m_Name, the <see cref="System.Data.DbType">DbType</see>, the size, /// the source column m_Name, a <see cref="System.Data.ParameterDirection">ParameterDirection</see>, /// the precision of the parameter, the scale of the parameter, a /// <see cref="System.Data.DataRowVersion">DataRowVersion</see> to use, and the /// value of the parameter. /// </summary> /// <param m_Name="parameterName">The m_Name of the parameter to map.</param> /// <param m_Name="parameterType">One of the <see cref="System.Data.DbType">DbType</see> values.</param> /// <param m_Name="size">The length of the parameter.</param> /// <param m_Name="sourceColumn">The m_Name of the source column.</param> /// <param m_Name="direction">One of the <see cref="System.Data.ParameterDirection">ParameterDirection</see> values.</param> /// <param m_Name="isNullable"><b>true</b> if the value of the field can be null, otherwise <b>false</b>.</param> /// <param m_Name="precision">The total number of digits to the left and right of the decimal point to which /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> is resolved.</param> /// <param m_Name="scale">The total number of decimal places to which /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> is resolved.</param> /// <param m_Name="sourceVersion">One of the <see cref="System.Data.DataRowVersion">DataRowVersion</see> values.</param> /// <param m_Name="value">An <see cref="System.Object">Object</see> that is the value /// of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see>.</param> public NpgsqlParameter(String parameterName, NpgsqlDbType parameterType, Int32 size, String sourceColumn, ParameterDirection direction, bool isNullable, byte precision, byte scale, DataRowVersion sourceVersion, object value) { this.ParameterName = parameterName; this.Size = size; this.SourceColumn = sourceColumn; this.Direction = direction; this.IsNullable = isNullable; this.Precision = precision; this.Scale = scale; this.SourceVersion = sourceVersion; this.Value = value; if (this.value == null) { this.value = DBNull.Value; type_info = NpgsqlTypesHelper.GetNativeTypeInfo(typeof(String)); } else { NpgsqlDbType = parameterType; //allow the setter to catch exceptions if necessary. } } public NpgsqlParameter(String parameterName, DbType parameterType, Int32 size, String sourceColumn, ParameterDirection direction, bool isNullable, byte precision, byte scale, DataRowVersion sourceVersion, object value) : this( parameterName, NpgsqlTypesHelper.GetNativeTypeInfo(parameterType).NpgsqlDbType, size, sourceColumn, direction, isNullable, precision, scale, sourceVersion, value) { } // Implementation of IDbDataParameter /// <summary> /// Gets or sets the maximum number of digits used to represent the /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> property. /// </summary> /// <value>The maximum number of digits used to represent the /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> property. /// The default value is 0, which indicates that the data provider /// sets the precision for <b>Value</b>.</value> [Category("Data"), DefaultValue((Byte)0)] public Byte Precision { get { return precision; } set { precision = value; } } public Boolean UseCast { get { // Prevents casts to be added for null values when they aren't needed. if (!useCast && (value == DBNull.Value || value == null)) return false; //return useCast; //&& (value != DBNull.Value); // This check for Datetime.minvalue and maxvalue is needed in order to // workaround a problem when comparing date values with infinity. // This is a known issue with postgresql and it is reported here: // http://archives.postgresql.org/pgsql-general/2008-10/msg00535.php // Josh's solution to add cast is documented here: // http://pgfoundry.org/forum/message.php?msg_id=1004118 return useCast || DateTime.MinValue.Equals(value) || DateTime.MaxValue.Equals(value) || !NpgsqlTypesHelper.DefinedType(Value); } } /// <summary> /// Gets or sets the number of decimal places to which /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> is resolved. /// </summary> /// <value>The number of decimal places to which /// <see cref="Npgsql.NpgsqlParameter.Value">Value</see> is resolved. The default is 0.</value> [Category("Data"), DefaultValue((Byte)0)] public Byte Scale { get { return scale; } set { scale = value; } } /// <summary> /// Gets or sets the maximum size, in bytes, of the data within the column. /// </summary> /// <value>The maximum size, in bytes, of the data within the column. /// The default value is inferred from the parameter value.</value> [Category("Data"), DefaultValue(0)] public override Int32 Size { get { return size; } set { size = value; } } /// <summary> /// Gets or sets the <see cref="System.Data.DbType">DbType</see> of the parameter. /// </summary> /// <value>One of the <see cref="System.Data.DbType">DbType</see> values. The default is <b>String</b>.</value> [Category("Data"), RefreshProperties(RefreshProperties.All), DefaultValue(DbType.String)] public override DbType DbType { get { if (type_info == null) return defaultTypeInfo.DbType; else return TypeInfo.DbType; } // [TODO] Validate data type. set { useCast = value != DbType.Object; if (!NpgsqlTypesHelper.TryGetNativeTypeInfo(value, out type_info)) { throw new InvalidCastException(String.Format(Exception_ImpossibleToCast, value)); } } } /// <summary> /// Gets or sets the <see cref="System.Data.DbType">DbType</see> of the parameter. /// </summary> /// <value>One of the <see cref="System.Data.DbType">DbType</see> values. The default is <b>String</b>.</value> [Category("Data"), RefreshProperties(RefreshProperties.All), DefaultValue(NpgsqlDbType.Text)] public NpgsqlDbType NpgsqlDbType { get { if (type_info == null) return defaultTypeInfo.NpgsqlDbType; else return TypeInfo.NpgsqlDbType; } // [TODO] Validate data type. set { useCast = true; if (value == NpgsqlDbType.Array) { throw new ArgumentOutOfRangeException(Exception_ParameterTypeIsOnlyArray); } if (!NpgsqlTypesHelper.TryGetNativeTypeInfo(value, out type_info)) { throw new InvalidCastException(String.Format(Exception_ImpossibleToCast, value)); } } } internal NpgsqlNativeTypeInfo TypeInfo { get { if (type_info == null) { return defaultTypeInfo; } return type_info; } } /// <summary> /// Gets or sets a value indicating whether the parameter is input-only, /// output-only, bidirectional, or a stored procedure return value parameter. /// </summary> /// <value>One of the <see cref="System.Data.ParameterDirection">ParameterDirection</see> /// values. The default is <b>Input</b>.</value> [Category("Data"), DefaultValue(ParameterDirection.Input)] public override ParameterDirection Direction { get { return direction; } set { direction = value; } } /// <summary> /// Gets or sets a value indicating whether the parameter accepts null values. /// </summary> /// <value><b>true</b> if null values are accepted; otherwise, <b>false</b>. The default is <b>false</b>.</value> public override Boolean IsNullable { get { return is_nullable; } set { is_nullable = value; } } /// <summary> /// Gets or sets the m_Name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see>. /// </summary> /// <value>The m_Name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see>. /// The default is an empty string.</value> [DefaultValue("")] public override String ParameterName { get { return m_Name; } set { m_Name = value; if (value == null) { m_Name = String.Empty; } // no longer prefix with : so that the m_Name returned is the m_Name set m_Name = m_Name.Trim(); } } /// <summary> /// The m_Name scrubbed of any optional marker /// </summary> internal string CleanName { get { string name = ParameterName; if (name[0] == ':' || name[0] == '@') { return name.Length > 1 ? name.Substring(1) : string.Empty; } return name; } } /// <summary> /// Gets or sets the m_Name of the source column that is mapped to the /// <see cref="System.Data.DataSet">DataSet</see> and used for loading or /// returning the <see cref="Npgsql.NpgsqlParameter.Value">Value</see>. /// </summary> /// <value>The m_Name of the source column that is mapped to the /// <see cref="System.Data.DataSet">DataSet</see>. The default is an empty string.</value> [Category("Data"), DefaultValue("")] public override String SourceColumn { get { return source_column; } set { source_column = value; } } /// <summary> /// Gets or sets the <see cref="System.Data.DataRowVersion">DataRowVersion</see> /// to use when loading <see cref="Npgsql.NpgsqlParameter.Value">Value</see>. /// </summary> /// <value>One of the <see cref="System.Data.DataRowVersion">DataRowVersion</see> values. /// The default is <b>Current</b>.</value> [Category("Data"), DefaultValue(DataRowVersion.Current)] public override DataRowVersion SourceVersion { get { return source_version; } set { source_version = value; } } /// <summary> /// Gets or sets the value of the parameter. /// </summary> /// <value>An <see cref="System.Object">Object</see> that is the value of the parameter. /// The default value is null.</value> [TypeConverter(typeof(StringConverter)), Category("Data")] public override Object Value { get { return this.value; } // [TODO] Check and validate data type. set { if ((value == null) || (value == DBNull.Value)) { // don't really know what to do - leave default and do further exploration // Default type for null values is String. this.value = value; this.npgsqlValue = value; return; } if (type_info == null && !NpgsqlTypesHelper.TryGetNativeTypeInfo(value.GetType(), out type_info)) { throw new InvalidCastException(String.Format(Exception_ImpossibleToCast, value.GetType())); } if (backendTypeInfo == null && !NpgsqlTypesHelper.TryGetBackendTypeInfo(type_info.Name, out backendTypeInfo)) { throw new InvalidCastException(String.Format(Exception_ImpossibleToCast, value.GetType())); } else { this.npgsqlValue = backendTypeInfo.ConvertToProviderType(value); this.value = backendTypeInfo.ConvertToFrameworkType(npgsqlValue); } } } /// <summary> /// Gets or sets the value of the parameter. /// </summary> /// <value>An <see cref="System.Object">Object</see> that is the value of the parameter. /// The default value is null.</value> [TypeConverter(typeof(StringConverter)), Category("Data")] public Object NpgsqlValue { get { return npgsqlValue; } set { Value = value; } } public override void ResetDbType() { type_info = null; this.Value = Value; } public override bool SourceColumnNullMapping { get { return sourceColumnNullMapping; } set { sourceColumnNullMapping = value; } } /// <summary> /// Creates a new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> that /// is a copy of the current instance. /// </summary> /// <returns>A new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> that is a copy of this instance.</returns> public NpgsqlParameter Clone() { // use fields instead of properties // to avoid auto-initializing something like type_info NpgsqlParameter clone = new NpgsqlParameter(); clone.precision = precision; clone.scale = scale; clone.size = size; clone.type_info = type_info; clone.direction = direction; clone.is_nullable = is_nullable; clone.m_Name = m_Name; clone.source_column = source_column; clone.source_version = source_version; clone.value = value; clone.sourceColumnNullMapping = sourceColumnNullMapping; return clone; } object ICloneable.Clone() { return Clone(); } } }
// Copyright (c) 2013 Mark Pearce // http://opensource.org/licenses/MIT using System; using System.Globalization; namespace PasswordUtilities { /// <summary> /// Policy used to control generation of a randomly-salted password hash. /// </summary> public sealed class HashPolicy { // We want a large number of hash iterations because it makes any // incremental attack much slower. Speed is exactly what you don't // want in a password hash function. // This also has the effect of stretching the password and thereby // increasing its entropy - 2^X iterations increases the password's // entropy by X bits. // A good default is something that takes around 0.5-1.0 second // to execute. private const int WORK_FACTOR_DEFAULT = 14; // 2^14 hash iterations private const int WORK_FACTOR_MINIMUM = 0; private const int WORK_FACTOR_MAXIMUM = 24; // Other class constants. private const int SALT_MINIMUM_BYTES = 0; private const int SALT_MINIMUM_BYTES_SHA1 = 8; private const int SALT_DEFAULT_BYTES = 10; private const HashAlgorithm HASH_ALGORITHM_DEFAULT = HashAlgorithm.SHA1_160; private const StorageFormat HASH_STORAGE_DEFAULT = StorageFormat.Hexadecimal; private const string COMMAS_AND_ZERO_DECIMAL_PLACES = "N0"; private const int SHA1_NUMBER_OF_HASH_BYTES = 20; /// <summary> /// Use the default hash policy settings. /// </summary> public HashPolicy() { this.SetPolicy(HASH_ALGORITHM_DEFAULT, WORK_FACTOR_DEFAULT, HASH_STORAGE_DEFAULT, SALT_DEFAULT_BYTES); } /// <summary> /// Constructor for a non-default hash policy. /// </summary> /// <param name="hashAlgorithm"> /// Required hash algorithm. /// </param> public HashPolicy(HashAlgorithm hashAlgorithm) { this.SetPolicy(hashAlgorithm, WORK_FACTOR_DEFAULT, HASH_STORAGE_DEFAULT, SALT_DEFAULT_BYTES); } /// <summary> /// Constructor for a non-default hash policy. /// </summary> /// <param name="hashAlgorithm"> /// Required hash algorithm. /// </param> /// <param name="workFactor"> /// Number of hash iterations expressed as 2^WorkFactor. /// </param> public HashPolicy(HashAlgorithm hashAlgorithm, int workFactor) { this.SetPolicy(hashAlgorithm, workFactor, HASH_STORAGE_DEFAULT, SALT_DEFAULT_BYTES); } /// <summary> /// Constructor for a non-default hash policy. /// </summary> /// <param name="hashAlgorithm"> /// Required hash algorithm. /// </param> /// <param name="workFactor"> /// Number of hash iterations expressed as 2^WorkFactor. /// </param> /// <param name="storageFormat"> /// Storage encoding required. /// </param> public HashPolicy(HashAlgorithm hashAlgorithm, int workFactor, StorageFormat storageFormat) { this.SetPolicy(hashAlgorithm, workFactor, storageFormat, SALT_DEFAULT_BYTES); } /// <summary> /// Constructor for a non-default hash policy. /// </summary> /// <param name="hashAlgorithm"> /// Required hash algorithm. /// </param> /// <param name="workFactor"> /// Number of hash iterations expressed as 2^WorkFactor. /// </param> /// <param name="storageFormat"> /// Storage encoding required. /// </param> /// <param name="numberOfSaltBytes"> /// Number of salt bytes required. /// </param> public HashPolicy(HashAlgorithm hashAlgorithm, int workFactor, StorageFormat storageFormat, int numberOfSaltBytes) { this.SetPolicy(hashAlgorithm, workFactor, storageFormat, numberOfSaltBytes); } // Called from every constructor to setup and validate the hash policy. private void SetPolicy(HashAlgorithm hashAlgorithm, int workFactor, StorageFormat storageFormat, int numberOfSaltBytes) { this.HashMethod = hashAlgorithm; this.WorkFactor = workFactor; this.HashStorageFormat = storageFormat; this.NumberOfSaltBytes = numberOfSaltBytes; this.ValidatePolicy(); } /// <summary> /// Required hash algorithm. /// </summary> public HashAlgorithm HashMethod { get; set; } /// <summary> /// Number of hash iterations expressed as 2^WorkFactor. /// </summary> public Int32 WorkFactor { get; set; } /// <summary> /// Format in which to output encoded salt/hash for storage. /// </summary> public StorageFormat HashStorageFormat { get; set; } /// <summary> /// Required length of salt in bytes. /// </summary> public Int32 NumberOfSaltBytes { get; set; } /// <summary> /// Minimum length of salt in bytes. /// </summary> public Int32 MinimumNumberOfSaltBytes { get { if (this.HashMethod == HashAlgorithm.SHA1_160) { return SALT_MINIMUM_BYTES_SHA1; } else { return SALT_MINIMUM_BYTES; } } } // Validates this policy. private void ValidatePolicy() { // Hash algorithm must be within enumeration range. // Not using Enum.IsDefined for this validation check because // that loads reflection code and some cold type metadata. // See: http://blogs.msdn.com/b/brada/archive/2003/11/29/50903.aspx switch (this.HashMethod) { case HashAlgorithm.SHA1_160: break; case HashAlgorithm.SHA2_256: break; case HashAlgorithm.SHA3_512: throw new NotImplementedException(String.Format(CultureInfo.InvariantCulture, "SHA3-512 not implemented yet")); case HashAlgorithm.BCRYPT_192: throw new NotImplementedException(String.Format(CultureInfo.InvariantCulture, "BCRYPT-192 not implemented yet")); case HashAlgorithm.SCRYPT_512: throw new NotImplementedException(String.Format(CultureInfo.InvariantCulture, "SCRYPT-512 not implemented yet")); default: throw new ArgumentOutOfRangeException(String.Format(CultureInfo.InvariantCulture, "Unknown hash algorithm")); } // 2^X iterations increases the password hash entropy by X bits. if (this.WorkFactor < WORK_FACTOR_MINIMUM) { throw new ArgumentOutOfRangeException("workFactor", String.Format(CultureInfo.InvariantCulture, "Work factor must be at least {0}, not {1}", WORK_FACTOR_MINIMUM, this.WorkFactor.ToString(COMMAS_AND_ZERO_DECIMAL_PLACES, CultureInfo.InvariantCulture))); } // 2^X iterations increases the password hash entropy by X bits. if (this.WorkFactor > WORK_FACTOR_MAXIMUM) { throw new ArgumentOutOfRangeException("workFactor", String.Format(CultureInfo.InvariantCulture, "Work factor must be less than {0}, not {1}", WORK_FACTOR_MAXIMUM, this.WorkFactor.ToString(COMMAS_AND_ZERO_DECIMAL_PLACES, CultureInfo.InvariantCulture))); } // The .NET implemention of HMAC-SHA1-PKDBF2 insists on a minimum of 64 bits! if (this.HashMethod == HashAlgorithm.SHA1_160) { if (this.NumberOfSaltBytes < SALT_MINIMUM_BYTES_SHA1) { throw new ArgumentOutOfRangeException("numberOfSaltBytes", String.Format(CultureInfo.InvariantCulture, "Must have at least {0} salt bytes to use SHA1: not {1}", SALT_MINIMUM_BYTES_SHA1, this.NumberOfSaltBytes.ToString(COMMAS_AND_ZERO_DECIMAL_PLACES, CultureInfo.InvariantCulture))); } } // Recommended salt length nowadays is at least 64 bits. else { if (this.NumberOfSaltBytes < SALT_MINIMUM_BYTES) { throw new ArgumentOutOfRangeException("numberOfSaltBytes", String.Format(CultureInfo.InvariantCulture, "Must have at least {0} salt bytes: not {1}", SALT_MINIMUM_BYTES, this.NumberOfSaltBytes.ToString(COMMAS_AND_ZERO_DECIMAL_PLACES, CultureInfo.InvariantCulture))); } } // Storage format must be within enumeration range. // Not using Enum.IsDefined for this validation check because // that loads reflection code and some cold type metadata. // See: http://blogs.msdn.com/b/brada/archive/2003/11/29/50903.aspx switch (this.HashStorageFormat) { case StorageFormat.Hexadecimal: break; case StorageFormat.Base64: break; default: throw new ArgumentOutOfRangeException(String.Format(CultureInfo.InvariantCulture, "Can only store hash/salt using base64 or hexadecimal")); } } /// <summary> /// Estimates the added entropy added to the password by this hash. /// </summary> /// <returns> /// The hash entropy in bits. /// </returns> public double HashEntropy { get { return Math.Log(Math.Pow(2, this.WorkFactor), 2); } } /// <summary> /// Overrides the default ToString(). /// </summary> /// <returns> /// The work factor and storage format specified by this policy. /// </returns> public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "HashPolicy: " + this.WorkFactor.ToString(COMMAS_AND_ZERO_DECIMAL_PLACES) + " work factor, " + this.HashStorageFormat.ToString() + " storage"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.ObjectModel; using System.Management.Automation.Provider; using System.Reflection; using System.Linq; using System.Threading; using Dbg = System.Management.Automation; using System.Collections.Generic; namespace System.Management.Automation { /// <summary> /// Information about a loaded Cmdlet Provider. /// </summary> /// <remarks> /// A cmdlet provider may want to derive from this class to provide their /// own public members to expose to the user or to cache information related to the provider. /// </remarks> public class ProviderInfo { /// <summary> /// Gets the System.Type of the class that implements the provider. /// </summary> public Type ImplementingType { get; } /// <summary> /// Gets the help file path for the provider. /// </summary> public string HelpFile { get; } = string.Empty; /// <summary> /// The instance of session state the provider belongs to. /// </summary> private SessionState _sessionState; private string _fullName; /// <summary> /// Gets the name of the provider. /// </summary> public string Name { get; } /// <summary> /// Gets the full name of the provider including the pssnapin name if available. /// </summary> internal string FullName { get { string GetFullName(string name, string psSnapInName, string moduleName) { string result = name; if (!string.IsNullOrEmpty(psSnapInName)) { result = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}\\{1}", psSnapInName, name); } // After converting core snapins to load as modules, the providers will have Module property populated else if (!string.IsNullOrEmpty(moduleName)) { result = string.Format( System.Globalization.CultureInfo.InvariantCulture, "{0}\\{1}", moduleName, name); } return result; } return _fullName ?? (_fullName = GetFullName(Name, PSSnapInName, ModuleName)); } } /// <summary> /// Gets the Snap-in in which the provider is implemented. /// </summary> public PSSnapInInfo PSSnapIn { get; } /// <summary> /// Gets the pssnapin name that the provider is implemented in. /// </summary> internal string PSSnapInName { get { string result = null; if (PSSnapIn != null) { result = PSSnapIn.Name; } return result; } } internal string ApplicationBase { get { string psHome = null; try { psHome = Utils.DefaultPowerShellAppBase; } catch (System.Security.SecurityException) { psHome = null; } return psHome; } } /// <summary> /// Get the name of the module exporting this provider. /// </summary> public string ModuleName { get { if (PSSnapIn != null) return PSSnapIn.Name; if (Module != null) return Module.Name; return string.Empty; } } /// <summary> /// Gets the module the defined this provider. /// </summary> public PSModuleInfo Module { get; private set; } internal void SetModule(PSModuleInfo module) { Module = module; _fullName = null; } /// <summary> /// Gets or sets the description for the provider. /// </summary> public string Description { get; set; } /// <summary> /// Gets the capabilities that are implemented by the provider. /// </summary> public Provider.ProviderCapabilities Capabilities { get { if (!_capabilitiesRead) { try { // Get the CmdletProvider declaration attribute Type providerType = this.ImplementingType; var attrs = providerType.GetCustomAttributes<CmdletProviderAttribute>(false); var cmdletProviderAttributes = attrs as CmdletProviderAttribute[] ?? attrs.ToArray(); if (cmdletProviderAttributes.Length == 1) { _capabilities = cmdletProviderAttributes[0].ProviderCapabilities; _capabilitiesRead = true; } } catch (Exception) // Catch-all OK, 3rd party callout { // Assume no capabilities for now } } return _capabilities; } } private ProviderCapabilities _capabilities = ProviderCapabilities.None; private bool _capabilitiesRead; /// <summary> /// Gets or sets the home for the provider. /// </summary> /// <remarks> /// The location can be either a fully qualified provider path /// or an Msh path. This is the location that is substituted for the ~. /// </remarks> public string Home { get; set; } /// <summary> /// Gets an enumeration of drives that are available for /// this provider. /// </summary> public Collection<PSDriveInfo> Drives { get { return _sessionState.Drive.GetAllForProvider(FullName); } } /// <summary> /// A hidden drive for the provider that is used for setting /// the location to a provider-qualified path. /// </summary> private PSDriveInfo _hiddenDrive; /// <summary> /// Gets the hidden drive for the provider that is used /// for setting a location to a provider-qualified path. /// </summary> internal PSDriveInfo HiddenDrive { get { return _hiddenDrive; } } /// <summary> /// Gets the string representation of the instance which is the name of the provider. /// </summary> /// <returns> /// The name of the provider. If single-shell, the name is pssnapin-qualified. If custom-shell, /// the name is just the provider name. /// </returns> public override string ToString() { return FullName; } #if USE_TLS /// <summary> /// Allocates some thread local storage to an instance of the /// provider. We don't want to cache a single instance of the /// provider because that could lead to problems in a multi-threaded /// environment. /// </summary> private LocalDataStoreSlot instance = Thread.AllocateDataSlot(); #endif /// <summary> /// Gets or sets if the drive-root relative paths on drives of this provider /// are separated by a colon or not. /// /// This is true for all PSDrives on all platforms, except for filesystems on /// non-windows platforms. /// </summary> public bool VolumeSeparatedByColon { get; internal set; } = true; /// <summary> /// Constructs an instance of the class using an existing reference /// as a template. /// </summary> /// <param name="providerInfo"> /// The provider information to copy to this instance. /// </param> /// <remarks> /// This constructor should be used by derived types to easily copying /// the base class members from an existing ProviderInfo. /// This is designed for use by a <see cref="System.Management.Automation.Provider.CmdletProvider"/> /// during calls to their <see cref="System.Management.Automation.Provider.CmdletProvider.Start(ProviderInfo)"/> method. /// </remarks> /// <exception cref="ArgumentNullException"> /// If <paramref name="providerInfo"/> is null. /// </exception> protected ProviderInfo(ProviderInfo providerInfo) { if (providerInfo == null) { throw PSTraceSource.NewArgumentNullException("providerInfo"); } Name = providerInfo.Name; ImplementingType = providerInfo.ImplementingType; _capabilities = providerInfo._capabilities; Description = providerInfo.Description; _hiddenDrive = providerInfo._hiddenDrive; Home = providerInfo.Home; HelpFile = providerInfo.HelpFile; PSSnapIn = providerInfo.PSSnapIn; _sessionState = providerInfo._sessionState; VolumeSeparatedByColon = providerInfo.VolumeSeparatedByColon; } /// <summary> /// Constructor for the ProviderInfo class. /// </summary> /// <param name="sessionState"> /// The instance of session state that the provider is being added to. /// </param> /// <param name="implementingType"> /// The type that implements the provider /// </param> /// <param name="name"> /// The name of the provider. /// </param> /// <param name="helpFile"> /// The help file for the provider. /// </param> /// <param name="psSnapIn"> /// The Snap-In name for the provider. /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="sessionState"/> is null. /// </exception> /// <exception cref="ArgumentNullException"> /// If <paramref name="implementingType"/> is null. /// </exception> internal ProviderInfo( SessionState sessionState, Type implementingType, string name, string helpFile, PSSnapInInfo psSnapIn) : this(sessionState, implementingType, name, string.Empty, string.Empty, helpFile, psSnapIn) { } /// <summary> /// Constructor for the ProviderInfo class. /// </summary> /// <param name="sessionState"> /// The instance of session state that the provider is being added to. /// </param> /// <param name="implementingType"> /// The type that implements the provider /// </param> /// <param name="name"> /// The alternate name to use for the provider instead of the one specified /// in the .cmdletprovider file. /// </param> /// <param name="description"> /// The description of the provider. /// </param> /// <param name="home"> /// The home path for the provider. This must be an MSH path. /// </param> /// <param name="helpFile"> /// The help file for the provider. /// </param> /// <param name="psSnapIn"> /// The Snap-In for the provider. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="implementingType"/> or <paramref name="sessionState"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="name"/> is null or empty. /// </exception> internal ProviderInfo( SessionState sessionState, Type implementingType, string name, string description, string home, string helpFile, PSSnapInInfo psSnapIn) { // Verify parameters if (sessionState == null) { throw PSTraceSource.NewArgumentNullException("sessionState"); } if (implementingType == null) { throw PSTraceSource.NewArgumentNullException("implementingType"); } if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentException("name"); } _sessionState = sessionState; Name = name; Description = description; Home = home; ImplementingType = implementingType; HelpFile = helpFile; PSSnapIn = psSnapIn; // Create the hidden drive. The name doesn't really // matter since we are not adding this drive to a scope. _hiddenDrive = new PSDriveInfo( this.FullName, this, string.Empty, string.Empty, null); _hiddenDrive.Hidden = true; // TODO:PSL // this is probably not right here if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows) { VolumeSeparatedByColon = false; } } /// <summary> /// Determines if the passed in name is either the fully-qualified pssnapin name or /// short name of the provider. /// </summary> /// <param name="providerName"> /// The name to compare with the provider name. /// </param> /// <returns> /// True if the name is the fully-qualified pssnapin name or the short name of the provider. /// </returns> internal bool NameEquals(string providerName) { PSSnapinQualifiedName qualifiedProviderName = PSSnapinQualifiedName.GetInstance(providerName); bool result = false; if (qualifiedProviderName != null) { // If the pssnapin name and provider name are specified, then both must match do // false loop { if (!string.IsNullOrEmpty(qualifiedProviderName.PSSnapInName)) { // After converting core snapins to load as modules, the providers will have Module property populated if (!string.Equals(qualifiedProviderName.PSSnapInName, this.PSSnapInName, StringComparison.OrdinalIgnoreCase) && !string.Equals(qualifiedProviderName.PSSnapInName, this.ModuleName, StringComparison.OrdinalIgnoreCase)) { break; } } result = string.Equals(qualifiedProviderName.ShortName, this.Name, StringComparison.OrdinalIgnoreCase); } while (false); } else { // If only the provider name is specified, then only the name must match result = string.Equals(providerName, Name, StringComparison.OrdinalIgnoreCase); } return result; } internal bool IsMatch(string providerName) { PSSnapinQualifiedName psSnapinQualifiedName = PSSnapinQualifiedName.GetInstance(providerName); WildcardPattern namePattern = null; if (psSnapinQualifiedName != null && WildcardPattern.ContainsWildcardCharacters(psSnapinQualifiedName.ShortName)) { namePattern = WildcardPattern.Get(psSnapinQualifiedName.ShortName, WildcardOptions.IgnoreCase); } return IsMatch(namePattern, psSnapinQualifiedName); } internal bool IsMatch(WildcardPattern namePattern, PSSnapinQualifiedName psSnapinQualifiedName) { bool result = false; if (psSnapinQualifiedName == null) { result = true; } else { if (namePattern == null) { if (string.Equals(Name, psSnapinQualifiedName.ShortName, StringComparison.OrdinalIgnoreCase) && IsPSSnapinNameMatch(psSnapinQualifiedName)) { result = true; } } else if (namePattern.IsMatch(Name) && IsPSSnapinNameMatch(psSnapinQualifiedName)) { result = true; } } return result; } private bool IsPSSnapinNameMatch(PSSnapinQualifiedName psSnapinQualifiedName) { bool result = false; if (string.IsNullOrEmpty(psSnapinQualifiedName.PSSnapInName) || string.Equals(psSnapinQualifiedName.PSSnapInName, PSSnapInName, StringComparison.OrdinalIgnoreCase)) { result = true; } return result; } /// <summary> /// Creates an instance of the provider. /// </summary> /// <returns> /// An instance of the provider or null if one could not be created. /// </returns> /// <exception cref="ProviderNotFoundException"> /// If an instance of the provider could not be created because the /// type could not be found in the assembly. /// </exception> internal Provider.CmdletProvider CreateInstance() { // It doesn't really seem that using thread local storage to store an // instance of the provider is really much of a performance gain and it // still causes problems with the CmdletProviderContext when piping two // commands together that use the same provider. // get-child -filter a*.txt | get-content // This pipeline causes problems when using a cached provider instance because // the CmdletProviderContext gets changed when get-content gets called. // When get-content finishes writing content from the first output of get-child // get-child gets control back and writes out a FileInfo but the WriteObject // from get-content gets used because the CmdletProviderContext is still from // that cmdlet. // Possible solutions are to not cache the provider instance, or to maintain // a CmdletProviderContext stack in ProviderBase. Each method invocation pushes // the current context and the last action of the method pops back to the // previous context. #if USE_TLS // Next see if we already have an instance in thread local storage object providerInstance = Thread.GetData(instance); if (providerInstance == null) { #else object providerInstance = null; #endif // Finally create an instance of the class Exception invocationException = null; try { providerInstance = Activator.CreateInstance(this.ImplementingType); } catch (TargetInvocationException targetException) { invocationException = targetException.InnerException; } catch (MissingMethodException) { } catch (MemberAccessException) { } catch (ArgumentException) { } #if USE_TLS // cache the instance in thread local storage Thread.SetData(instance, providerInstance); } #endif if (providerInstance == null) { ProviderNotFoundException e = null; if (invocationException != null) { e = new ProviderNotFoundException( this.Name, SessionStateCategory.CmdletProvider, "ProviderCtorException", SessionStateStrings.ProviderCtorException, invocationException.Message); } else { e = new ProviderNotFoundException( this.Name, SessionStateCategory.CmdletProvider, "ProviderNotFoundInAssembly", SessionStateStrings.ProviderNotFoundInAssembly); } throw e; } Provider.CmdletProvider result = providerInstance as Provider.CmdletProvider; Dbg.Diagnostics.Assert( result != null, "DiscoverProvider should verify that the class is derived from CmdletProvider so this is just validation of that"); result.SetProviderInformation(this); return result; } /// <summary> /// Get the output types specified on this provider for the cmdlet requested. /// </summary> internal void GetOutputTypes(string cmdletname, List<PSTypeName> listToAppend) { if (_providerOutputType == null) { _providerOutputType = new Dictionary<string, List<PSTypeName>>(); foreach (OutputTypeAttribute outputType in ImplementingType.GetCustomAttributes<OutputTypeAttribute>(false)) { if (string.IsNullOrEmpty(outputType.ProviderCmdlet)) { continue; } List<PSTypeName> l; if (!_providerOutputType.TryGetValue(outputType.ProviderCmdlet, out l)) { l = new List<PSTypeName>(); _providerOutputType[outputType.ProviderCmdlet] = l; } l.AddRange(outputType.Type); } } List<PSTypeName> cmdletOutputType = null; if (_providerOutputType.TryGetValue(cmdletname, out cmdletOutputType)) { listToAppend.AddRange(cmdletOutputType); } } private Dictionary<string, List<PSTypeName>> _providerOutputType; private PSNoteProperty _noteProperty; internal PSNoteProperty GetNotePropertyForProviderCmdlets(string name) { if (_noteProperty == null) { Interlocked.CompareExchange(ref _noteProperty, new PSNoteProperty(name, this), null); } return _noteProperty; } } }
using Microsoft.SPOT.Hardware; namespace IngenuityMicro.Radius.Hardware { public class Pin { /// <summary>A value indicating that no GPIO pin is specified.</summary> public const Cpu.Pin GPIO_NONE = Cpu.Pin.GPIO_NONE; /// <summary>Digital I/O.</summary> public const Cpu.Pin PA0 = (Cpu.Pin)((0 * 16) + 0); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA1 = (Cpu.Pin)((0 * 16) + 1); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA2 = (Cpu.Pin)((0 * 16) + 2); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA3 = (Cpu.Pin)((0 * 16) + 3); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA4 = (Cpu.Pin)((0 * 16) + 4); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA5 = (Cpu.Pin)((0 * 16) + 5); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA6 = (Cpu.Pin)((0 * 16) + 6); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA7 = (Cpu.Pin)((0 * 16) + 7); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA8 = (Cpu.Pin)((0 * 16) + 8); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA9 = (Cpu.Pin)((0 * 16) + 9); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA10 = (Cpu.Pin)((0 * 16) + 10); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA11 = (Cpu.Pin)((0 * 16) + 11); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA12 = (Cpu.Pin)((0 * 16) + 12); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA13 = (Cpu.Pin)((0 * 16) + 13); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA14 = (Cpu.Pin)((0 * 16) + 14); /// <summary>Digital I/O.</summary> public const Cpu.Pin PA15 = (Cpu.Pin)((0 * 16) + 15); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB0 = (Cpu.Pin)((1 * 16) + 0); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB1 = (Cpu.Pin)((1 * 16) + 1); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB2 = (Cpu.Pin)((1 * 16) + 2); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB3 = (Cpu.Pin)((1 * 16) + 3); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB4 = (Cpu.Pin)((1 * 16) + 4); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB5 = (Cpu.Pin)((1 * 16) + 5); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB6 = (Cpu.Pin)((1 * 16) + 6); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB7 = (Cpu.Pin)((1 * 16) + 7); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB8 = (Cpu.Pin)((1 * 16) + 8); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB9 = (Cpu.Pin)((1 * 16) + 9); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB10 = (Cpu.Pin)((1 * 16) + 10); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB11 = (Cpu.Pin)((1 * 16) + 11); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB12 = (Cpu.Pin)((1 * 16) + 12); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB13 = (Cpu.Pin)((1 * 16) + 13); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB14 = (Cpu.Pin)((1 * 16) + 14); /// <summary>Digital I/O.</summary> public const Cpu.Pin PB15 = (Cpu.Pin)((1 * 16) + 15); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC0 = (Cpu.Pin)((2 * 16) + 0); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC1 = (Cpu.Pin)((2 * 16) + 1); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC2 = (Cpu.Pin)((2 * 16) + 2); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC3 = (Cpu.Pin)((2 * 16) + 3); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC4 = (Cpu.Pin)((2 * 16) + 4); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC5 = (Cpu.Pin)((2 * 16) + 5); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC6 = (Cpu.Pin)((2 * 16) + 6); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC7 = (Cpu.Pin)((2 * 16) + 7); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC8 = (Cpu.Pin)((2 * 16) + 8); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC9 = (Cpu.Pin)((2 * 16) + 9); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC10 = (Cpu.Pin)((2 * 16) + 10); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC11 = (Cpu.Pin)((2 * 16) + 11); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC12 = (Cpu.Pin)((2 * 16) + 12); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC13 = (Cpu.Pin)((2 * 16) + 13); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC14 = (Cpu.Pin)((2 * 16) + 14); /// <summary>Digital I/O.</summary> public const Cpu.Pin PC15 = (Cpu.Pin)((2 * 16) + 15); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD0 = (Cpu.Pin)((3 * 16) + 0); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD1 = (Cpu.Pin)((3 * 16) + 1); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD2 = (Cpu.Pin)((3 * 16) + 2); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD3 = (Cpu.Pin)((3 * 16) + 3); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD4 = (Cpu.Pin)((3 * 16) + 4); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD5 = (Cpu.Pin)((3 * 16) + 5); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD6 = (Cpu.Pin)((3 * 16) + 6); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD7 = (Cpu.Pin)((3 * 16) + 7); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD8 = (Cpu.Pin)((3 * 16) + 8); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD9 = (Cpu.Pin)((3 * 16) + 9); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD10 = (Cpu.Pin)((3 * 16) + 10); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD11 = (Cpu.Pin)((3 * 16) + 11); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD12 = (Cpu.Pin)((3 * 16) + 12); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD13 = (Cpu.Pin)((3 * 16) + 13); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD14 = (Cpu.Pin)((3 * 16) + 14); /// <summary>Digital I/O.</summary> public const Cpu.Pin PD15 = (Cpu.Pin)((3 * 16) + 15); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE0 = (Cpu.Pin)((4 * 16) + 0); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE1 = (Cpu.Pin)((4 * 16) + 1); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE2 = (Cpu.Pin)((4 * 16) + 2); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE3 = (Cpu.Pin)((4 * 16) + 3); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE4 = (Cpu.Pin)((4 * 16) + 4); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE5 = (Cpu.Pin)((4 * 16) + 5); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE6 = (Cpu.Pin)((4 * 16) + 6); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE7 = (Cpu.Pin)((4 * 16) + 7); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE8 = (Cpu.Pin)((4 * 16) + 8); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE9 = (Cpu.Pin)((4 * 16) + 9); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE10 = (Cpu.Pin)((4 * 16) + 10); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE11 = (Cpu.Pin)((4 * 16) + 11); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE12 = (Cpu.Pin)((4 * 16) + 12); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE13 = (Cpu.Pin)((4 * 16) + 13); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE14 = (Cpu.Pin)((4 * 16) + 14); /// <summary>Digital I/O.</summary> public const Cpu.Pin PE15 = (Cpu.Pin)((4 * 16) + 15); } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using Windows.Devices.Bluetooth; using Windows.Devices.Bluetooth.Rfcomm; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Navigation; namespace SDKTemplate { public sealed partial class Scenario2_ChatServer : Page { private StreamSocket socket; private DataWriter writer; private RfcommServiceProvider rfcommProvider; private StreamSocketListener socketListener; // A pointer back to the main page is required to display status messages. MainPage rootPage; public Scenario2_ChatServer() { this.InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } protected override void OnNavigatedFrom(NavigationEventArgs e) { Disconnect(); } private void ListenButton_Click(object sender, RoutedEventArgs e) { InitializeRfcommServer(); } /// <summary> /// Initializes the server using RfcommServiceProvider to advertise the Chat Service UUID and start listening /// for incoming connections. /// </summary> private async void InitializeRfcommServer() { ListenButton.IsEnabled = false; DisconnectButton.IsEnabled = true; try { rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid)); } // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE). catch (Exception ex) when ((uint)ex.HResult == 0x800710DF) { // The Bluetooth radio may be off. rootPage.NotifyUser("Make sure your Bluetooth Radio is on: " + ex.Message, NotifyType.ErrorMessage); ListenButton.IsEnabled = true; DisconnectButton.IsEnabled = false; return; } // Create a listener for this service and start listening socketListener = new StreamSocketListener(); socketListener.ConnectionReceived += OnConnectionReceived; var rfcomm = rfcommProvider.ServiceId.AsString(); await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication); // Set the SDP attributes and start Bluetooth advertising InitializeServiceSdpAttributes(rfcommProvider); try { rfcommProvider.StartAdvertising(socketListener, true); } catch (Exception e) { // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why. Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices. rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage); ListenButton.IsEnabled = true; DisconnectButton.IsEnabled = false; return; } rootPage.NotifyUser("Listening for incoming connections", NotifyType.StatusMessage); } /// <summary> /// Creates the SDP record that will be revealed to the Client device when pairing occurs. /// </summary> /// <param name="rfcommProvider">The RfcommServiceProvider that is being used to initialize the server</param> private void InitializeServiceSdpAttributes(RfcommServiceProvider rfcommProvider) { var sdpWriter = new DataWriter(); // Write the Service Name Attribute. sdpWriter.WriteByte(Constants.SdpServiceNameAttributeType); // The length of the UTF-8 encoded Service Name SDP Attribute. sdpWriter.WriteByte((byte)Constants.SdpServiceName.Length); // The UTF-8 encoded Service Name value. sdpWriter.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; sdpWriter.WriteString(Constants.SdpServiceName); // Set the SDP Attribute on the RFCOMM Service Provider. rfcommProvider.SdpRawAttributes.Add(Constants.SdpServiceNameAttributeId, sdpWriter.DetachBuffer()); } private void SendButton_Click(object sender, RoutedEventArgs e) { SendMessage(); } public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter) { SendMessage(); } } private async void SendMessage() { // There's no need to send a zero length message if (MessageTextBox.Text.Length != 0) { // Make sure that the connection is still up and there is a message to send if (socket != null) { string message = MessageTextBox.Text; writer.WriteUInt32((uint)message.Length); writer.WriteString(message); ConversationListBox.Items.Add("Sent: " + message); // Clear the messageTextBox for a new message MessageTextBox.Text = ""; await writer.StoreAsync(); } else { rootPage.NotifyUser("No clients connected, please wait for a client to connect before attempting to send a message", NotifyType.StatusMessage); } } } private void DisconnectButton_Click(object sender, RoutedEventArgs e) { Disconnect(); rootPage.NotifyUser("Disconnected.", NotifyType.StatusMessage); } private async void Disconnect() { if (rfcommProvider != null) { rfcommProvider.StopAdvertising(); rfcommProvider = null; } if (socketListener != null) { socketListener.Dispose(); socketListener = null; } if (writer != null) { writer.DetachStream(); writer = null; } if (socket != null) { socket.Dispose(); socket = null; } await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ListenButton.IsEnabled = true; DisconnectButton.IsEnabled = false; ConversationListBox.Items.Clear(); }); } /// <summary> /// Invoked when the socket listener accepts an incoming Bluetooth connection. /// </summary> /// <param name="sender">The socket listener that accepted the connection.</param> /// <param name="args">The connection accept parameters, which contain the connected socket.</param> private async void OnConnectionReceived( StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { // Don't need the listener anymore socketListener.Dispose(); socketListener = null; try { socket = args.Socket; } catch (Exception e) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser(e.Message, NotifyType.ErrorMessage); }); Disconnect(); return; } // Note - this is the supported way to get a Bluetooth device from a given socket var remoteDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName); writer = new DataWriter(socket.OutputStream); var reader = new DataReader(socket.InputStream); bool remoteDisconnection = false; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Connected to Client: " + remoteDevice.Name, NotifyType.StatusMessage); }); // Infinite read buffer loop while (true) { try { // Based on the protocol we've defined, the first uint is the size of the message uint readLength = await reader.LoadAsync(sizeof(uint)); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < sizeof(uint)) { remoteDisconnection = true; break; } uint currentLength = reader.ReadUInt32(); // Load the rest of the message since you already know the length of the data expected. readLength = await reader.LoadAsync(currentLength); // Check if the size of the data is expected (otherwise the remote has already terminated the connection) if (readLength < currentLength) { remoteDisconnection = true; break; } string message = reader.ReadString(currentLength); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { ConversationListBox.Items.Add("Received: " + message); }); } // Catch exception HRESULT_FROM_WIN32(ERROR_OPERATION_ABORTED). catch (Exception ex) when ((uint)ex.HResult == 0x800703E3) { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client Disconnected Successfully", NotifyType.StatusMessage); }); break; } } reader.DetachStream(); if (remoteDisconnection) { Disconnect(); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Client disconnected",NotifyType.StatusMessage); }); } } } }
#region Copyright (C) 2017 Atif Aziz. 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.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; try { Run(args); return 0; } catch (Exception e) { Console.Error.WriteLine(e.ToString()); return 0xbad; } static void Run(IEnumerable<string> args) { var dir = Directory.GetCurrentDirectory(); string includePattern = null; string excludePattern = null; var debug = false; var usings = new List<string>(); var noClassLead = false; using (var arg = args.GetEnumerator()) { while (arg.MoveNext()) { switch (arg.Current) { case "-i": case "--include": includePattern = Read(arg, MissingArgValue); break; case "-x": case "--exclude": excludePattern = Read(arg, MissingArgValue); break; case "-u": case "--using": usings.Add(Read(arg, MissingArgValue)); break; case "--no-class-lead": noClassLead = true; break; case "-d": case "--debug": debug = true; break; case "": continue; default: dir = arg.Current[0] != '-' ? arg.Current : throw new Exception("Invalid argument: " + arg.Current); break; } } static Exception MissingArgValue() => new InvalidOperationException("Missing argument value."); } static Func<string, bool> PredicateFromPattern(string pattern, bool @default) => string.IsNullOrEmpty(pattern) ? delegate { return @default; } : new Func<string, bool>(new Regex(pattern).IsMatch); var includePredicate = PredicateFromPattern(includePattern, true); var excludePredicate = PredicateFromPattern(excludePattern, false); var thisAssemblyName = typeof(TypeKey).GetTypeInfo().Assembly.GetName(); // // Type abbreviations are used to abbreviate all generic type // parameters into a letter from the alphabet. So for example, a // method with generic type parameters `TSource` and `TResult` will // become `a` and `b`. This is used later for sorting and stabilizes // the sort irrespective of how the type parameters are named or // renamed in the source. // var abbreviatedTypeNodes = Enumerable .Range(0, 26) .Select(a => (char) ('a' + a)) .Select(ch => new SimpleTypeKey(ch.ToString())) .ToArray(); var q = from ms in new[] { from fp in Directory.EnumerateFiles(dir, "*.cs") where !excludePredicate(fp) && includePredicate(fp) orderby fp // // Find all class declarations where class name is // `MoreEnumerable`. Note that this is irrespective of // namespace, which is out of sheer laziness. // from cd in CSharpSyntaxTree .ParseText(File.ReadAllText(fp), CSharpParseOptions.Default.WithPreprocessorSymbols("MORELINQ")) .GetRoot() .SyntaxTree .GetCompilationUnitRoot() .DescendantNodes().OfType<ClassDeclarationSyntax>() where (string) cd.Identifier.Value == "MoreEnumerable" // // Get all method declarations where method: // // - has at least one parameter // - extends a type (first parameter uses the `this` modifier) // - is public // - isn't marked as being obsolete // from md in cd.DescendantNodes().OfType<MethodDeclarationSyntax>() let mn = (string) md.Identifier.Value where md.ParameterList.Parameters.Count > 0 && md.ParameterList.Parameters.First().Modifiers.Any(m => (string)m.Value == "this") && md.Modifiers.Any(m => (string)m.Value == "public") && md.AttributeLists.SelectMany(al => al.Attributes).All(a => a.Name.ToString() != "Obsolete") // // Build a dictionary of type abbreviations (e.g. TSource -> a, // TResult -> b, etc.) for the method's type parameters. If the // method is non-generic, then this will be null! // let typeParameterAbbreviationByName = md.TypeParameterList ?.Parameters .Select((e, i) => (Original: e.Identifier.ValueText, Alias: abbreviatedTypeNodes[i])) .ToDictionary(e => e.Original, e => e.Alias) // // Put everything together. While we mostly care about the // method declaration, the rest of the information is captured // for the purpose of stabilizing the code generation order and // debugging (--debug). // select new { Syntax = md, Name = md.Identifier.ToString(), TypeParameterCount = md.TypeParameterList?.Parameters.Count ?? 0, TypeParameterAbbreviationByName = typeParameterAbbreviationByName, ParameterCount = md.ParameterList.Parameters.Count, SortableParameterTypes = from p in md.ParameterList.Parameters select CreateTypeKey(p.Type, n => typeParameterAbbreviationByName != null && typeParameterAbbreviationByName.TryGetValue(n, out var a) ? a : null), } } from e in ms.Select((m, i) => (SourceOrder: i + 1, Method: m)) orderby e.Method.Name, e.Method.TypeParameterCount, e.Method.ParameterCount, new TupleTypeKey(ImmutableList.CreateRange(e.Method.SortableParameterTypes)) select new { e.Method, e.SourceOrder, }; q = q.ToArray(); if (debug) { var ms = // // Example of what this is designed to produce: // // 083: Lag<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult // 084: Lag<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult // 085: Lead<a, b>(IEnumerable<a>, int, Func<a, a, b>) where a = TSource, b = TResult // 086: Lead<a, b>(IEnumerable<a>, int, a, Func<a, a, b>) where a = TSource, b = TResult // from e in q let m = e.Method select new { m.Name, SourceOrder = e.SourceOrder.ToString("000", CultureInfo.InvariantCulture), TypeParameters = m.TypeParameterCount == 0 ? string.Empty : "<" + string.Join(", ", from a in m.TypeParameterAbbreviationByName select a.Value) + ">", Parameters = "(" + string.Join(", ", m.SortableParameterTypes) + ")", Abbreviations = m.TypeParameterCount == 0 ? string.Empty : " where " + string.Join(", ", from a in m.TypeParameterAbbreviationByName select a.Value + " = " + a.Key), } into e select e.SourceOrder + ": " + e.Name + e.TypeParameters + e.Parameters + e.Abbreviations; foreach (var m in ms) Console.Error.WriteLine(m); } var indent = new string(' ', 4); var indent2 = indent + indent; var indent3 = indent2 + indent; var baseImports = new [] { "System", "System.CodeDom.Compiler", "System.Collections.Generic", "System.Diagnostics.CodeAnalysis", }; var imports = from ns in baseImports.Concat(usings) select indent + $"using {ns};"; var classes = from md in q select md.Method.Syntax into md group md by (string) md.Identifier.Value into g select new { Name = g.Key, Overloads = from md in g select MethodDeclaration(md.ReturnType, md.Identifier) .WithAttributeLists(md.AttributeLists) .WithModifiers(md.Modifiers) .WithTypeParameterList(md.TypeParameterList) .WithConstraintClauses(md.ConstraintClauses) .WithParameterList(md.ParameterList) .WithExpressionBody( ArrowExpressionClause( InvocationExpression( MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, IdentifierName("MoreEnumerable"), IdentifierName(md.Identifier)), ArgumentList( SeparatedList( from p in md.ParameterList.Parameters select Argument(IdentifierName(p.Identifier)), Enumerable.Repeat(ParseToken(",").WithTrailingTrivia(Space), md.ParameterList.Parameters.Count - 1)))) .WithLeadingTrivia(Space)) .WithLeadingTrivia(Whitespace(indent3))) .WithSemicolonToken(ParseToken(";").WithTrailingTrivia(LineFeed)) } into m select (!noClassLead ? $@" /// <summary><c>{m.Name}</c> extension.</summary> [GeneratedCode(""{thisAssemblyName.Name}"", ""{thisAssemblyName.Version}"")]" : null) + $@" public static partial class {m.Name}Extension {{ {string.Join(null, from mo in m.Overloads select mo.ToFullString())} }}"; var template = $@" #region License and Terms // MoreLINQ - Extensions to LINQ to Objects // // 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 // This code was generated by a tool. Any changes made manually will be lost // the next time this code is regenerated. #nullable enable // required for auto-generated sources (see below why) // > Older code generation strategies may not be nullable aware. Setting the // > project-level nullable context to ""enable"" could result in many // > warnings that a user is unable to fix. To support this scenario any syntax // > tree that is determined to be generated will have its nullable state // > implicitly set to ""disable"", regardless of the overall project state. // // Source: https://github.com/dotnet/roslyn/blob/70e158ba6c2c99bd3c3fc0754af0dbf82a6d353d/docs/features/nullable-reference-types.md#generated-code namespace MoreLinq.Extensions {{ {string.Join("\n", imports)} {string.Join("\n", classes)} }} "; Console.WriteLine(template.Trim() // normalize line endings .Replace("\r", string.Empty) .Replace("\n", Environment.NewLine)); } static TypeKey CreateTypeKey(TypeSyntax root, Func<string, TypeKey> abbreviator = null) { return Walk(root ?? throw new ArgumentNullException(nameof(root))); TypeKey Walk(TypeSyntax ts) => ts switch { PredefinedTypeSyntax pts => new SimpleTypeKey(pts.ToString()), NullableTypeSyntax nts => new NullableTypeKey(Walk(nts.ElementType)), IdentifierNameSyntax ins => abbreviator?.Invoke(ins.Identifier.ValueText) ?? new SimpleTypeKey(ins.ToString()), GenericNameSyntax gns => new GenericTypeKey(gns.Identifier.ToString(), ImmutableList.CreateRange(gns.TypeArgumentList.Arguments.Select(Walk))), ArrayTypeSyntax ats => new ArrayTypeKey(Walk(ats.ElementType), ImmutableList.CreateRange(from rs in ats.RankSpecifiers select rs.Rank)), TupleTypeSyntax tts => new TupleTypeKey(ImmutableList.CreateRange(from te in tts.Elements select Walk(te.Type))), _ => throw new NotSupportedException("Unhandled type: " + ts) }; } static T Read<T>(IEnumerator<T> e, Func<Exception> errorFactory = null) { if (!e.MoveNext()) throw errorFactory?.Invoke() ?? new InvalidOperationException(); return e.Current; } // // Logical type nodes designed to be structurally sortable based on: // // - Type parameter count // - Name // - Array rank, if an array // - Each type parameter (recursively) // abstract class TypeKey : IComparable<TypeKey> { protected TypeKey(string name) => Name = name; public string Name { get; } public abstract ImmutableList<TypeKey> Parameters { get; } public virtual int CompareTo(TypeKey other) => ReferenceEquals(this, other) ? 0 : other == null ? 1 : Parameters.Count.CompareTo(other.Parameters.Count) is {} lc and not 0 ? lc : string.Compare(Name, other.Name, StringComparison.Ordinal) is {} nc and not 0 ? nc : CompareParameters(other); protected virtual int CompareParameters(TypeKey other) => Compare(Parameters, other.Parameters); protected static int Compare(IEnumerable<TypeKey> a, IEnumerable<TypeKey> b) => a.Zip(b, (us, them) => (Us: us, Them: them)) .Select(e => e.Us.CompareTo(e.Them)) .FirstOrDefault(e => e != 0); } sealed class SimpleTypeKey : TypeKey { public SimpleTypeKey(string name) : base(name) {} public override string ToString() => Name; public override ImmutableList<TypeKey> Parameters => ImmutableList<TypeKey>.Empty; } abstract class ParameterizedTypeKey : TypeKey { protected ParameterizedTypeKey(string name, TypeKey parameter) : this(name, ImmutableList.Create(parameter)) {} protected ParameterizedTypeKey(string name, ImmutableList<TypeKey> parameters) : base(name) => Parameters = parameters; public override ImmutableList<TypeKey> Parameters { get; } } sealed class GenericTypeKey : ParameterizedTypeKey { public GenericTypeKey(string name, ImmutableList<TypeKey> parameters) : base(name, parameters) {} public override string ToString() => Name + "<" + string.Join(", ", Parameters) + ">"; } sealed class NullableTypeKey : ParameterizedTypeKey { public NullableTypeKey(TypeKey underlying) : base("?", underlying) {} public override string ToString() => Parameters.Single() + "?"; } sealed class TupleTypeKey : ParameterizedTypeKey { public TupleTypeKey(ImmutableList<TypeKey> parameters) : base("()", parameters) {} public override string ToString() => "(" + string.Join(", ", Parameters) + ")"; } sealed class ArrayTypeKey : ParameterizedTypeKey { public ArrayTypeKey(TypeKey element, IEnumerable<int> ranks) : base("[]", element) => Ranks = ImmutableList.CreateRange(ranks); public ImmutableList<int> Ranks { get; } public override string ToString() => Parameters.Single() + string.Concat(from r in Ranks select "[" + string.Concat(Enumerable.Repeat(",", r - 1)) + "]"); protected override int CompareParameters(TypeKey other) { if (other is ArrayTypeKey a) { if (Ranks.Count.CompareTo(a.Ranks.Count) is {} rlc and not 0) return rlc; if (Ranks.Zip(a.Ranks, (us, them) => (Us: us, Them: them)) .Aggregate(0, (c, r) => c == 0 ? r.Us.CompareTo(r.Them) : c) is {} rc and not 0) return rc; } return base.CompareParameters(other); } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ using System; using System.Runtime.InteropServices; using UnityEngine; /// <summary> /// OVRGamepadController is an interface class to a gamepad controller. /// </summary> public class OVRGamepadController : MonoBehaviour { /// <summary> An axis on the gamepad. </summary> public enum Axis { None = -1, LeftXAxis = 0, LeftYAxis, RightXAxis, RightYAxis, LeftTrigger, RightTrigger, Max, }; /// <summary> A button on the gamepad. </summary> public enum Button { None = -1, A = 0, B, X, Y, Up, Down, Left, Right, Start, Back, LStick, RStick, LeftShoulder, RightShoulder, Max }; /// <summary> /// The default Unity input name for each gamepad Axis. /// </summary> public static string[] AndroidAxisNames = new string[(int)Axis.Max] { "Left_X_Axis", "Left_Y_Axis", "Right_X_Axis", "Right_Y_Axis", "LeftTrigger", "RightTrigger", }; /// <summary> /// The default Unity input name for each gamepad Button. /// </summary> public static string[] AndroidButtonNames = new string[(int)Button.Max] { "Button A", "Button B", "Button X", "Button Y", "Up", "Down", "Left", "Right", "Start", "Back", "LStick", "RStick", "LeftShoulder", "RightShoulder", }; /// <summary> /// The default Unity input name for each gamepad Axis. /// </summary> public static string[] DesktopAxisNames = new string[(int)Axis.Max] { "Desktop_Left_X_Axis", "Desktop_Left_Y_Axis", "Desktop_Right_X_Axis", "Desktop_Right_Y_Axis", "Desktop_LeftTrigger", "Desktop_RightTrigger", }; /// <summary> /// The default Unity input name for each gamepad Button. /// </summary> public static string[] DesktopButtonNames = new string[(int)Button.Max] { "Desktop_Button A", "Desktop_Button B", "Desktop_Button X", "Desktop_Button Y", "Desktop_Up", "Desktop_Down", "Desktop_Left", "Desktop_Right", "Desktop_Start", "Desktop_Back", "Desktop_LStick", "Desktop_RStick", "Desktop_LeftShoulder", "Desktop_RightShoulder", }; public static int[] DefaultButtonIds = new int[(int)Button.Max] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; /// <summary> /// The current Unity input names for all gamepad axes. /// </summary> public static string[] AxisNames = null; /// <summary> /// The current Unity input names for all gamepad buttons. /// </summary> public static string[] ButtonNames = null; static OVRGamepadController() { #if UNITY_ANDROID && !UNITY_EDITOR SetAxisNames(AndroidAxisNames); SetButtonNames(AndroidButtonNames); #else SetAxisNames(DesktopAxisNames); SetButtonNames(DesktopButtonNames); #endif } /// <summary> /// Sets the current names for all gamepad axes. /// </summary> public static void SetAxisNames(string[] axisNames) { AxisNames = axisNames; } /// <summary> /// Sets the current Unity input names for all gamepad buttons. /// </summary> /// <param name="buttonNames">Button names.</param> public static void SetButtonNames(string[] buttonNames) { ButtonNames = buttonNames; } /// <summary> Handles an axis read event. </summary> public delegate float ReadAxisDelegate(Axis axis); /// <summary> Handles an button read event. </summary> public delegate bool ReadButtonDelegate(Button button); /// <summary> Occurs when an axis has been read. </summary> public static ReadAxisDelegate ReadAxis = DefaultReadAxis; /// <summary> Occurs when a button has been read. </summary> public static ReadButtonDelegate ReadButton = DefaultReadButton; #if (!UNITY_ANDROID || UNITY_EDITOR) private static bool GPC_Available = false; //------------------------- // Public access to plugin functions /// <summary> /// GPC_Initialize. /// </summary> /// <returns><c>true</c>, if c_ initialize was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Initialize() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Initialize(); } /// <summary> /// GPC_Destroy /// </summary> /// <returns><c>true</c>, if c_ destroy was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Destroy() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Destroy(); } /// <summary> /// GPC_Update /// </summary> /// <returns><c>true</c>, if c_ update was GPed, <c>false</c> otherwise.</returns> public static bool GPC_Update() { if (!OVRManager.instance.isSupportedPlatform) return false; return OVR_GamepadController_Update(); } #endif /// <summary> /// GPC_GetAxis /// The default delegate for retrieving axis info. /// </summary> /// <returns>The current value of the axis.</returns> /// <param name="axis">Axis.</param> public static float DefaultReadAxis(Axis axis) { #if UNITY_ANDROID && !UNITY_EDITOR return Input.GetAxis(AxisNames[(int)axis]); #else return OVR_GamepadController_GetAxis((int)axis); #endif } /// <summary> /// Returns the current value of the given Axis. /// </summary> public static float GPC_GetAxis(Axis axis) { if (ReadAxis == null) return 0f; return ReadAxis(axis); } public static void SetReadAxisDelegate(ReadAxisDelegate del) { ReadAxis = del; } /// <summary> /// Uses XInput to check if the given Button is down. /// </summary> public static bool DefaultReadButton(Button button) { #if UNITY_ANDROID && !UNITY_EDITOR return Input.GetButton(ButtonNames[(int)button]); #else return OVR_GamepadController_GetButton((int)button); #endif } /// <summary> /// Returns true if the given Button is down. /// </summary> public static bool GPC_GetButton(Button button) { if (ReadButton == null) return false; return ReadButton(button); } public static void SetReadButtonDelegate(ReadButtonDelegate del) { ReadButton = del; } /// <summary> /// Returns true if the gamepad controller is available. /// </summary> public static bool GPC_IsAvailable() { #if !UNITY_ANDROID || UNITY_EDITOR return GPC_Available; #else return true; #endif } void GPC_Test() { // Axis test Debug.Log(string.Format("LT:{0:F3} RT:{1:F3} LX:{2:F3} LY:{3:F3} RX:{4:F3} RY:{5:F3}", GPC_GetAxis(Axis.LeftTrigger), GPC_GetAxis(Axis.RightTrigger), GPC_GetAxis(Axis.LeftXAxis), GPC_GetAxis(Axis.LeftYAxis), GPC_GetAxis(Axis.RightXAxis), GPC_GetAxis(Axis.RightYAxis))); // Button test Debug.Log(string.Format("A:{0} B:{1} X:{2} Y:{3} U:{4} D:{5} L:{6} R:{7} SRT:{8} BK:{9} LS:{10} RS:{11} L1:{12} R1:{13}", GPC_GetButton(Button.A), GPC_GetButton(Button.B), GPC_GetButton(Button.X), GPC_GetButton(Button.Y), GPC_GetButton(Button.Up), GPC_GetButton(Button.Down), GPC_GetButton(Button.Left), GPC_GetButton(Button.Right), GPC_GetButton(Button.Start), GPC_GetButton(Button.Back), GPC_GetButton(Button.LStick), GPC_GetButton(Button.RStick), GPC_GetButton(Button.LeftShoulder), GPC_GetButton(Button.RightShoulder))); } #if !UNITY_ANDROID || UNITY_EDITOR void Start() { GPC_Available = GPC_Initialize(); } void Update() { GPC_Available = GPC_Update(); } void OnDestroy() { GPC_Destroy(); GPC_Available = false; } public const string LibOVR = "OculusPlugin"; [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Initialize(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Destroy(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_Update(); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern float OVR_GamepadController_GetAxis(int axis); [DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)] public static extern bool OVR_GamepadController_GetButton(int button); #endif }
using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Xml.Linq; using HealthCheck; using HealthCheck.Framework; using Moq; using Quartz; using Xunit; namespace UnitTests.Framework { [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] public class PluginManagerTests { [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithListener() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var xml = new XElement("Listener"); xml.SetAttributeValue("Type", "LogFile"); xml.SetAttributeValue("Threshold", "Warning"); config.Listeners.Add(xml); var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetListener(It.IsAny<string>())).Returns(new Mock<IStatusListener>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert _ = Assert.Single(job.Listeners); } [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithNoListeners() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetListener(It.IsAny<string>())).Returns(new Mock<IStatusListener>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert Assert.Empty(job.Listeners); } [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithNoTriggers() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetTrigger(It.IsAny<XElement>())).Returns(new Mock<ITrigger>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert Assert.Empty(job.Triggers); } [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithTrigger() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var xml = new XElement("Trigger"); xml.SetAttributeValue("Type", "simple"); xml.SetAttributeValue("Repeat", "10"); config.Triggers.Add(xml); var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetTrigger(It.IsAny<XElement>())).Returns(new Mock<ITrigger>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert _ = Assert.Single(job.Triggers); } [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithTriggerAndListener() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var xml = new XElement("Listener"); xml.SetAttributeValue("Type", "LogFile"); xml.SetAttributeValue("Threshold", "Warning"); config.Listeners.Add(xml); xml = new XElement("Trigger"); xml.SetAttributeValue("Type", "simple"); xml.SetAttributeValue("Repeat", "10"); config.Triggers.Add(xml); var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetListener(It.IsAny<string>())).Returns(new Mock<IStatusListener>().Object); _ = mock.Setup(f => f.GetTrigger(It.IsAny<XElement>())).Returns(new Mock<ITrigger>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert Assert.True(job.Triggers.Any() && job.Listeners.Any()); } [Fact] public void InitializeCheckJob_Should_CreatePingCheckJobWithTriggerAndListenerAndSettings() { // Arrange var config = new JobConfiguration { Type = "Ping" }; var xml = new XElement("Listener"); xml.SetAttributeValue("Type", "LogFile"); xml.SetAttributeValue("Threshold", "Warning"); config.Listeners.Add(xml); xml = new XElement("Trigger"); xml.SetAttributeValue("Type", "simple"); xml.SetAttributeValue("Repeat", "10"); config.Triggers.Add(xml); config.Settings = new XElement("Settings", new XElement("HostName")); var job = new HealthCheckJob { JobConfiguration = config }; var mock = new Mock<IComponentFactory>(); _ = mock.Setup(f => f.GetPlugin("Ping")).Returns(new Mock<IHealthCheckPlugin>().Object); _ = mock.Setup(f => f.GetListener(It.IsAny<string>())).Returns(new Mock<IStatusListener>().Object); _ = mock.Setup(f => f.GetTrigger(It.IsAny<XElement>())).Returns(new Mock<ITrigger>().Object); var manager = new PluginManager(mock.Object); var group = new HealthCheckGroup { Name = "PROD" }; // Act _ = manager.InitializeCheckJob(job, group); // Assert Assert.True(job.Triggers.Any() && job.Listeners.Any()); } } }
// 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.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using Xunit; public class FileVersionInfoTest { private const string NativeConsoleAppFileName = "NativeConsoleApp.exe"; private const string NativeLibraryFileName = "NativeLibrary.dll"; private const string SecondNativeLibraryFileName = "SecondNativeLibrary.dll"; private const string TestAssemblyFileName = "System.Diagnostics.FileVersionInfo.TestAssembly.dll"; private const string TestCsFileName = "Assembly1.cs"; private const string TestNotFoundFileName = "notfound.dll"; [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_Normal() { // NativeConsoleApp (English) VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName), new MyFVI() { Comments = "", CompanyName = "Microsoft Corporation", FileBuildPart = 3, FileDescription = "This is the description for the native console application.", FileMajorPart = 5, FileMinorPart = 4, FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeConsoleAppFileName), FilePrivatePart = 2, FileVersion = "5.4.3.2", InternalName = NativeConsoleAppFileName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = true, IsSpecialBuild = true, Language = GetFileVersionLanguage(0x0409), //English (United States) LegalCopyright = "Copyright (C) 2050", LegalTrademarks = "", OriginalFilename = NativeConsoleAppFileName, PrivateBuild = "", ProductBuildPart = 3, ProductMajorPart = 5, ProductMinorPart = 4, ProductName = Path.GetFileNameWithoutExtension(NativeConsoleAppFileName), ProductPrivatePart = 2, ProductVersion = "5.4.3.2", SpecialBuild = "" }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_Chinese() { // NativeLibrary.dll (Chinese) VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName), new MyFVI() { Comments = "", CompanyName = "A non-existent company", FileBuildPart = 3, FileDescription = "Here is the description of the native library.", FileMajorPart = 9, FileMinorPart = 9, FileName = Path.Combine(Directory.GetCurrentDirectory(), NativeLibraryFileName), FilePrivatePart = 3, FileVersion = "9.9.3.3", InternalName = "NativeLi.dll", IsDebug = false, IsPatched = true, IsPrivateBuild = false, IsPreRelease = true, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0004),//Chinese (Simplified) Language2 = GetFileVersionLanguage(0x0804),//Chinese (Simplified, PRC) - changed, but not yet on all platforms LegalCopyright = "None", LegalTrademarks = "", OriginalFilename = "NativeLi.dll", PrivateBuild = "", ProductBuildPart = 40, ProductMajorPart = 20, ProductMinorPart = 30, ProductName = "I was never given a name.", ProductPrivatePart = 50, ProductVersion = "20.30.40.50", SpecialBuild = "", }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // native PE files only supported on Windows public void FileVersionInfo_DifferentFileVersionAndProductVersion() { // Mtxex.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName), new MyFVI() { Comments = "", CompanyName = "", FileBuildPart = 0, FileDescription = "", FileMajorPart = 0, FileMinorPart = 65535, FileName = Path.Combine(Directory.GetCurrentDirectory(), SecondNativeLibraryFileName), FilePrivatePart = 2, FileVersion = "0.65535.0.2", InternalName = "SecondNa.dll", IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = GetFileVersionLanguage(0x0400),//Process Default Language LegalCopyright = "Copyright (C) 1 - 2014", LegalTrademarks = "", OriginalFilename = "SecondNa.dll", PrivateBuild = "", ProductBuildPart = 0, ProductMajorPart = 1, ProductMinorPart = 0, ProductName = "Unknown_Product_Name", ProductPrivatePart = 1, ProductVersion = "1.0.0.1", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_CustomManagedAssembly() { // Assembly1.dll VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), new MyFVI() { Comments = "Have you played a Contoso amusement device today?", CompanyName = "The name of the company.", FileBuildPart = 2, FileDescription = "My File", FileMajorPart = 4, FileMinorPart = 3, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestAssemblyFileName), FilePrivatePart = 1, FileVersion = "4.3.2.1", InternalName = TestAssemblyFileName, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? GetFileVersionLanguage(0x0000) : "Language Neutral", LegalCopyright = "Copyright, you betcha!", LegalTrademarks = "TM", OriginalFilename = TestAssemblyFileName, PrivateBuild = "", ProductBuildPart = 2, ProductMajorPart = 4, ProductMinorPart = 3, ProductName = "The greatest product EVER", ProductPrivatePart = 1, ProductVersion = "4.3.2.1", SpecialBuild = "", }); } [Fact] public void FileVersionInfo_EmptyFVI() { // Assembly1.cs VerifyVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), new MyFVI() { Comments = null, CompanyName = null, FileBuildPart = 0, FileDescription = null, FileMajorPart = 0, FileMinorPart = 0, FileName = Path.Combine(Directory.GetCurrentDirectory(), TestCsFileName), FilePrivatePart = 0, FileVersion = null, InternalName = null, IsDebug = false, IsPatched = false, IsPrivateBuild = false, IsPreRelease = false, IsSpecialBuild = false, Language = null, LegalCopyright = null, LegalTrademarks = null, OriginalFilename = null, PrivateBuild = null, ProductBuildPart = 0, ProductMajorPart = 0, ProductMinorPart = 0, ProductName = null, ProductPrivatePart = 0, ProductVersion = null, SpecialBuild = null, }); } [Fact] public void FileVersionInfo_FileNotFound() { Assert.Throws<FileNotFoundException>(() => FileVersionInfo.GetVersionInfo(Path.Combine(Directory.GetCurrentDirectory(), TestNotFoundFileName))); } // Additional Tests Wanted: // [] File exists but we don't have permission to read it // [] DLL has unknown codepage info // [] DLL language/codepage is 8-hex-digits (locale > 0x999) (different codepath) private void VerifyVersionInfo(String filePath, MyFVI expected) { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(filePath); Assert.Equal(expected.Comments, fvi.Comments); Assert.Equal(expected.CompanyName, fvi.CompanyName); Assert.Equal(expected.FileBuildPart, fvi.FileBuildPart); Assert.Equal(expected.FileDescription, fvi.FileDescription); Assert.Equal(expected.FileMajorPart, fvi.FileMajorPart); Assert.Equal(expected.FileMinorPart, fvi.FileMinorPart); Assert.Equal(expected.FileName, fvi.FileName); Assert.Equal(expected.FilePrivatePart, fvi.FilePrivatePart); Assert.Equal(expected.FileVersion, fvi.FileVersion); Assert.Equal(expected.InternalName, fvi.InternalName); Assert.Equal(expected.IsDebug, fvi.IsDebug); Assert.Equal(expected.IsPatched, fvi.IsPatched); Assert.Equal(expected.IsPrivateBuild, fvi.IsPrivateBuild); Assert.Equal(expected.IsPreRelease, fvi.IsPreRelease); Assert.Equal(expected.IsSpecialBuild, fvi.IsSpecialBuild); Assert.Contains(fvi.Language, new[] { expected.Language, expected.Language2 }); Assert.Equal(expected.LegalCopyright, fvi.LegalCopyright); Assert.Equal(expected.LegalTrademarks, fvi.LegalTrademarks); Assert.Equal(expected.OriginalFilename, fvi.OriginalFilename); Assert.Equal(expected.PrivateBuild, fvi.PrivateBuild); Assert.Equal(expected.ProductBuildPart, fvi.ProductBuildPart); Assert.Equal(expected.ProductMajorPart, fvi.ProductMajorPart); Assert.Equal(expected.ProductMinorPart, fvi.ProductMinorPart); Assert.Equal(expected.ProductName, fvi.ProductName); Assert.Equal(expected.ProductPrivatePart, fvi.ProductPrivatePart); Assert.Equal(expected.ProductVersion, fvi.ProductVersion); Assert.Equal(expected.SpecialBuild, fvi.SpecialBuild); //ToString String nl = Environment.NewLine; Assert.Equal("File: " + fvi.FileName + nl + "InternalName: " + fvi.InternalName + nl + "OriginalFilename: " + fvi.OriginalFilename + nl + "FileVersion: " + fvi.FileVersion + nl + "FileDescription: " + fvi.FileDescription + nl + "Product: " + fvi.ProductName + nl + "ProductVersion: " + fvi.ProductVersion + nl + "Debug: " + fvi.IsDebug.ToString() + nl + "Patched: " + fvi.IsPatched.ToString() + nl + "PreRelease: " + fvi.IsPreRelease.ToString() + nl + "PrivateBuild: " + fvi.IsPrivateBuild.ToString() + nl + "SpecialBuild: " + fvi.IsSpecialBuild.ToString() + nl + "Language: " + fvi.Language + nl, fvi.ToString()); } internal class MyFVI { public string Comments; public string CompanyName; public int FileBuildPart; public string FileDescription; public int FileMajorPart; public int FileMinorPart; public string FileName; public int FilePrivatePart; public string FileVersion; public string InternalName; public bool IsDebug; public bool IsPatched; public bool IsPrivateBuild; public bool IsPreRelease; public bool IsSpecialBuild; public string Language; public string Language2; public string LegalCopyright; public string LegalTrademarks; public string OriginalFilename; public string PrivateBuild; public int ProductBuildPart; public int ProductMajorPart; public int ProductMinorPart; public string ProductName; public int ProductPrivatePart; public string ProductVersion; public string SpecialBuild; } static string GetUnicodeString(String str) { if (str == null) return "<null>"; StringBuilder buffer = new StringBuilder(); buffer.Append("\""); for (int i = 0; i < str.Length; i++) { char ch = str[i]; if (ch == '\r') { buffer.Append("\\r"); } else if (ch == '\n') { buffer.Append("\\n"); } else if (ch == '\\') { buffer.Append("\\"); } else if (ch == '\"') { buffer.Append("\\\""); } else if (ch == '\'') { buffer.Append("\\\'"); } else if (ch < 0x20 || ch >= 0x7f) { buffer.Append("\\u"); buffer.Append(((int)ch).ToString("x4")); } else { buffer.Append(ch); } } buffer.Append("\""); return (buffer.ToString()); } private static string GetFileVersionLanguage(uint langid) { var lang = new StringBuilder(256); Interop.mincore.VerLanguageName(langid, lang, (uint)lang.Capacity); return lang.ToString(); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IFittedBondCollection.cs" company=""> // // </copyright> // <summary> // The BackgroundFittedBondCollection interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ABM.Data.Services { using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using ABM.Model; /// <summary> /// The BackgroundFittedBondCollection interface. /// </summary> public interface IFittedBondCollection { #region Public Properties /// <summary> /// Gets or sets the last error message. /// </summary> string LastErrorMessage { get; set; } /// <summary> /// Gets or sets the n fit loop. /// </summary> int NFitLoops { get; set; } #endregion #region Public Methods and Operators /// <summary> /// The add. /// </summary> /// <param name="bond"> /// The bond. /// </param> void Add(Bond bond); /// <summary> /// The amount outstanding in billions. /// </summary> /// <returns> /// The <see cref="IList" />. /// </returns> IList<double> AmountOutstandingInBillions(); /// <summary> /// The bid ask spread. /// </summary> /// <returns> /// The <see cref="IList" />. /// </returns> IList<double> BidAskSpread(); /// <summary> /// The cheapness. /// </summary> /// <returns> /// The <see cref="IList" />. /// </returns> IList<double> Cheapness(); /// <summary> /// The coeffs. /// </summary> /// <returns> /// The <see cref="IList" />. /// </returns> IList<double> Coeffs(); /// <summary> /// The cost. /// </summary> /// <returns> /// The <see cref="double" />. /// </returns> double Cost { get; } /// <summary> /// The count. /// </summary> /// <returns> /// The <see cref="int"/>. /// </returns> int Size { get; } /// <summary> /// The evals. /// </summary> /// <returns> /// The <see cref="int" />. /// </returns> int Evals { get; } /// <summary> /// The fitted parameters. /// </summary> /// <returns> /// The <see cref="Vector" />. /// </returns> Vector<double> FittedParameters(); /// <summary> /// The fitted yield curve. /// </summary> /// <returns> /// The <see cref="Vector" />. /// </returns> IList<double> FittedAnchorYields { get; } /// <summary> /// The initialise. /// </summary> /// <param name="tickerStringList"> /// The ticker string list. /// </param> /// <param name="benchMarkList"> /// The bench mark list. /// </param> /// <param name="ctdList"> /// The ctd list. /// </param> /// <param name="weightList"> /// The weight list. /// </param> /// <param name="bidPriceList"> /// The bid price list. /// </param> /// <param name="askPriceList"> /// The ask price list. /// </param> /// <param name="asof"> /// The asof. /// </param> /// <param name="calculateYields"> /// The calculate yields. /// </param> /// <param name="anchorDates"> /// The anchor dates. /// </param> /// <param name="localCoeffFlags"> /// The extra Parameters. /// </param> void Initialise( IList<string> tickerStringList, IList<double> benchMarkList, IList<double> ctdList, IList<double> weightList, IList<double> bidPriceList, IList<double> askPriceList, object asof, bool calculateYields, IList<double> anchorDates, IList<bool> localCoeffFlags); /// <summary> /// The initialise extra parameters. /// </summary> /// <param name="coeffFlags"> /// The extra parameters. /// </param> void InitialiseCoeffFlags(IList<bool> coeffFlags); /// <summary> /// The initialise yield curve. /// </summary> /// <param name="anchorDays"> /// The anchor days. /// </param> void InitialiseYieldCurve(IList<double> anchorDays); /// <summary> /// The last fit length. /// </summary> /// <returns> /// The <see cref="double" />. /// </returns> double LastFitLength { get; } /// <summary> /// The last fit time. /// </summary> /// <returns> /// The <see cref="DateTime" />. /// </returns> DateTime LastFitTime { get; } /// <summary> /// The maturity. /// </summary> /// <returns> /// The <see cref="double[]" />. /// </returns> IList<double> Maturity(); /// <summary> /// The model clean price. /// </summary> /// <returns> /// The <see cref="double[]" />. /// </returns> IList<double> ModelCleanPrice(); /// <summary> /// The model clean price. /// </summary> /// <param name="ticker"> /// The ticker. /// </param> /// <returns> /// The <see cref="double"/>. /// </returns> double ModelCleanPrice(string ticker); /// <summary> /// The model yield. /// </summary> /// <returns> /// The <see cref="double[]" />. /// </returns> IList<double> ModelYield(); /// <summary> /// The start. /// </summary> /// <returns> /// The <see cref="bool" />. /// </returns> bool Start(); /// <summary> /// The status. /// </summary> /// <returns> /// The <see cref="string" />. /// </returns> string Status { get; } /// <summary> /// The stop. /// </summary> /// <returns> /// The <see cref="bool" />. /// </returns> bool Stop(); /// <summary> /// The update. /// </summary> /// <param name="tickerStringList"> /// The ticker string list. /// </param> /// <param name="bencchMarkList"> /// The bencch mark list. /// </param> /// <param name="ctdList"> /// The ctd list. /// </param> /// <param name="weightList"> /// The weight list. /// </param> /// <param name="bidPriceList"> /// The bid price list. /// </param> /// <param name="askPriceList"> /// The ask price list. /// </param> /// <param name="asof"> /// The asof. /// </param> /// <param name="calculateYields"> /// The calculate yields. /// </param> /// <param name="anchorDates"> /// The anchor dates. /// </param> /// <param name="extraParameters"> /// The extra Parameters. /// </param> /// <returns> /// The <see cref="bool"/>. /// </returns> bool Update( IList<string> tickerStringList, IList<double> bencchMarkList, IList<double> ctdList, IList<double> weightList, IList<double> bidPriceList, IList<double> askPriceList, object asof, bool calculateYields, IList<double> anchorDates, IList<bool> extraParameters); Bond GetBond(string ticker); #endregion } }
using System; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// A place (such as an event location) associated with the containing entity. The type of /// the association is determined by the rel attribute; the details of the location are /// contained in an embedded or linked-to Contact entry. /// A gd:where element is more general than a gd:geoPt element. The former identifies a place /// using a text description and/or a Contact entry, while the latter identifies a place /// using a specific geographic location. /// Properties /// Property Type Description /// @label? xs:string Specifies a user-readable label to distinguish this location from other locations. /// @rel? xs:string Specifies the relationship between the containing entity and the contained location. Possible values /// (see below) are defined by other elements. For example, gd:when defines http://schemas.google.com/g/2005#event. /// @valueString? xs:string A simple string value that can be used as a representation of this location. /// gd:entryLink? entryLink Entry representing location details. This entry should implement the Contact kind. /// rel values /// Value Description /// http://schemas.google.com/g/2005#event or not specified Place where the enclosing event takes place. /// http://schemas.google.com/g/2005#event.alternate A secondary location. For example, a remote /// site with a videoconference link to the main site. /// http://schemas.google.com/g/2005#event.parking A nearby parking lot. /// </summary> public class Where : IExtensionElementFactory { /// <summary> /// Constructs an empty Where instance /// </summary> public Where() { } /// <summary> /// default constructor, takes 3 parameters /// </summary> /// <param name="value">the valueString property value</param> /// <param name="label">label property value</param> /// <param name="rel">default for the Rel property value</param> public Where(string rel, string label, string value) { Rel = rel; Label = label; ValueString = value; } /// <summary> /// Rel property accessor /// </summary> public string Rel { get; set; } /// <summary> /// User-readable label that identifies this location. /// </summary> public string Label { get; set; } /// <summary> /// String description of the event places. /// </summary> public string ValueString { get; set; } /// <summary> /// Nested entry (optional). /// </summary> public EntryLink EntryLink { get; set; } #region overloaded for persistence /// <summary> /// Persistence method for the Where object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { writer.WriteStartElement(BaseNameTable.gDataPrefix, XmlName, BaseNameTable.gNamespace); writer.WriteAttributeString(GDataParserNameTable.XmlAttributeValueString, ValueString); if (Utilities.IsPersistable(Label)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeLabel, Label); } if (Utilities.IsPersistable(Rel)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, Rel); } if (EntryLink != null) { EntryLink.Save(writer); } writer.WriteEndElement(); } #endregion /// <summary> /// Relation type. Describes the meaning of this location. /// </summary> public class RelType { /// <summary> /// The standard relationship EVENT_ALTERNATE /// </summary> public const string EVENT = null; /// <summary> /// the alternate EVENT location /// </summary> public const string EVENT_ALTERNATE = BaseNameTable.gNamespacePrefix + "event.alternate"; /// <summary> /// the parking location /// </summary> public const string EVENT_PARKING = BaseNameTable.gNamespacePrefix + "event.parking"; } #region overloaded from IExtensionElementFactory ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { Tracing.TraceCall(); Where where = null; if (node != null) { object localname = node.LocalName; if (!localname.Equals(XmlName) || !node.NamespaceURI.Equals(XmlNameSpace)) { return null; } } where = new Where(); if (node != null) { if (node.Attributes != null) { if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null) { where.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeLabel] != null) { where.Label = node.Attributes[GDataParserNameTable.XmlAttributeLabel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeValueString] != null) { where.ValueString = node.Attributes[GDataParserNameTable.XmlAttributeValueString].Value; } } if (node.HasChildNodes) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == GDataParserNameTable.XmlEntryLinkElement) { if (where.EntryLink == null) { where.EntryLink = EntryLink.ParseEntryLink(childNode, parser); } else { throw new ArgumentException("Only one entryLink is allowed inside the g:where"); } } } } } return where; } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlWhereElement; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion } }
namespace Nancy.ModelBinding { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Nancy.Validation; /// <summary> /// A convenience class that contains various extension methods for modules. /// </summary> public static class ModuleExtensions { private static readonly string[] NoBlacklistedProperties = ArrayCache.Empty<string>(); /// <summary> /// Parses an array of expressions like <code>t =&gt; t.Property</code> to a list of strings containing the property names; /// </summary> /// <typeparam name="T">Type of the model</typeparam> /// <param name="expressions">Expressions that tell which property should be ignored</param> /// <returns>Array of strings containing the names of the properties.</returns> private static string[] ParseBlacklistedPropertiesExpressionTree<T>(this IEnumerable<Expression<Func<T, object>>> expressions) { return expressions.Select(p => p.GetTargetMemberInfo().Name).ToArray(); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Model adapter - cast to a model type to bind it</returns> public static dynamic Bind(this INancyModule module, params string[] blacklistedProperties) { return module.Bind(BindingConfig.Default, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Model adapter - cast to a model type to bind it</returns> public static dynamic Bind(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, null, configuration, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module) { return module.Bind(); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, params string[] blacklistedProperties) { return module.Bind(blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, params string[] blacklistedProperties) { var model = module.Bind<TModel>(blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.Bind<TModel>(blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module) { var model = module.Bind<TModel>(NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration) { return module.Bind(configuration); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { return module.Bind(configuration, blacklistedProperties); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperty">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, Expression<Func<TModel, object>> blacklistedProperty) { return module.Bind(configuration, new [] { blacklistedProperty }.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> public static TModel Bind<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.Bind(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params string[] blacklistedProperties) { var model = module.Bind<TModel>(configuration, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.Bind<TModel>(configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to a model and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <returns>Bound model instance</returns> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindAndValidate<TModel>(this INancyModule module, BindingConfig configuration) { var model = module.Bind<TModel>(configuration, NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties) { return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.BindTo(instance, BindingConfig.NoOverwrite, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance) { return module.BindTo(instance, BindingConfig.NoOverwrite, NoBlacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params string[] blacklistedProperties) { var model = module.BindTo(instance, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.BindTo(instance, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance) { var model = module.BindTo(instance, NoBlacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties) { dynamic adapter = new DynamicModelBinderAdapter(module.ModelBinderLocator, module.Context, instance, configuration, blacklistedProperties); return adapter; } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <example>this.Bind&lt;Person&gt;(p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { return module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); } /// <summary> /// Bind the incoming request to an existing instance /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> public static TModel BindTo<TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { return module.BindTo(instance, configuration, NoBlacklistedProperties); } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Property names to blacklist from binding</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params string[] blacklistedProperties) { var model = module.BindTo(instance, configuration, blacklistedProperties); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blacklistedProperties">Expressions that tell which property should be ignored</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> /// <example>this.BindToAndValidate(person, config, p =&gt; p.Name, p =&gt; p.Age)</example> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration, params Expression<Func<TModel, object>>[] blacklistedProperties) { var model = module.BindTo(instance, configuration, blacklistedProperties.ParseBlacklistedPropertiesExpressionTree()); module.Validate(model); return model; } /// <summary> /// Bind the incoming request to an existing instance and validate /// </summary> /// <typeparam name="TModel">Model type</typeparam> /// <param name="module">Current module</param> /// <param name="instance">The class instance to bind properties to</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <remarks><see cref="ModelValidationResult"/> is stored in NancyModule.ModelValidationResult and NancyContext.ModelValidationResult.</remarks> public static TModel BindToAndValidate<TModel>(this INancyModule module, TModel instance, BindingConfig configuration) { var model = module.BindTo(instance, configuration, NoBlacklistedProperties); module.Validate(model); return model; } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Reflection; namespace DBus { using Authentication; using Transports; public partial class Connection { Transport transport; internal Transport Transport { get { return transport; } set { transport = value; transport.Connection = this; } } protected Connection () {} internal Connection (Transport transport) { this.transport = transport; transport.Connection = this; } //should this be public? internal Connection (string address) { OpenPrivate (address); Authenticate (); } internal bool isConnected = false; public bool IsConnected { get { return isConnected; } } // TODO: Complete disconnection support internal bool isShared = false; public void Close () { if (isShared) throw new Exception ("Cannot disconnect a shared Connection"); if (!IsConnected) return; transport.Disconnect (); isConnected = false; } //should we do connection sharing here? public static Connection Open (string address) { Connection conn = new Connection (); conn.OpenPrivate (address); conn.Authenticate (); return conn; } internal void OpenPrivate (string address) { if (address == null) throw new ArgumentNullException ("address"); AddressEntry[] entries = Address.Parse (address); if (entries.Length == 0) throw new Exception ("No addresses were found"); //TODO: try alternative addresses if needed AddressEntry entry = entries[0]; Id = entry.GUID; Transport = Transport.Create (entry); isConnected = true; } internal UUID Id = UUID.Zero; void Authenticate () { if (transport != null) transport.WriteCred (); SaslClient auth = new SaslClient (); auth.Identity = transport.AuthString (); auth.stream = transport.Stream; auth.Peer = new SaslPeer (); auth.Peer.Peer = auth; auth.Peer.stream = transport.Stream; if (!auth.Authenticate ()) throw new Exception ("Authentication failure"); if (Id != UUID.Zero) if (auth.ActualId != Id) throw new Exception ("Authentication failure: Unexpected GUID"); if (Id == UUID.Zero) Id = auth.ActualId; isAuthenticated = true; } internal bool isAuthenticated = false; internal bool IsAuthenticated { get { return isAuthenticated; } } //Interlocked.Increment() handles the overflow condition for uint correctly, so it's ok to store the value as an int but cast it to uint int serial = 0; internal uint GenerateSerial () { return (uint)Interlocked.Increment (ref serial); } internal Message SendWithReplyAndBlock (Message msg) { PendingCall pending = SendWithReply (msg); return pending.Reply; } internal PendingCall SendWithReply (Message msg) { msg.ReplyExpected = true; if (msg.Header.Serial == 0) msg.Header.Serial = GenerateSerial (); // Should we throttle the maximum number of concurrent PendingCalls? // Should we support timeouts? PendingCall pending = new PendingCall (this); lock (pendingCalls) pendingCalls[msg.Header.Serial] = pending; Send (msg); return pending; } internal virtual uint Send (Message msg) { if (msg.Header.Serial == 0) msg.Header.Serial = GenerateSerial (); transport.WriteMessage (msg); return msg.Header.Serial; } Queue<Message> Inbound = new Queue<Message> (); //temporary hack internal void DispatchSignals () { lock (Inbound) { while (Inbound.Count != 0) { Message msg = Inbound.Dequeue (); HandleSignal (msg); } } } internal Thread mainThread = Thread.CurrentThread; //temporary hack public void Iterate () { mainThread = Thread.CurrentThread; Message msg = transport.ReadMessage (); HandleMessage (msg); DispatchSignals (); } internal void Dispatch () { while (transport.Inbound.Count != 0) { Message msg = transport.Inbound.Dequeue (); HandleMessage (msg); } DispatchSignals (); } internal virtual void HandleMessage (Message msg) { if (msg == null) return; //TODO: support disconnection situations properly and move this check elsewhere if (msg == null) throw new ArgumentNullException ("msg", "Cannot handle a null message; maybe the bus was disconnected"); //TODO: Restrict messages to Local ObjectPath? { object field_value = msg.Header[FieldCode.ReplySerial]; if (field_value != null) { uint reply_serial = (uint)field_value; PendingCall pending; lock (pendingCalls) { if (pendingCalls.TryGetValue (reply_serial, out pending)) { if (pendingCalls.Remove (reply_serial)) pending.Reply = msg; return; } } //we discard reply messages with no corresponding PendingCall if (Protocol.Verbose) Console.Error.WriteLine ("Unexpected reply message received: MessageType='" + msg.Header.MessageType + "', ReplySerial=" + reply_serial); return; } } switch (msg.Header.MessageType) { case MessageType.MethodCall: MethodCall method_call = new MethodCall (msg); HandleMethodCall (method_call); break; case MessageType.Signal: //HandleSignal (msg); lock (Inbound) Inbound.Enqueue (msg); break; case MessageType.Error: //TODO: better exception handling Error error = new Error (msg); string errMsg = String.Empty; if (msg.Signature.Value.StartsWith ("s")) { MessageReader reader = new MessageReader (msg); errMsg = reader.ReadString (); } Console.Error.WriteLine ("Remote Error: Signature='" + msg.Signature.Value + "' " + error.ErrorName + ": " + errMsg); break; case MessageType.Invalid: default: throw new Exception ("Invalid message received: MessageType='" + msg.Header.MessageType + "'"); } } Dictionary<uint,PendingCall> pendingCalls = new Dictionary<uint,PendingCall> (); //this might need reworking with MulticastDelegate internal void HandleSignal (Message msg) { Signal signal = new Signal (msg); //TODO: this is a hack, not necessary when MatchRule is complete MatchRule rule = new MatchRule (); rule.MessageType = MessageType.Signal; rule.Fields.Add (FieldCode.Interface, new MatchTest (signal.Interface)); rule.Fields.Add (FieldCode.Member, new MatchTest (signal.Member)); //rule.Fields.Add (FieldCode.Sender, new MatchTest (signal.Sender)); rule.Fields.Add (FieldCode.Path, new MatchTest (signal.Path)); Delegate dlg; if (Handlers.TryGetValue (rule, out dlg) && dlg != null) { MethodInfo mi = dlg.GetType ().GetMethod ("Invoke"); bool compatible = false; Signature inSig, outSig; if (TypeImplementer.SigsForMethod(mi, out inSig, out outSig)) if (outSig == Signature.Empty && inSig == msg.Signature) compatible = true; if (!compatible) { if (Protocol.Verbose) Console.Error.WriteLine ("Signal argument mismatch: " + signal.Interface + '.' + signal.Member); return; } //signals have no return value dlg.DynamicInvoke (MessageHelper.GetDynamicValues (msg, mi.GetParameters ())); } else { //TODO: how should we handle this condition? sending an Error may not be appropriate in this case if (Protocol.Verbose) Console.Error.WriteLine ("Warning: No signal handler for " + signal.Member); } } internal Dictionary<MatchRule,Delegate> Handlers = new Dictionary<MatchRule,Delegate> (); //very messy internal void MaybeSendUnknownMethodError (MethodCall method_call) { Message msg = MessageHelper.CreateUnknownMethodError (method_call); if (msg != null) Send (msg); } //not particularly efficient and needs to be generalized internal void HandleMethodCall (MethodCall method_call) { //TODO: Ping and Introspect need to be abstracted and moved somewhere more appropriate once message filter infrastructure is complete //FIXME: these special cases are slightly broken for the case where the member but not the interface is specified in the message if (method_call.Interface == "org.freedesktop.DBus.Peer") { switch (method_call.Member) { case "Ping": Send (MessageHelper.ConstructReply (method_call)); return; case "GetMachineId": if (MachineId != UUID.Zero) { Send (MessageHelper.ConstructReply (method_call, MachineId.ToString ())); return; } else { // Might want to send back an error here? } break; } } if (method_call.Interface == "org.freedesktop.DBus.Introspectable" && method_call.Member == "Introspect") { Introspector intro = new Introspector (); intro.root_path = method_call.Path; intro.WriteStart (); //FIXME: do this properly //this is messy and inefficient List<string> linkNodes = new List<string> (); int depth = method_call.Path.Decomposed.Length; foreach (ObjectPath pth in RegisteredObjects.Keys) { if (pth.Value == (method_call.Path.Value)) { ExportObject exo = (ExportObject)RegisteredObjects[pth]; exo.WriteIntrospect (intro); } else { for (ObjectPath cur = pth ; cur != null ; cur = cur.Parent) { if (cur.Value == method_call.Path.Value) { string linkNode = pth.Decomposed[depth]; if (!linkNodes.Contains (linkNode)) { intro.WriteNode (linkNode); linkNodes.Add (linkNode); } } } } } intro.WriteEnd (); Message reply = MessageHelper.ConstructReply (method_call, intro.xml); Send (reply); return; } BusObject bo; if (RegisteredObjects.TryGetValue (method_call.Path, out bo)) { ExportObject eo = (ExportObject)bo; eo.HandleMethodCall (method_call); } else { MaybeSendUnknownMethodError (method_call); } } Dictionary<ObjectPath,BusObject> RegisteredObjects = new Dictionary<ObjectPath,BusObject> (); //FIXME: this shouldn't be part of the core API //that also applies to much of the other object mapping code public object GetObject (Type type, string bus_name, ObjectPath path) { //if (type == null) // return GetObject (bus_name, path); //if the requested type is an interface, we can implement it efficiently //otherwise we fall back to using a transparent proxy if (type.IsInterface || type.IsAbstract) { return BusObject.GetObject (this, bus_name, path, type); } else { if (Protocol.Verbose) Console.Error.WriteLine ("Warning: Note that MarshalByRefObject use is not recommended; for best performance, define interfaces"); BusObject busObject = new BusObject (this, bus_name, path); DProxy prox = new DProxy (busObject, type); return prox.GetTransparentProxy (); } } public T GetObject<T> (string bus_name, ObjectPath path) { return (T)GetObject (typeof (T), bus_name, path); } [Obsolete ("Use the overload of Register() which does not take a bus_name parameter")] public void Register (string bus_name, ObjectPath path, object obj) { Register (path, obj); } [Obsolete ("Use the overload of Unregister() which does not take a bus_name parameter")] public object Unregister (string bus_name, ObjectPath path) { return Unregister (path); } public void Register (ObjectPath path, object obj) { ExportObject eo = ExportObject.CreateExportObject (this, path, obj); eo.Registered = true; //TODO: implement some kind of tree data structure or internal object hierarchy. right now we are ignoring the name and putting all object paths in one namespace, which is bad RegisteredObjects[path] = eo; } public object Unregister (ObjectPath path) { BusObject bo; if (!RegisteredObjects.TryGetValue (path, out bo)) throw new Exception ("Cannot unregister " + path + " as it isn't registered"); RegisteredObjects.Remove (path); ExportObject eo = (ExportObject)bo; eo.Registered = false; return eo.obj; } //these look out of place, but are useful internal protected virtual void AddMatch (string rule) { } internal protected virtual void RemoveMatch (string rule) { } // Maybe we should use XDG/basedir or check an env var for this? const string machineUuidFilename = @"/var/lib/dbus/machine-id"; static UUID? machineId = null; private static object idReadLock = new object (); internal static UUID MachineId { get { lock (idReadLock) { if (machineId != null) return (UUID)machineId; try { machineId = ReadMachineId (machineUuidFilename); } catch { machineId = UUID.Zero; } return (UUID)machineId; } } } static UUID ReadMachineId (string fname) { using (FileStream fs = File.OpenRead (fname)) { // Length is typically 33 (32 for the UUID, plus a linefeed) //if (fs.Length < 32) // return UUID.Zero; byte[] data = new byte[32]; int pos = 0; while (pos < data.Length) { int read = fs.Read (data, pos, data.Length - pos); if (read == 0) break; pos += read; } if (pos != data.Length) //return UUID.Zero; throw new Exception ("Insufficient data while reading GUID string"); return UUID.Parse (System.Text.Encoding.ASCII.GetString (data)); } } static Connection () { if (BitConverter.IsLittleEndian) NativeEndianness = EndianFlag.Little; else NativeEndianness = EndianFlag.Big; } internal static readonly EndianFlag NativeEndianness; } }
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 WebChat.Api.Areas.HelpPage.Models; namespace WebChat.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); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.Contracts; namespace System.Collections { #if !SILVERLIGHT public class ArrayList { public virtual int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return default(int); } set { Contract.Requires(value >= this.Count); } } extern public virtual int Count { get; } extern public virtual bool IsReadOnly { get; } extern public virtual bool IsFixedSize { get; } public virtual void TrimToSize() { //Contract.Requires(!this.IsReadOnly); //Contract.Requires(!this.IsFixedSize); } public virtual Array ToArray(Type type) { Contract.Requires(type != null); Contract.Ensures(Contract.Result<Array>() != null); return default(Array); } public virtual object[] ToArray() { Contract.Ensures(Contract.Result<object[]>() != null); return default(object[]); } public static ArrayList Synchronized(ArrayList list) { Contract.Requires(list != null); //Contract.Ensures(result.IsSynchronized); return default(ArrayList); } #if false public static IList Synchronized (IList list) { Contract.Requires(list != null); Contract.Ensures(result.IsSynchronized); return default(IList); } #endif public virtual void Sort(int index, int count, IComparer comparer) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Count); //Contract.Requires(!this.IsReadOnly); } public virtual void Sort(IComparer comparer) { //Contract.Requires(!this.IsReadOnly); } public virtual void Sort() { //Contract.Requires(!this.IsReadOnly); } public virtual ArrayList GetRange(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Count); return default(ArrayList); } public virtual void SetRange(int index, ICollection c) { Contract.Requires(c != null); Contract.Requires(index >= 0); Contract.Requires(index + c.Count <= Count); //Contract.Requires(!this.IsReadOnly); } public virtual void Reverse(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Count); //Contract.Requires(!this.IsReadOnly); } public virtual void Reverse() { //Contract.Requires(!this.IsReadOnly); } [Pure] public static ArrayList Repeat(object value, int count) { Contract.Requires(count >= 0); return default(ArrayList); } public virtual void RemoveRange(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= Count); //Contract.Requires(!this.IsReadOnly); //Contract.Requires(!this.IsFixedSize); } public static ArrayList ReadOnly(ArrayList list) { Contract.Requires(list != null); Contract.Ensures(Contract.Result<ArrayList>().IsReadOnly); Contract.Ensures(Contract.Result<ArrayList>() != null); return default(ArrayList); } public static IList ReadOnly(IList list) { Contract.Requires(list != null); Contract.Ensures(Contract.Result<IList>().IsReadOnly); Contract.Ensures(Contract.Result<IList>() != null); return default(IList); } [Pure] public virtual int LastIndexOf(object value, int startIndex, int count) { Contract.Requires(0 <= count); Contract.Requires(0 <= startIndex); Contract.Requires(startIndex + count <= Count); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); } [Pure] public virtual int LastIndexOf(object value, int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex < this.Count); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); } [Pure] public virtual int LastIndexOf(object value) { Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); } public virtual void InsertRange(int index, ICollection c) { Contract.Requires(c != null); Contract.Requires(index >= 0); Contract.Requires(index <= Count); //Contract.Requires(!this.IsReadOnly); //Contract.Requires(!this.IsFixedSize); } [Pure] public virtual int IndexOf(object value, int startIndex, int count) { Contract.Requires(0 <= count); Contract.Requires(0 <= startIndex); Contract.Requires(startIndex + count <= Count); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); } [Pure] public virtual int IndexOf(object value, int startIndex) { Contract.Requires(startIndex >= 0); Contract.Requires(startIndex < this.Count); Contract.Ensures(-1 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() < this.Count); return default(int); } [Pure] public virtual IEnumerator GetEnumerator(int index, int count) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Ensures(Contract.Result<IEnumerator>() != null); return default(IEnumerator); } public static ArrayList FixedSize(ArrayList list) { Contract.Requires(list != null); Contract.Ensures(Contract.Result<ArrayList>().IsFixedSize); return default(ArrayList); } public static IList FixedSize(IList list) { Contract.Requires(list != null); Contract.Ensures(Contract.Result<IList>().IsFixedSize); return default(IList); } public virtual void CopyTo(int index, Array array, int arrayIndex, int count) { Contract.Requires(array != null); Contract.Requires(array.Rank == 1); Contract.Requires(index >= 0); Contract.Requires(index < this.Count); Contract.Requires(arrayIndex >= 0); Contract.Requires(count >= 0); Contract.Requires(index + count <= this.Count); Contract.Requires(arrayIndex <= array.Length - count); } public virtual void CopyTo(Array array) { Contract.Requires(array != null); Contract.Requires(array.Rank == 1); Contract.Requires(this.Count <= array.Length); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public virtual int BinarySearch(object value, IComparer comparer) { Contract.Ensures(Contract.Result<int>() < this.Count); Contract.Ensures(~Contract.Result<int>() <= this.Count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public virtual int BinarySearch(object value) { Contract.Ensures(Contract.Result<int>() < this.Count); Contract.Ensures(~Contract.Result<int>() <= this.Count); return default(int); } [Pure] [Reads(ReadsAttribute.Reads.Owned)] public virtual int BinarySearch(int index, int count, object value, IComparer comparer) { Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(index <= this.Count - count); Contract.Ensures(Contract.Result<int>() - index < count); Contract.Ensures(~Contract.Result<int>() - index <= count); Contract.Ensures(Contract.Result<int>() >= index || ~Contract.Result<int>() >= index); return default(int); } public virtual void AddRange(ICollection c) { Contract.Requires(c != null); //Contract.Requires(!this.IsReadOnly); //Contract.Requires(!this.IsFixedSize); } public static ArrayList Adapter(IList list) { Contract.Requires(list != null); return default(ArrayList); } public ArrayList(ICollection c) { Contract.Requires(c != null); Contract.Ensures(this.Capacity == c.Count); Contract.Ensures(this.Count == c.Count); Contract.Ensures(!this.IsReadOnly); Contract.Ensures(!this.IsFixedSize); } public ArrayList(int capacity) { Contract.Requires(capacity >= 0); Contract.Ensures(capacity < 0 || this.Capacity >= capacity); Contract.Ensures(!this.IsReadOnly); Contract.Ensures(!this.IsFixedSize); } public ArrayList() { Contract.Ensures(this.Count == 0); Contract.Ensures(!this.IsReadOnly); Contract.Ensures(!this.IsFixedSize); } } #endif }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.Runtime.CompilerServices; namespace System { /// <summary> /// Extension methods for Span{T}, Memory{T}, and friends. /// </summary> public static partial class MemoryExtensions { /// <summary> /// Returns a value indicating whether the specified <paramref name="value"/> occurs within the <paramref name="span"/>. /// <param name="span">The source span.</param> /// <param name="value">The value to seek within the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param> /// </summary> public static bool Contains(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { return (IndexOf(span, value, comparisonType) >= 0); } /// <summary> /// Determines whether this <paramref name="span"/> and the specified <paramref name="other"/> span have the same characters /// when compared using the specified <paramref name="comparisonType"/> option. /// <param name="span">The source span.</param> /// <param name="other">The value to compare with the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param> /// </summary> public static bool Equals(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other) == 0); case StringComparison.CurrentCultureIgnoreCase: return (CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other) == 0); case StringComparison.InvariantCulture: return (CompareInfo.Invariant.CompareOptionNone(span, other) == 0); case StringComparison.InvariantCultureIgnoreCase: return (CompareInfo.Invariant.CompareOptionIgnoreCase(span, other) == 0); case StringComparison.Ordinal: return EqualsOrdinal(span, other); case StringComparison.OrdinalIgnoreCase: return EqualsOrdinalIgnoreCase(span, other); } Debug.Fail("StringComparison outside range"); return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EqualsOrdinal(this ReadOnlySpan<char> span, ReadOnlySpan<char> value) { if (span.Length != value.Length) return false; if (value.Length == 0) // span.Length == value.Length == 0 return true; return span.SequenceEqual(value); } [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool EqualsOrdinalIgnoreCase(this ReadOnlySpan<char> span, ReadOnlySpan<char> value) { if (span.Length != value.Length) return false; if (value.Length == 0) // span.Length == value.Length == 0 return true; return CompareInfo.EqualsOrdinalIgnoreCase(ref MemoryMarshal.GetReference(span), ref MemoryMarshal.GetReference(value), span.Length); } /// <summary> /// Compares the specified <paramref name="span"/> and <paramref name="other"/> using the specified <paramref name="comparisonType"/>, /// and returns an integer that indicates their relative position in the sort order. /// <param name="span">The source span.</param> /// <param name="other">The value to compare with the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="other"/> are compared.</param> /// </summary> public static int CompareTo(this ReadOnlySpan<char> span, ReadOnlySpan<char> other, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); switch (comparisonType) { case StringComparison.CurrentCulture: return CultureInfo.CurrentCulture.CompareInfo.CompareOptionNone(span, other); case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.CompareOptionIgnoreCase(span, other); case StringComparison.InvariantCulture: return CompareInfo.Invariant.CompareOptionNone(span, other); case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.CompareOptionIgnoreCase(span, other); case StringComparison.Ordinal: if (span.Length == 0 || other.Length == 0) return span.Length - other.Length; return string.CompareOrdinal(span, other); case StringComparison.OrdinalIgnoreCase: return CompareInfo.CompareOrdinalIgnoreCase(span, other); } Debug.Fail("StringComparison outside range"); return 0; } /// <summary> /// Reports the zero-based index of the first occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>. /// <param name="span">The source span.</param> /// <param name="value">The value to seek within the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param> /// </summary> public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); if (value.Length == 0) { return 0; } if (span.Length == 0) { return -1; } if (GlobalizationMode.Invariant) { return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.IndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); default: Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); return CompareInfo.Invariant.IndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); } } /// <summary> /// Reports the zero-based index of the last occurrence of the specified <paramref name="value"/> in the current <paramref name="span"/>. /// <param name="span">The source span.</param> /// <param name="value">The value to seek within the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param> /// </summary> public static int LastIndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); if (value.Length == 0) { return span.Length > 0 ? span.Length - 1 : 0; } if (span.Length == 0) { return -1; } if (GlobalizationMode.Invariant) { return CompareInfo.InvariantIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None, fromBeginning: false); } switch (comparisonType) { case StringComparison.CurrentCulture: case StringComparison.CurrentCultureIgnoreCase: return CultureInfo.CurrentCulture.CompareInfo.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); case StringComparison.InvariantCulture: case StringComparison.InvariantCultureIgnoreCase: return CompareInfo.Invariant.LastIndexOf(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); default: Debug.Assert(comparisonType == StringComparison.Ordinal || comparisonType == StringComparison.OrdinalIgnoreCase); return CompareInfo.Invariant.LastIndexOfOrdinal(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType) != CompareOptions.None); } } /// <summary> /// Copies the characters from the source span into the destination, converting each character to lowercase, /// using the casing rules of the specified culture. /// </summary> /// <param name="source">The source span.</param> /// <param name="destination">The destination span which contains the transformed characters.</param> /// <param name="culture">An object that supplies culture-specific casing rules.</param> /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten.</remarks> /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns> /// <exception cref="System.ArgumentNullException"> /// Thrown when <paramref name="culture"/> is null. /// </exception> public static int ToLower(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) TextInfo.ToLowerAsciiInvariant(source, destination); else culture.TextInfo.ChangeCaseToLower(source, destination); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to lowercase, /// using the casing rules of the invariant culture. /// </summary> /// <param name="source">The source span.</param> /// <param name="destination">The destination span which contains the transformed characters.</param> /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten.</remarks> /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns> public static int ToLowerInvariant(this ReadOnlySpan<char> source, Span<char> destination) { // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) TextInfo.ToLowerAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCaseToLower(source, destination); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to uppercase, /// using the casing rules of the specified culture. /// </summary> /// <param name="source">The source span.</param> /// <param name="destination">The destination span which contains the transformed characters.</param> /// <param name="culture">An object that supplies culture-specific casing rules.</param> /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten.</remarks> /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns> /// <exception cref="System.ArgumentNullException"> /// Thrown when <paramref name="culture"/> is null. /// </exception> public static int ToUpper(this ReadOnlySpan<char> source, Span<char> destination, CultureInfo culture) { if (culture == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.culture); // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) TextInfo.ToUpperAsciiInvariant(source, destination); else culture.TextInfo.ChangeCaseToUpper(source, destination); return source.Length; } /// <summary> /// Copies the characters from the source span into the destination, converting each character to uppercase /// using the casing rules of the invariant culture. /// </summary> /// <param name="source">The source span.</param> /// <param name="destination">The destination span which contains the transformed characters.</param> /// <remarks>If the source and destinations overlap, this method behaves as if the original values are in /// a temporary location before the destination is overwritten.</remarks> /// <returns>The number of characters written into the destination span. If the destination is too small, returns -1.</returns> public static int ToUpperInvariant(this ReadOnlySpan<char> source, Span<char> destination) { // Assuming that changing case does not affect length if (destination.Length < source.Length) return -1; if (GlobalizationMode.Invariant) TextInfo.ToUpperAsciiInvariant(source, destination); else CultureInfo.InvariantCulture.TextInfo.ChangeCaseToUpper(source, destination); return source.Length; } /// <summary> /// Determines whether the end of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option. /// </summary> /// <param name="span">The source span.</param> /// <param name="value">The sequence to compare to the end of the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param> public static bool EndsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); if (value.Length == 0) { return true; } if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant) { if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None) return span.EndsWith(value); return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(span.Length - value.Length), value) == 0) : false; } if (span.Length == 0) { return false; } return (comparisonType >= StringComparison.InvariantCulture) ? CompareInfo.Invariant.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) : CultureInfo.CurrentCulture.CompareInfo.IsSuffix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); } /// <summary> /// Determines whether the beginning of the <paramref name="span"/> matches the specified <paramref name="value"/> when compared using the specified <paramref name="comparisonType"/> option. /// </summary> /// <param name="span">The source span.</param> /// <param name="value">The sequence to compare to the beginning of the source span.</param> /// <param name="comparisonType">One of the enumeration values that determines how the <paramref name="span"/> and <paramref name="value"/> are compared.</param> public static bool StartsWith(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType) { string.CheckStringComparison(comparisonType); if (value.Length == 0) { return true; } if (comparisonType >= StringComparison.Ordinal || GlobalizationMode.Invariant) { if (string.GetCaseCompareOfComparisonCulture(comparisonType) == CompareOptions.None) return span.StartsWith(value); return (span.Length >= value.Length) ? (CompareInfo.CompareOrdinalIgnoreCase(span.Slice(0, value.Length), value) == 0) : false; } if (span.Length == 0) { return false; } return (comparisonType >= StringComparison.InvariantCulture) ? CompareInfo.Invariant.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)) : CultureInfo.CurrentCulture.CompareInfo.IsPrefix(span, value, string.GetCaseCompareOfComparisonCulture(comparisonType)); } /// <summary> /// Creates a new span over the portion of the target array. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Span<T> AsSpan<T>(this T[] array, int start) { if (array == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(); return default; } if (default(T) == null && array.GetType() != typeof(T[])) ThrowHelper.ThrowArrayTypeMismatchException(); if ((uint)start > (uint)array.Length) ThrowHelper.ThrowArgumentOutOfRangeException(); return new Span<T>(ref Unsafe.Add(ref Unsafe.As<byte, T>(ref array.GetRawSzArrayData()), start), array.Length - start); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text) { if (text == null) return default; return new ReadOnlySpan<char>(ref text.GetRawStringData(), text.Length); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentNullException">Thrown when <paramref name="text"/> is null.</exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start) { if (text == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), text.Length - start); } /// <summary> /// Creates a new readonly span over the portion of the target string. /// </summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlySpan<char> AsSpan(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlySpan<char>(ref Unsafe.Add(ref text.GetRawStringData(), start), length); } /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> public static ReadOnlyMemory<char> AsMemory(this string text) { if (text == null) return default; return new ReadOnlyMemory<char>(text, 0, text.Length); } /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index is not in range (&lt;0 or &gt;text.Length). /// </exception> public static ReadOnlyMemory<char> AsMemory(this string text, int start) { if (text == null) { if (start != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlyMemory<char>(text, start, text.Length - start); } /// <summary>Creates a new <see cref="ReadOnlyMemory{T}"/> over the portion of the target string.</summary> /// <param name="text">The target string.</param> /// <param name="start">The index at which to begin this slice.</param> /// <param name="length">The desired length for the slice (exclusive).</param> /// <remarks>Returns default when <paramref name="text"/> is null.</remarks> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified <paramref name="start"/> index or <paramref name="length"/> is not in range. /// </exception> public static ReadOnlyMemory<char> AsMemory(this string text, int start, int length) { if (text == null) { if (start != 0 || length != 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return default; } if ((uint)start > (uint)text.Length || (uint)length > (uint)(text.Length - start)) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start); return new ReadOnlyMemory<char>(text, start, length); } } }
using System; using System.Data; using Aranasoft.Cobweb.FluentMigrator.Extensions; using FluentMigrator; using FluentMigrator.SqlServer; namespace Aranasoft.Cobweb.EntityFrameworkCore.Validation.Tests.Support.Migrations { [Migration(12345, "Add Identity Tables")] public class ValidIdentityMigrations : Migration { public override void Up() { Create.Table("AspNetRoles") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetRoles")) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Name", col => col.AsString(256).Nullable()) .WithColumn("NormalizedName", col => col.AsString(256).Nullable()) ; Create.Index("RoleNameIndex") .OnTable("AspNetRoles") .OnColumn("NormalizedName", col => col.Unique().NullsNotDistinct()) ; IfDatabase(dbType => string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("AspNetUsers") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetUsers")) .WithColumn("AccessFailedCount", col => col.AsInt32().NotNullable()) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Email", col => col.AsString(256).Nullable()) .WithColumn("EmailConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnd", col => col.AsString().Nullable()) .WithColumn("NormalizedEmail", col => col.AsString(256).Nullable().Indexed("EmailIndex")) .WithColumn("NormalizedUserName", col => col.AsString(256).Nullable()) .WithColumn("PasswordHash", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumber", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumberConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("SecurityStamp", col => col.AsStringMax().Nullable()) .WithColumn("TwoFactorEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("UserName", col => col.AsString(256).Nullable()); }); IfDatabase(dbType => !string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("AspNetUsers") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_AspNetUsers")) .WithColumn("AccessFailedCount", col => col.AsInt32().NotNullable()) .WithColumn("ConcurrencyStamp", col => col.AsStringMax().Nullable()) .WithColumn("Email", col => col.AsString(256).Nullable()) .WithColumn("EmailConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("LockoutEnd", col => col.AsDateTimeOffset().Nullable()) .WithColumn("NormalizedEmail", col => col.AsString(256).Nullable().Indexed("EmailIndex")) .WithColumn("NormalizedUserName", col => col.AsString(256).Nullable()) .WithColumn("PasswordHash", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumber", col => col.AsStringMax().Nullable()) .WithColumn("PhoneNumberConfirmed", col => col.AsBoolean().NotNullable()) .WithColumn("SecurityStamp", col => col.AsStringMax().Nullable()) .WithColumn("TwoFactorEnabled", col => col.AsBoolean().NotNullable()) .WithColumn("UserName", col => col.AsString(256).Nullable()); }); Create.Index("UserNameIndex") .OnTable("AspNetUsers") .OnColumn("NormalizedUserName", col => col.Unique().NullsNotDistinct()) ; Create.Table("AspNetRoleClaims") .WithColumn("Id", col => col.AsInt32().NotNullable().Identity().PrimaryKey("PK_AspNetRoleClaims")) .WithColumn("ClaimType", col => col.AsStringMax().Nullable()) .WithColumn("ClaimValue", col => col.AsStringMax().Nullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetRoleClaims_RoleId") .ForeignKey("FK_AspNetRoleClaims_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserClaims") .WithColumn("Id", col => col.AsInt32().NotNullable().Identity().PrimaryKey("PK_AspNetUserClaims")) .WithColumn("ClaimType", col => col.AsStringMax().Nullable()) .WithColumn("ClaimValue", col => col.AsStringMax().Nullable()) .WithColumn("UserId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetUserClaims_UserId") .ForeignKey("FK_AspNetUserClaims_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserLogins") .WithColumn("LoginProvider", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserLogins")) .WithColumn("ProviderKey", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserLogins")) .WithColumn("ProviderDisplayName", col => col.AsStringMax().Nullable()) .WithColumn("UserId", col => col.AsInt32() .NotNullable() .Indexed("IX_AspNetUserLogins_UserId") .ForeignKey("FK_AspNetUserLogins_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserRoles") .WithColumn("UserId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserRoles") .ForeignKey("FK_AspNetUserRoles_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserRoles") .Indexed("IX_AspNetUserRoles_RoleId") .ForeignKey("FK_AspNetUserRoles_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; Create.Table("AspNetUserTokens") .WithColumn("UserId", col => col.AsInt32() .NotNullable() .PrimaryKey("PK_AspNetUserTokens") .ForeignKey("FK_AspNetUserTokens_AspNetUsers_UserId", "AspNetUsers", "Id") .OnDelete(Rule.Cascade)) .WithColumn("LoginProvider", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserTokens")) .WithColumn("Name", col => col.AsString(450).NotNullable().PrimaryKey("PK_AspNetUserTokens")) .WithColumn("Value", col => col.AsStringMax().Nullable()) ; IfDatabase(dbType => string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("TableBasedEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedEntity")) .WithColumn("Field", col => col.AsString(256).Nullable()) .WithColumn("NumberValue", col => col.AsString(20000).NotNullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedEntity_RoleId") .ForeignKey("FK_TableBasedEntity_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; }); IfDatabase(dbType => !string.Equals(dbType, "SQLite-Test", StringComparison.InvariantCultureIgnoreCase)) .Delegate(() => { Create.Table("TableBasedEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedEntity")) .WithColumn("Field", col => col.AsString(256).Nullable()) .WithColumn("NumberValue", col => col.AsDecimal(18, 2).NotNullable()) .WithColumn("RoleId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedEntity_RoleId") .ForeignKey("FK_TableBasedEntity_AspNetRoles_RoleId", "AspNetRoles", "Id") .OnDelete(Rule.Cascade)) ; }); Execute.Sql(@"CREATE VIEW ViewBasedEntities AS SELECT Id, Field, RoleId FROM TableBasedEntity"); Create.Table("TableBasedChildEntity") .WithColumn("Id", col => col.AsInt32().NotNullable().PrimaryKey("PK_TableBasedChildEntity")) .WithColumn("Name", col => col.AsString(20000).Nullable()) .WithColumn("ViewEntityId", col => col.AsInt32() .NotNullable() .Indexed("IX_TableBasedChildEntity_ViewEntityId")) ; } public override void Down() { if (Schema.Table("TableBasedChildEntity").Exists()) { Delete.Table("TableBasedChildEntity"); } Execute.Sql(@"DROP VIEW ViewBasedEntities"); if (Schema.Table("TableBasedEntity").Exists()) { Delete.Table("TableBasedEntity"); } if (Schema.Table("AspNetRoleClaims").Exists()) { Delete.Table("AspNetRoleClaims"); } if (Schema.Table("AspNetUserClaims").Exists()) { Delete.Table("AspNetUserClaims"); } if (Schema.Table("AspNetUserLogins").Exists()) { Delete.Table("AspNetUserLogins"); } if (Schema.Table("AspNetUserRoles").Exists()) { Delete.Table("AspNetUserRoles"); } if (Schema.Table("AspNetUserTokens").Exists()) { Delete.Table("AspNetUserTokens"); } if (Schema.Table("AspNetRoles").Exists()) { Delete.Table("AspNetRoles"); } if (Schema.Table("AspNetUsers").Exists()) { Delete.Table("AspNetUsers"); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using GodotTools.Build; using GodotTools.Ides.Rider; using GodotTools.Internals; using GodotTools.Utils; using JetBrains.Annotations; using static GodotTools.Internals.Globals; using File = GodotTools.Utils.File; namespace GodotTools { public static class BuildManager { private static readonly List<BuildInfo> BuildsInProgress = new List<BuildInfo>(); public const string PropNameMSBuildMono = "MSBuild (Mono)"; public const string PropNameMSBuildVs = "MSBuild (VS Build Tools)"; public const string PropNameMSBuildJetBrains = "MSBuild (JetBrains Rider)"; public const string PropNameDotnetCli = "dotnet CLI"; public const string MsBuildIssuesFileName = "msbuild_issues.csv"; public const string MsBuildLogFileName = "msbuild_log.txt"; private static void RemoveOldIssuesFile(BuildInfo buildInfo) { var issuesFile = GetIssuesFilePath(buildInfo); if (!File.Exists(issuesFile)) return; File.Delete(issuesFile); } private static void ShowBuildErrorDialog(string message) { GodotSharpEditor.Instance.ShowErrorDialog(message, "Build error"); GodotSharpEditor.Instance.BottomPanel.ShowBuildTab(); } public static void RestartBuild(BuildTab buildTab) => throw new NotImplementedException(); public static void StopBuild(BuildTab buildTab) => throw new NotImplementedException(); private static string GetLogFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildLogFileName); } private static string GetIssuesFilePath(BuildInfo buildInfo) { return Path.Combine(buildInfo.LogsDirPath, MsBuildIssuesFileName); } private static void PrintVerbose(string text) { if (Godot.OS.IsStdoutVerbose()) Godot.GD.Print(text); } public static bool Build(BuildInfo buildInfo) { if (BuildsInProgress.Contains(buildInfo)) throw new InvalidOperationException("A build is already in progress"); BuildsInProgress.Add(buildInfo); try { BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.GetBuildTabFor(buildInfo); buildTab.OnBuildStart(); // Required in order to update the build tasks list Internal.GodotMainIteration(); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = BuildSystem.Build(buildInfo); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); buildTab.OnBuildExit(exitCode == 0 ? BuildTab.BuildResults.Success : BuildTab.BuildResults.Error); return exitCode == 0; } catch (Exception e) { buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { BuildsInProgress.Remove(buildInfo); } } public static async Task<bool> BuildAsync(BuildInfo buildInfo) { if (BuildsInProgress.Contains(buildInfo)) throw new InvalidOperationException("A build is already in progress"); BuildsInProgress.Add(buildInfo); try { BuildTab buildTab = GodotSharpEditor.Instance.BottomPanel.GetBuildTabFor(buildInfo); try { RemoveOldIssuesFile(buildInfo); } catch (IOException e) { buildTab.OnBuildExecFailed($"Cannot remove issues file: {GetIssuesFilePath(buildInfo)}"); Console.Error.WriteLine(e); } try { int exitCode = await BuildSystem.BuildAsync(buildInfo); if (exitCode != 0) PrintVerbose($"MSBuild exited with code: {exitCode}. Log file: {GetLogFilePath(buildInfo)}"); buildTab.OnBuildExit(exitCode == 0 ? BuildTab.BuildResults.Success : BuildTab.BuildResults.Error); return exitCode == 0; } catch (Exception e) { buildTab.OnBuildExecFailed($"The build method threw an exception.\n{e.GetType().FullName}: {e.Message}"); Console.Error.WriteLine(e); return false; } } finally { BuildsInProgress.Remove(buildInfo); } } public static bool BuildProjectBlocking(string config, [CanBeNull] string platform = null) { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return true; // No solution to build // Make sure the API assemblies are up to date before building the project. // We may not have had the chance to update the release API assemblies, and the debug ones // may have been deleted by the user at some point after they were loaded by the Godot editor. string apiAssembliesUpdateError = Internal.UpdateApiAssembliesFromPrebuilt(config == "ExportRelease" ? "Release" : "Debug"); if (!string.IsNullOrEmpty(apiAssembliesUpdateError)) { ShowBuildErrorDialog("Failed to update the Godot API assemblies"); return false; } using (var pr = new EditorProgress("mono_project_debug_build", "Building project solution...", 1)) { pr.Step("Building project solution", 0); var buildInfo = new BuildInfo(GodotSharpDirs.ProjectSlnPath, targets: new[] {"Build"}, config, restore: true); // If a platform was not specified, try determining the current one. If that fails, let MSBuild auto-detect it. if (platform != null || OS.PlatformNameMap.TryGetValue(Godot.OS.GetName(), out platform)) buildInfo.CustomProperties.Add($"GodotTargetPlatform={platform}"); if (Internal.GodotIsRealTDouble()) buildInfo.CustomProperties.Add("GodotRealTIsDouble=true"); if (!Build(buildInfo)) { ShowBuildErrorDialog("Failed to build project solution"); return false; } } return true; } public static bool EditorBuildCallback() { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) return true; // No solution to build string editorScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor"); string playerScriptsMetadataPath = Path.Combine(GodotSharpDirs.ResMetadataDir, "scripts_metadata.editor_player"); CsProjOperations.GenerateScriptsMetadata(GodotSharpDirs.ProjectCsProjPath, editorScriptsMetadataPath); if (File.Exists(editorScriptsMetadataPath)) File.Copy(editorScriptsMetadataPath, playerScriptsMetadataPath); if (GodotSharpEditor.Instance.SkipBuildBeforePlaying) return true; // Requested play from an external editor/IDE which already built the project return BuildProjectBlocking("Debug"); } public static void Initialize() { // Build tool settings var editorSettings = GodotSharpEditor.Instance.GetEditorInterface().GetEditorSettings(); BuildTool msbuildDefault; if (OS.IsWindows) { if (RiderPathManager.IsExternalEditorSetToRider(editorSettings)) msbuildDefault = BuildTool.JetBrainsMsBuild; else msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildVs; } else { msbuildDefault = !string.IsNullOrEmpty(OS.PathWhich("dotnet")) ? BuildTool.DotnetCli : BuildTool.MsBuildMono; } EditorDef("mono/builds/build_tool", msbuildDefault); string hintString; if (OS.IsWindows) { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameMSBuildVs}:{(int)BuildTool.MsBuildVs}," + $"{PropNameMSBuildJetBrains}:{(int)BuildTool.JetBrainsMsBuild}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } else { hintString = $"{PropNameMSBuildMono}:{(int)BuildTool.MsBuildMono}," + $"{PropNameDotnetCli}:{(int)BuildTool.DotnetCli}"; } editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary { ["type"] = Godot.Variant.Type.Int, ["name"] = "mono/builds/build_tool", ["hint"] = Godot.PropertyHint.Enum, ["hint_string"] = hintString }); EditorDef("mono/builds/print_build_output", false); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; namespace Prism.Regions { /// <summary> /// Implementation of <see cref="IViewsCollection"/> that takes an <see cref="ObservableCollection{T}"/> of <see cref="ItemMetadata"/> /// and filters it to display an <see cref="INotifyCollectionChanged"/> collection of /// <see cref="object"/> elements (the items which the <see cref="ItemMetadata"/> wraps). /// </summary> public partial class ViewsCollection : IViewsCollection { private readonly ObservableCollection<ItemMetadata> subjectCollection; private readonly Dictionary<ItemMetadata, MonitorInfo> monitoredItems = new Dictionary<ItemMetadata, MonitorInfo>(); private readonly Predicate<ItemMetadata> filter; private Comparison<object> sort; private List<object> filteredItems = new List<object>(); /// <summary> /// Initializes a new instance of the <see cref="ViewsCollection"/> class. /// </summary> /// <param name="list">The list to wrap and filter.</param> /// <param name="filter">A predicate to filter the <paramref name="list"/> collection.</param> public ViewsCollection(ObservableCollection<ItemMetadata> list, Predicate<ItemMetadata> filter) { this.subjectCollection = list; this.filter = filter; this.MonitorAllMetadataItems(); this.subjectCollection.CollectionChanged += this.SourceCollectionChanged; this.UpdateFilteredItemsList(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Gets or sets the comparison used to sort the views. /// </summary> /// <value>The comparison to use.</value> public Comparison<object> SortComparison { get { return this.sort; } set { if (this.sort != value) { this.sort = value; this.UpdateFilteredItemsList(); this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } private IEnumerable<object> FilteredItems { get { return this.filteredItems; } } /// <summary> /// Determines whether the collection contains a specific value. /// </summary> /// <param name="value">The object to locate in the collection.</param> /// <returns><see langword="true" /> if <paramref name="value"/> is found in the collection; otherwise, <see langword="false" />.</returns> public bool Contains(object value) { return this.FilteredItems.Contains(value); } ///<summary> ///Returns an enumerator that iterates through the collection. ///</summary> ///<returns> ///A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. ///</returns> public IEnumerator<object> GetEnumerator() { return this.FilteredItems.GetEnumerator(); } ///<summary> ///Returns an enumerator that iterates through a collection. ///</summary> ///<returns> ///An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. ///</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Used to invoked the <see cref="CollectionChanged"/> event. /// </summary> /// <param name="e"></param> private void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { NotifyCollectionChangedEventHandler handler = this.CollectionChanged; if (handler != null) handler(this, e); } private void NotifyReset() { this.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } /// <summary> /// Removes all monitoring of underlying MetadataItems and re-adds them. /// </summary> private void ResetAllMonitors() { this.RemoveAllMetadataMonitors(); this.MonitorAllMetadataItems(); } /// <summary> /// Adds all underlying MetadataItems to the list from the subjectCollection /// </summary> private void MonitorAllMetadataItems() { foreach (var item in this.subjectCollection) { this.AddMetadataMonitor(item, this.filter(item)); } } private readonly Dictionary<ItemMetadata, IDisposable> _disposables = new Dictionary<ItemMetadata, IDisposable>(); /// <summary> /// Removes all monitored items from our monitoring list. /// </summary> private void RemoveAllMetadataMonitors() { foreach (var item in this.monitoredItems) { _disposables[item.Key].Dispose(); } this.monitoredItems.Clear(); } /// <summary> /// Adds handler to monitor the MetadatItem and adds it to our monitoring list. /// </summary> /// <param name="itemMetadata"></param> /// <param name="isInList"></param> private void AddMetadataMonitor(ItemMetadata itemMetadata, bool isInList) { var d = itemMetadata.MetadataChanged.Subscribe(args => { OnItemMetadataChanged(args.Sender, args); }); _disposables.Add(itemMetadata, d); this.monitoredItems.Add( itemMetadata, new MonitorInfo { IsInList = isInList }); } /// <summary> /// Unhooks from the MetadataItem change event and removes from our monitoring list. /// </summary> /// <param name="itemMetadata"></param> private void RemoveMetadataMonitor(ItemMetadata itemMetadata) { _disposables[itemMetadata].Dispose(); this.monitoredItems.Remove(itemMetadata); } /// <summary> /// Invoked when any of the underlying ItemMetadata items we're monitoring changes. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnItemMetadataChanged(object sender, EventArgs e) { ItemMetadata itemMetadata = (ItemMetadata) sender; // Our monitored item may have been removed during another event before // our OnItemMetadataChanged got called back, so it's not unexpected // that we may not have it in our list. MonitorInfo monitorInfo; bool foundInfo = this.monitoredItems.TryGetValue(itemMetadata, out monitorInfo); if (!foundInfo) return; if (this.filter(itemMetadata)) { if (!monitorInfo.IsInList) { // This passes our filter and wasn't marked // as in our list so we can consider this // an Add. monitorInfo.IsInList = true; this.UpdateFilteredItemsList(); NotifyAdd(itemMetadata.Item); } } else { // This doesn't fit our filter, we remove from our // tracking list, but should not remove any monitoring in // case it fits our filter in the future. monitorInfo.IsInList = false; this.RemoveFromFilteredList(itemMetadata.Item); } } /// <summary> /// The event handler due to changes in the underlying collection. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SourceCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: this.UpdateFilteredItemsList(); foreach (ItemMetadata itemMetadata in e.NewItems) { bool isInFilter = this.filter(itemMetadata); this.AddMetadataMonitor(itemMetadata, isInFilter); if (isInFilter) { NotifyAdd(itemMetadata.Item); } } // If we're sorting we can't predict how // the collection has changed on an add so we // resort to a reset notification. if (this.sort != null) { this.NotifyReset(); } break; case NotifyCollectionChangedAction.Remove: foreach (ItemMetadata itemMetadata in e.OldItems) { this.RemoveMetadataMonitor(itemMetadata); if (this.filter(itemMetadata)) { this.RemoveFromFilteredList(itemMetadata.Item); } } break; default: this.ResetAllMonitors(); this.UpdateFilteredItemsList(); this.NotifyReset(); break; } } private void NotifyAdd(object item) { int newIndex = this.filteredItems.IndexOf(item); this.NotifyAdd(new[] { item }, newIndex); } private void RemoveFromFilteredList(object item) { int index = this.filteredItems.IndexOf(item); this.UpdateFilteredItemsList(); this.NotifyRemove(new[] { item }, index); } private void UpdateFilteredItemsList() { this.filteredItems = this.subjectCollection.Where(i => this.filter(i)).Select(i => i.Item) .OrderBy<object, object>(o => o, new RegionItemComparer(this.SortComparison)).ToList(); } private class MonitorInfo { public bool IsInList { get; set; } } private class RegionItemComparer : Comparer<object> { private readonly Comparison<object> comparer; public RegionItemComparer(Comparison<object> comparer) { this.comparer = comparer; } public override int Compare(object x, object y) { if (this.comparer == null) { return 0; } return this.comparer(x, y); } } } }
/* ==================================================================== 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.XWPF.UserModel { using System; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; using NPOI.Util; /** * @author Philipp Epp * */ public class XWPFAbstractNum { private CT_AbstractNum ctAbstractNum; protected XWPFNumbering numbering; protected XWPFAbstractNum() { this.ctAbstractNum = null; this.numbering = null; } public XWPFAbstractNum(CT_AbstractNum abstractNum) { this.ctAbstractNum = abstractNum; } public XWPFAbstractNum(CT_AbstractNum ctAbstractNum, XWPFNumbering numbering) { this.ctAbstractNum = ctAbstractNum; this.numbering = numbering; } public CT_AbstractNum GetAbstractNum() { return ctAbstractNum; } public XWPFNumbering GetNumbering() { return numbering; } public CT_AbstractNum GetCTAbstractNum() { return ctAbstractNum; } public void SetNumbering(XWPFNumbering numbering) { this.numbering = numbering; } #region AbstractNum property /// <summary> /// Abstract Numbering Definition Type /// </summary> public MultiLevelType MultiLevelType { get { return EnumConverter.ValueOf<MultiLevelType, ST_MultiLevelType>(ctAbstractNum.multiLevelType.val); } set { ctAbstractNum.multiLevelType.val = EnumConverter.ValueOf<ST_MultiLevelType, MultiLevelType>(value); } } public string AbstractNumId { get { return ctAbstractNum.abstractNumId; } set { ctAbstractNum.abstractNumId = value; } } //square, dot, diamond private char[] lvlText = new char[] { '\u006e', '\u006c', '\u0075' }; internal void InitLvl() { List<CT_Lvl> list = new List<CT_Lvl>(); for (int i = 0; i < 9; i++) { CT_Lvl lvl = new CT_Lvl(); lvl.start.val = "1"; lvl.tentative = i==0? ST_OnOff.on : ST_OnOff.off; lvl.ilvl = i.ToString(); lvl.lvlJc.val = ST_Jc.left; lvl.numFmt.val = ST_NumberFormat.bullet; lvl.lvlText.val = lvlText[i % 3].ToString(); CT_Ind ind = lvl.pPr.AddNewInd(); ind.left = (420 * (i + 1)).ToString(); ind.hanging = 420; CT_Fonts fonts = lvl.rPr.AddNewRFonts(); fonts.ascii = "Wingdings"; fonts.hAnsi = "Wingdings"; fonts.hint = ST_Hint.@default; list.Add(lvl); } ctAbstractNum.lvl = list; } #endregion internal void SetLevelTentative(int lvl, bool tentative) { if (tentative) this.ctAbstractNum.lvl[lvl].tentative = ST_OnOff.on; else this.ctAbstractNum.lvl[lvl].tentative = ST_OnOff.off; } } /// <summary> /// Numbering Definition Type /// </summary> public enum MultiLevelType { /// <summary> /// Single Level Numbering Definition /// </summary> SingleLevel, /// <summary> /// Multilevel Numbering Definition /// </summary> Multilevel, /// <summary> /// Hybrid Multilevel Numbering Definition /// </summary> HybridMultilevel } /// <summary> /// Numbering Format /// </summary> public enum NumberFormat { /// <summary> /// Decimal Numbers /// </summary> Decimal, /// <summary> /// Uppercase Roman Numerals /// </summary> UpperRoman, /// <summary> /// Lowercase Roman Numerals /// </summary> LowerRoman, /// <summary> /// Uppercase Latin Alphabet /// </summary> UpperLetter, /// <summary> /// Lowercase Latin Alphabet /// </summary> LowerLetter, /// <summary> /// Ordinal /// </summary> Ordinal, /// <summary> /// Cardinal Text /// </summary> CardinalText, /// <summary> /// Ordinal Text /// </summary> OrdinalText, /// <summary> /// Hexadecimal Numbering /// </summary> Hex, /// <summary> /// Chicago Manual of Style /// </summary> Chicago, /// <summary> /// Ideographs /// </summary> IdeographDigital, /// <summary> /// Japanese Counting System /// </summary> JapaneseCounting, /// <summary> /// AIUEO Order Hiragana /// </summary> Aiueo, /// <summary> /// Iroha Ordered Katakana /// </summary> Iroha, /// <summary> /// Double Byte Arabic Numerals /// </summary> DecimalFullWidth, /// <summary> /// Single Byte Arabic Numerals /// </summary> DecimalHalfWidth, /// <summary> /// Japanese Legal Numbering /// </summary> JapaneseLegal, /// <summary> /// Japanese Digital Ten Thousand Counting System /// </summary> JapaneseDigitalTenThousand, /// <summary> /// Decimal Numbers Enclosed in a Circle /// </summary> DecimalEnclosedCircle, /// <summary> /// Double Byte Arabic Numerals Alternate /// </summary> DecimalFullWidth2, /// <summary> /// Full-Width AIUEO Order Hiragana /// </summary> AiueoFullWidth, /// <summary> /// Full-Width Iroha Ordered Katakana /// </summary> IrohaFullWidth, /// <summary> /// Initial Zero Arabic Numerals /// </summary> DecimalZero, /// <summary> /// Bullet /// </summary> Bullet, /// <summary> /// Korean Ganada Numbering /// </summary> Ganada, /// <summary> /// Korean Chosung Numbering /// </summary> Chosung, /// <summary> /// Decimal Numbers Followed by a Period /// </summary> DecimalEnclosedFullstop, /// <summary> /// Decimal Numbers Enclosed in Parenthesis /// </summary> DecimalEnclosedParen, /// <summary> /// Decimal Numbers Enclosed in a Circle /// </summary> DecimalEnclosedCircleChinese, /// <summary> /// Ideographs Enclosed in a Circle /// </summary> IdeographEnclosedCircle, /// <summary> /// Traditional Ideograph Format /// </summary> IdeographTraditional, /// <summary> /// Zodiac Ideograph Format /// </summary> IdeographZodiac, /// <summary> /// Traditional Zodiac Ideograph Format /// </summary> IdeographZodiacTraditional, /// <summary> /// Taiwanese Counting System /// </summary> TaiwaneseCounting, /// <summary> /// Traditional Legal Ideograph Format /// </summary> IdeographLegalTraditional, /// <summary> /// Taiwanese Counting Thousand System /// </summary> TaiwaneseCountingThousand, /// <summary> /// Taiwanese Digital Counting System /// </summary> TaiwaneseDigital, /// <summary> /// Chinese Counting System /// </summary> ChineseCounting, /// <summary> /// Chinese Legal Simplified Format /// </summary> ChineseLegalSimplified, /// <summary> /// Chinese Counting Thousand System /// </summary> ChineseCountingThousand, /// <summary> /// Korean Digital Counting System /// </summary> KoreanDigital, /// <summary> /// Korean Counting System /// </summary> KoreanCounting, /// <summary> /// Korean Legal Numbering /// </summary> KoreanLegal, /// <summary> /// Korean Digital Counting System Alternate /// </summary> KoreanDigital2, /// <summary> /// Vietnamese Numerals /// </summary> VietnameseCounting, /// <summary> /// Lowercase Russian Alphabet /// </summary> RussianLower, /// <summary> /// Uppercase Russian Alphabet /// </summary> RussianUpper, /// <summary> /// No Numbering /// </summary> None, /// <summary> /// Number With Dashes /// </summary> NumberInDash, /// <summary> /// Hebrew Numerals /// </summary> Hebrew1, /// <summary> /// Hebrew Alphabet /// </summary> Hebrew2, /// <summary> /// Arabic Alphabet /// </summary> ArabicAlpha, /// <summary> /// Arabic Abjad Numerals /// </summary> ArabicAbjad, /// <summary> /// Hindi Vowels /// </summary> HindiVowels, /// <summary> /// Hindi Consonants /// </summary> HindiConsonants, /// <summary> /// Hindi Numbers /// </summary> HindiNumbers, /// <summary> /// Hindi Counting System /// </summary> HindiCounting, /// <summary> /// Thai Letters /// </summary> ThaiLetters, /// <summary> /// Thai Numerals /// </summary> ThaiNumbers, /// <summary> /// Thai Counting System /// </summary> ThaiCounting, } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G11Level111111Child (editable child object).<br/> /// This is a generated base class of <see cref="G11Level111111Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G10Level11111"/> collection. /// </remarks> [Serializable] public partial class G11Level111111Child : BusinessBase<G11Level111111Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_1_1_Child_Name, "Level_1_1_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G11Level111111Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="G11Level111111Child"/> object.</returns> internal static G11Level111111Child NewG11Level111111Child() { return DataPortal.CreateChild<G11Level111111Child>(); } /// <summary> /// Factory method. Loads a <see cref="G11Level111111Child"/> object, based on given parameters. /// </summary> /// <param name="cQarentID1">The CQarentID1 parameter of the G11Level111111Child to fetch.</param> /// <returns>A reference to the fetched <see cref="G11Level111111Child"/> object.</returns> internal static G11Level111111Child GetG11Level111111Child(int cQarentID1) { return DataPortal.FetchChild<G11Level111111Child>(cQarentID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G11Level111111Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private G11Level111111Child() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="G11Level111111Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G11Level111111Child"/> object from the database, based on given criteria. /// </summary> /// <param name="cQarentID1">The CQarent ID1.</param> protected void Child_Fetch(int cQarentID1) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetG11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CQarentID1", cQarentID1).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cQarentID1); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G11Level111111Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G11Level111111Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddG11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="G11Level111111Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateG11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="G11Level111111Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G10Level11111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteG11Level111111Child", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_1_1_ID", parent.Level_1_1_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Resources; using System.Text; using System.Diagnostics; using System.Globalization; using System.Threading; using System.Runtime.Serialization; namespace System.Xml { /// <devdoc> /// <para>Returns detailed information about the last parse error, including the error /// number, line number, character position, and a text description.</para> /// </devdoc> [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class XmlException : SystemException { private readonly string _res; private readonly string[] _args; // this field is not used, it's here just V1.1 serialization compatibility private readonly int _lineNumber; private readonly int _linePosition; private readonly string _sourceUri; // message != null for V1 exceptions deserialized in Whidbey // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) private readonly string _message; protected XmlException(SerializationInfo info, StreamingContext context) : base(info, context) { _res = (string)info.GetValue("res", typeof(string)); _args = (string[])info.GetValue("args", typeof(string[])); _lineNumber = (int)info.GetValue("lineNumber", typeof(int)); _linePosition = (int)info.GetValue("linePosition", typeof(int)); // deserialize optional members _sourceUri = string.Empty; string version = null; foreach (SerializationEntry e in info) { switch (e.Name) { case "sourceUri": _sourceUri = (string)e.Value; break; case "version": version = (string)e.Value; break; } } if (version == null) { // deserializing V1 exception _message = CreateMessage(_res, _args, _lineNumber, _linePosition); } else { // deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message) _message = null; } } public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("res", _res); info.AddValue("args", _args); info.AddValue("lineNumber", _lineNumber); info.AddValue("linePosition", _linePosition); info.AddValue("sourceUri", _sourceUri); info.AddValue("version", "2.0"); } //provided to meet the ECMA standards public XmlException() : this(null) { } //provided to meet the ECMA standards public XmlException(string message) : this(message, ((Exception)null), 0, 0) { #if DEBUG Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!"); #endif } //provided to meet ECMA standards public XmlException(string message, Exception innerException) : this(message, innerException, 0, 0) { } //provided to meet ECMA standards public XmlException(string message, Exception innerException, int lineNumber, int linePosition) : this(message, innerException, lineNumber, linePosition, null) { } internal XmlException(string message, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(FormatUserMessage(message, lineNumber, linePosition), innerException) { HResult = HResults.Xml; _res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException); _args = new string[] { message }; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } internal XmlException(string res, string[] args) : this(res, args, null, 0, 0, null) { } internal XmlException(string res, string arg) : this(res, new string[] { arg }, null, 0, 0, null) { } internal XmlException(string res, string arg, string sourceUri) : this(res, new string[] { arg }, null, 0, 0, sourceUri) { } internal XmlException(string res, string arg, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, lineInfo, null) { } internal XmlException(string res, string arg, Exception innerException, IXmlLineInfo lineInfo) : this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) : this(res, args, lineInfo, null) { } internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) : this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri) { } internal XmlException(string res, string arg, int lineNumber, int linePosition) : this(res, new string[] { arg }, null, lineNumber, linePosition, null) { } internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) : this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition) : this(res, args, null, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) : this(res, args, null, lineNumber, linePosition, sourceUri) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) : this(res, args, innerException, lineNumber, linePosition, null) { } internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) : base(CreateMessage(res, args, lineNumber, linePosition), innerException) { HResult = HResults.Xml; _res = res; _args = args; _sourceUri = sourceUri; _lineNumber = lineNumber; _linePosition = linePosition; } private static string FormatUserMessage(string message, int lineNumber, int linePosition) { if (message == null) { return CreateMessage(SR.Xml_DefaultException, null, lineNumber, linePosition); } else { if (lineNumber == 0 && linePosition == 0) { // do not reformat the message when not needed return message; } else { // add line information return CreateMessage(SR.Xml_UserException, new string[] { message }, lineNumber, linePosition); } } } private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition) { try { string message; // No line information -> get resource string and return if (lineNumber == 0) { message = (args == null) ? res : string.Format(res, args); } // Line information is available -> we need to append it to the error message else { string lineNumberStr = lineNumber.ToString(CultureInfo.InvariantCulture); string linePositionStr = linePosition.ToString(CultureInfo.InvariantCulture); message = string.Format(res, args); message = SR.Format(SR.Xml_MessageWithErrorPosition, new string[] { message, lineNumberStr, linePositionStr }); } return message; } catch (MissingManifestResourceException) { return "UNKNOWN(" + res + ")"; } } internal static string[] BuildCharExceptionArgs(string data, int invCharIndex) { return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < data.Length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char[] data, int length, int invCharIndex) { Debug.Assert(invCharIndex < data.Length); Debug.Assert(invCharIndex < length); Debug.Assert(length <= data.Length); return BuildCharExceptionArgs(data[invCharIndex], invCharIndex + 1 < length ? data[invCharIndex + 1] : '\0'); } internal static string[] BuildCharExceptionArgs(char invChar, char nextChar) { string[] aStringList = new string[2]; // for surrogate characters include both high and low char in the message so that a full character is displayed if (XmlCharType.IsHighSurrogate(invChar) && nextChar != 0) { int combinedChar = XmlCharType.CombineSurrogateChar(nextChar, invChar); ReadOnlySpan<char> invAndNextChars = stackalloc char[] { invChar, nextChar }; aStringList[0] = new string(invAndNextChars); aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", combinedChar); } else { // don't include 0 character in the string - in means eof-of-string in native code, where this may bubble up to if ((int)invChar == 0) { aStringList[0] = "."; } else { aStringList[0] = invChar.ToString(); } aStringList[1] = string.Format(CultureInfo.InvariantCulture, "0x{0:X2}", (int)invChar); } return aStringList; } public int LineNumber { get { return _lineNumber; } } public int LinePosition { get { return _linePosition; } } public string SourceUri { get { return _sourceUri; } } public override string Message { get { return (_message == null) ? base.Message : _message; } } internal string ResString { get { return _res; } } internal static bool IsCatchableException(Exception e) { Debug.Assert(e != null, "Unexpected null exception"); return !( e is OutOfMemoryException || e is NullReferenceException ); } }; }
// <copyright file=AngleMethods.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // 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. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:57 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.Diagnostics; namespace HciLab.Utilities.Mathematics.Geometry3D { public sealed class AngleMethods { public enum AngleOrientation : short { XPlane = 0, YPlane = 1, ZPlane = 2 }; public static double Angle(Vector3 pDirection, Plane pPlane) { return System.Math.Asin( System.Math.Abs(Vector3.DotProduct(pDirection, pPlane.Normal)) / (pDirection.GetLength() * pPlane.Normal.GetLength()) ); } #region Ray-Plane public static double Angle(Ray pRay, Plane pPlane) { return System.Math.Acos(Vector3.DotProduct(pRay.Direction, pPlane.Normal) / (pRay.Direction.GetLength() * pPlane.Normal.GetLength())); } public static double Angle(Ray pRay, Plane pPlane, AngleOrientation pOrientation) { Ray senkrechte = Ray.CreateUsingOrginAndDirection(pRay.Origin, pPlane.Normal); IntersectionPair schnittEbeneSenkrechte = IntersectionMethods.Intersects(senkrechte, pPlane); IntersectionPair schnittEbeneGerade = IntersectionMethods.Intersects(pRay, pPlane); if (schnittEbeneSenkrechte.IntersectionOccurred == false ||schnittEbeneGerade.IntersectionOccurred == false) throw new NotImplementedException(); Double a = 0, c = 0, b = 0; Vector2 A, B, C; if (pOrientation == AngleOrientation.XPlane) { A = new Vector2(schnittEbeneGerade.IntersectionPoint.Z, schnittEbeneGerade.IntersectionPoint.Y); B = new Vector2(pRay.Origin.Z, pRay.Origin.Y); C = new Vector2(schnittEbeneSenkrechte.IntersectionPoint.Z, schnittEbeneSenkrechte.IntersectionPoint.Y); } else if (pOrientation == AngleOrientation.YPlane) { A = new Vector2(schnittEbeneGerade.IntersectionPoint.Z, schnittEbeneGerade.IntersectionPoint.X); B = new Vector2(pRay.Origin.Z, pRay.Origin.X); C = new Vector2(schnittEbeneSenkrechte.IntersectionPoint.Z, schnittEbeneSenkrechte.IntersectionPoint.X); } else if (pOrientation == AngleOrientation.ZPlane) { A = new Vector2(schnittEbeneGerade.IntersectionPoint.Y, schnittEbeneGerade.IntersectionPoint.X); B = new Vector2(pRay.Origin.Y, pRay.Origin.X); C = new Vector2(schnittEbeneSenkrechte.IntersectionPoint.Y, schnittEbeneSenkrechte.IntersectionPoint.X); } else { throw new Exception(); } a = Geometry2D.DistanceMethods.Distance(C, B); b = Geometry2D.DistanceMethods.Distance(A, C); c = Geometry2D.DistanceMethods.Distance(A, B); double ret; if (A.Y < C.Y && B.X >= C.X) // 0-90 { ret = System.Math.Asin(a / c); } else if (A.Y >= C.Y && B.X >= C.X) // 90-180 { ret = (System.Math.PI - System.Math.Asin(a / c)); } else if (A.Y >= C.Y && B.X < C.X) //180-270 { ret = (System.Math.PI + System.Math.Asin(a / c)); //k } else if (A.Y < C.Y && B.X < C.X) //270-360 { ret = ((2 * System.Math.PI) - System.Math.Asin(a / c)); } else throw new Exception(); return (ret - (Math.PI / 2))*-1; } #endregion #region Plane-Plane public static double Angle(Plane e1, Plane e2) { return System.Math.Acos(Vector3.DotProduct(e1.Normal, e2.Normal) / (e1.Normal.GetLength() * e2.Normal.GetLength())); } #endregion public static double ToDegree(double rad) { return ((180 / System.Math.PI) * rad); } /*public static double MapToPi(double rad) { return rad % Math.PI; }*/ #region Private Constructor private AngleMethods() { } #endregion public static double Angle(Ray pRay1, Ray pRay2, AngleOrientation pOrientation) { Plane p = null; if (pOrientation == AngleOrientation.XPlane) { p = Plane.CreateZPlane(); } else if (pOrientation == AngleOrientation.YPlane) { p = Plane.CreateXPlane(); } else if (pOrientation == AngleOrientation.ZPlane) { p = Plane.CreateYPlane(); } else { throw new Exception(); } if (pOrientation == AngleOrientation.YPlane) Debugger.Break(); Double a1 = Angle(pRay1, p, pOrientation); Double a2 = Angle(pRay2, p, pOrientation); return a2 - a1; } /// <summary> /// Angle in B with Ray to A and C /// /// calc Beta in ABC /// </summary> /// <param name="pA"></param> /// <param name="pB"></param> /// <param name="pC"></param> /// <param name="v"></param> /// <returns></returns> public static double Angle(Vector3 pA, Vector3 pB, Vector3 pC, AngleOrientation pOrientation) { Double a = 0, c = 0, b = 0; Vector2 A, B, C; if (pOrientation == AngleOrientation.XPlane) { A = new Vector2(pA.Z, pA.Y); B = new Vector2(pB.Z, pB.Y); C = new Vector2(pC.Z, pC.Y); } else if (pOrientation == AngleOrientation.YPlane) { A = new Vector2(pA.Z, pA.X); B = new Vector2(pB.Z, pB.X); C = new Vector2(pC.Z, pC.X); } else if (pOrientation == AngleOrientation.ZPlane) { A = new Vector2(pA.Y, pA.X); B = new Vector2(pB.Y, pB.X); C = new Vector2(pC.Y, pC.X); } else { throw new Exception(); } a = Geometry2D.DistanceMethods.Distance(C, B); b = Geometry2D.DistanceMethods.Distance(A, C); c = Geometry2D.DistanceMethods.Distance(A, B); if (a == 0 || c == 0) throw new ArgumentOutOfRangeException(); if (C.Y < A.Y) return - Math.Acos((a * a - b * b + c * c) / (2 * a * c)); else return Math.Acos((a * a - b * b + c * c) / (2 * a * c)); } } }
using System; using System.Drawing; using System.Runtime.InteropServices; using System.Windows.Forms; namespace GuruComponents.CodeEditor.Library.Win32 { public sealed class NativeMethods { private NativeMethods() { } #region uxTheme.dll [DllImport("uxtheme.dll", SetLastError = true, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr OpenThemeData(IntPtr hwnd, [MarshalAs(UnmanagedType.LPWStr)] string pszClassList); [DllImport("uxtheme.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CloseThemeData(IntPtr hTheme); [DllImport("uxtheme.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool IsThemeActive(); [DllImport("uxtheme.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref APIRect rect, ref APIRect clipRect); [DllImport("uxtheme.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int DrawThemeText(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, string pszText, int iCharCount, uint dwTextFlags, uint dwTextFlags2, [MarshalAs(UnmanagedType.Struct)] ref APIRect rect); [DllImport("uxtheme.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetThemeColor(IntPtr hTheme, int iPartId, int iStateId, int iPropId, out ulong color); /* [DllImportAttribute( "uxtheme.dll")] public static extern void GetThemeBackgroundContentRect( int hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pBoundingRect, ref RECT pContentRect ); [DllImportAttribute( "uxtheme.dll" )] public static extern void GetThemeBackgroundExtent( int hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pContentRect, ref RECT pExtentRect ); [DllImportAttribute( "uxtheme.dll")] public static extern uint GetThemePartSize( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, IntPtr prc, int sizeType, out SIZE psz ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern uint GetThemeTextExtent( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, string pszText, int iCharCount, uint dwTextFlags, [MarshalAs( UnmanagedType.Struct )] ref RECT pBoundingRect, out RECT pExtentRect ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeTextMetrics( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, out TEXTMETRIC ptm ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeBackgroundRegion( IntPtr hTheme, int iPartId, int iStateId, RECT pRect, out IntPtr pRegion ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong HitTestThemeBackground( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ulong dwOptions, RECT pRect, IntPtr hrgn, POINT ptTest, out uint wHitTestCode ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong DrawThemeLine( IntPtr hTheme, IntPtr hdc, int iStateId, RECT pRect, ulong dwDtlFlags ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong DrawThemeEdge( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, RECT pDestRect, uint uEdge, uint uFlags, out RECT contentRect ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong DrawThemeBorder( IntPtr hTheme, IntPtr hdc, int iStateId, RECT pRect ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong DrawThemeIcon( IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, RECT pRect, IntPtr himl, int iImageIndex ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern bool IsThemePartDefined( IntPtr hTheme, int iPartId, int iStateId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern bool IsThemeBackgroundPartiallyTransparent( IntPtr hTheme, int iPartId, int iStateId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern int GetThemeColor( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out ulong color ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeMetric( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int iVal ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeString( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out string pszBuff, int cchMaxBuffChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeBool( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out bool fVal ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeInt( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int iVal ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeEnumValue( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int iVal ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemePosition( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out POINT point ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeFont( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out LOGFONT font ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeRect( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out RECT pRect ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeMargins( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out MARGINS margins ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeIntList( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out INTLIST intList ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemePropertyOrigin( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out int origin ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong SetWindowTheme( IntPtr hwnd, string pszSubAppName, string pszSubIdList ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeFilename( IntPtr hTheme, int iPartId, int iStateId, int iPropId, out string pszThemeFileName, int cchMaxBuffChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeSysColor( IntPtr hTheme, int iColorId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern IntPtr GetThemeSysColorBrush( IntPtr hTheme, int iColorId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern int GetThemeSysSize( IntPtr hTheme, int iSizeId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern bool GetThemeSysBool( IntPtr hTheme, int iBoolId ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeSysFont( IntPtr hTheme, int iFontId, out LOGFONT lf ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeSysString( IntPtr hTheme, int iStringId, out string pszStringBuff, int cchMaxStringChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeSysInt( IntPtr hTheme, int iIntId, out int iValue ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern bool IsAppThemed(); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern IntPtr GetWindowTheme( IntPtr hwnd ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong EnableThemeDialogTexture( IntPtr hwnd, bool fEnable ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern bool IsThemeDialogTextureEnabled( IntPtr hwnd ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeAppProperties(); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern void SetThemeAppProperties( ulong dwFlags ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetCurrentThemeName( out string pszThemeFileName, int cchMaxNameChars, out string pszColorBuff, int cchMaxColorChars, out string pszSizeBuff, int cchMaxSizeChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeDocumentationProperty( string pszThemeName, string pszPropertyName, out string pszValueBuff, int cchMaxValChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeLastErrorContext( out THEME_ERROR_CONTEXT context ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong FormatThemeMessage( ulong dwLanguageId, THEME_ERROR_CONTEXT context, out string pszMessageBuff, int cchMaxMessageChars ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern ulong GetThemeImageFromParent( IntPtr hwnd, IntPtr hdc, RECT rc ); [DllImportAttribute( "uxtheme.dll", CharSet=CharSet.Auto )] public static extern IntPtr DrawThemeParentBackground( IntPtr hwnd, IntPtr hdc, ref RECT prc ); */ #endregion [DllImport("imm32.dll")] public static extern IntPtr ImmGetDefaultIMEWnd(IntPtr hWnd); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, COMPOSITIONFORM lParam); [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, LogFont lParam); [DllImport("user32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int DrawText(IntPtr hDC, string lpString, int nCount, ref APIRect Rect, int wFormat); public const int GWL_STYLE = -16; public const int WS_CHILD = 0x40000000; [DllImport("gdi32", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern int EnumFontFamiliesEx(IntPtr hDC, [MarshalAs(UnmanagedType.LPStruct)] LogFont lf, FONTENUMPROC proc, Int64 LParam, Int64 DW); [DllImport("shlwapi.dll", SetLastError = true)] public static extern int SHAutoComplete(IntPtr hWnd, UInt32 flags); [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.DLL")] public static extern IntPtr GetWindowRect(IntPtr hWND, ref APIRect Rect); [DllImport("user32.dll", EntryPoint = "SendMessage")] public static extern int SendMessage(IntPtr hWND, int message, int WParam, int LParam); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetBkColor(IntPtr hDC, int crColor); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetBkMode(IntPtr hDC, int Mode); [DllImport("user32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr ReleaseDC(IntPtr hWND, IntPtr hDC); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr DeleteDC(IntPtr hDC); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr GdiFlush(); [DllImport("user32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr GetWindowDC(IntPtr hWND); [DllImport("user32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr GetDC(IntPtr hWND); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth, int nHeight); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr DeleteObject(IntPtr hObject); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetTextColor(IntPtr hDC); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetTextColor(IntPtr hDC, int crColor); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetBkColor(IntPtr hDC); [DllImport("gdi32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetBkMode(IntPtr hDC); [DllImport("user32", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int DrawFocusRect(IntPtr hDC, ref APIRect rect); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateSolidBrush(int crColor); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int Rectangle(IntPtr hDC, int left, int top, int right, int bottom); [DllImport("gdi32.DLL", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateHatchBrush(int Style, int crColor); [DllImport("user32.DLL", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int TabbedTextOut(IntPtr hDC, int x, int y, string lpString, int nCount, int nTabPositions, ref int lpnTabStopPositions, int nTabOrigin); [DllImport("gdi32.dll", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr BitBlt(IntPtr hDestDC, int x, int y, int nWidth, int nHeight, IntPtr hSrcDC, int xSrc, int ySrc, int dwRop); [DllImport("user32.dll", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int FillRect(IntPtr hDC, ref APIRect rect, IntPtr hBrush); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetTextFace(IntPtr hDC, int nCount, string lpFacename); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int GetTextMetrics(IntPtr hDC, ref GDITextMetric TextMetric); [DllImport("gdi32.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreateFontIndirect([MarshalAs(UnmanagedType.LPStruct)]LogFont LogFont); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] public static extern int GetTabbedTextExtent(IntPtr hDC, string lpString, int nCount, int nTabPositions, ref int lpnTabStopPositions); [DllImport("user32.dll", SetLastError = false, CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int InvertRect(IntPtr hDC, ref APIRect rect); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreatePen(int nPenStyle, int nWidth, int crColor); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetBrushOrgEx(IntPtr hDC, int x, int y, ref APIPoint p); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr CreatePatternBrush(IntPtr hBMP); [DllImport("User32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int ShowWindow(IntPtr hWnd, short cmdShow); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr MoveToEx(IntPtr hDC, int x, int y, ref APIPoint lpPoint); [DllImport("gdi32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern IntPtr LineTo(IntPtr hDC, int x, int y); [DllImport("user32", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern UInt16 GetAsyncKeyState(int vKey); public static bool IsKeyPressed(Keys k) { int s = (int)NativeMethods.GetAsyncKeyState((int)k); s = (s & 0x8000) >> 15; return (s == 1); } //--------------------------------------- //helper , return DC of a control public static IntPtr ControlDC(Control control) { return GetDC(control.Handle); } //--------------------------------------- //--------------------------------------- //helper , convert from and to colors from int values public static int ColorToInt(Color color) { return (color.B << 16 | color.G << 8 | color.R); } public static Color IntToColor(int color) { int b = (color >> 16) & 0xFF; int g = (color >> 8) & 0xFF; int r = (color) & 0xFF; return Color.FromArgb(r, g, b); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using Gibraltar; using JetBrains.Annotations; using Archichect.Markers; using Archichect.Matching; namespace Archichect { public abstract class ItemSegment { [NotNull] private readonly ItemType _type; [NotNull] public readonly string[] Values; [NotNull] public readonly string[] CasedValues; private readonly int _hash; protected ItemSegment([NotNull] ItemType type, [NotNull] string[] values) { if (type == null) { throw new ArgumentNullException(nameof(type)); } _type = type; for (int i = 0; i < values.Length; i++) { if (values[i] != null && values[i].Length < 50) { values[i] = string.Intern(values[i]); } } IEnumerable<string> enoughValues = values.Length < type.Length ? values.Concat(Enumerable.Range(0, type.Length - values.Length).Select(i => "")) : values; Values = values == enoughValues ? values : enoughValues.ToArray(); CasedValues = type.IgnoreCase ? enoughValues.Select(v => v.ToUpperInvariant()).ToArray() : Values; unchecked { int h = _type.GetHashCode(); foreach (var t in CasedValues) { if (t == null) { h *= 11; } else { h = 157204211 * h + t.GetHashCode(); } } _hash = h; } } public ItemType Type => _type; [DebuggerStepThrough] protected bool EqualsSegment(ItemSegment other) { if (other == null) { return false; } else if (ReferenceEquals(other, this)) { return true; } else if (other._hash != _hash) { return false; } else if (!Type.Equals(other.Type)) { return false; } else if (Values.Length != other.Values.Length) { return false; } else { for (int i = 0; i < CasedValues.Length; i++) { if (CasedValues[i] != other.CasedValues[i]) { return false; } } return true; } } [DebuggerStepThrough] protected int SegmentHashCode() { return _hash; } } public sealed class ItemTail : ItemSegment { private ItemTail([NotNull]ItemType type, [NotNull, ItemNotNull] string[] values) : base(type, values) { } public static ItemTail New(Intern<ItemTail> cache, [NotNull] ItemType type, [NotNull, ItemNotNull] string[] values) { return cache.GetReference(new ItemTail(type, values)); } [ExcludeFromCodeCoverage] public override string ToString() { return "ItemTail(" + Type + ":" + string.Join(":", Values) + ")"; } public override bool Equals(object other) { return EqualsSegment(other as ItemTail); } [DebuggerHidden] public override int GetHashCode() { return SegmentHashCode(); } } // See http://stackoverflow.com/questions/31562791/what-makes-the-visual-studio-debugger-stop-evaluating-a-tostring-override [DebuggerDisplay("{" + nameof(ToString) + "()}")] public abstract class AbstractItem<TItem> : ItemSegment, IMatchableObject where TItem : AbstractItem<TItem> { private string _asString; private string _asFullString; [NotNull] public abstract IMarkerSet MarkerSet { get; } protected AbstractItem([NotNull] ItemType type, string[] values) : base(type, values) { if (type.Length < values.Length) { throw new ArgumentException( $"ItemType '{type.Name}' is defined as '{type}' with {type.Length} fields, but item is created with {values.Length} fields '{string.Join(":", values)}'", nameof(values)); } } public string Name => AsString(); public bool IsEmpty() => Values.All(s => s == ""); public string GetCasedValue(int i) { return i < 0 || i >= CasedValues.Length ? null : CasedValues[i]; } [DebuggerStepThrough] public override bool Equals(object obj) { AbstractItem<TItem> other = obj as AbstractItem<TItem>; return other != null && EqualsSegment(other); } [DebuggerHidden] public override int GetHashCode() { return SegmentHashCode(); } [ExcludeFromCodeCoverage] public override string ToString() { return AsFullString(300); } [NotNull] public string AsFullString(int maxLength = 250) { if (_asFullString == null) { string s = AsString(); _asFullString = Type.Name + ":" + s + MarkerSet.AsFullString(maxLength - s.Length); } return _asFullString; } protected void MarkersHaveChanged() { _asFullString = null; } public bool IsMatch(IEnumerable<CountPattern<IMatcher>.Eval> evals) { return MarkerSet.IsMatch(evals); } [NotNull] public string AsString() { if (_asString == null) { var sb = new StringBuilder(); string sep = ""; for (int i = 0; i < Type.Length; i++) { sb.Append(sep); sb.Append(Values[i]); sep = i < Type.Length - 1 && Type.Keys[i + 1] == Type.Keys[i] ? ";" : ":"; } _asString = sb.ToString(); } return _asString; } public static Dictionary<TItem, TDependency[]> CollectIncomingDependenciesMap<TDependency>( [NotNull, ItemNotNull] IEnumerable<TDependency> dependencies, Func<TItem, bool> selectItem = null) where TDependency : AbstractDependency<TItem> { return CollectMap(dependencies, d => selectItem == null || selectItem(d.UsedItem) ? d.UsedItem : null, d => d) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToArray()); } public static Dictionary<TItem, TDependency[]> CollectOutgoingDependenciesMap<TDependency>( [NotNull, ItemNotNull] IEnumerable<TDependency> dependencies, Func<TItem, bool> selectItem = null) where TDependency : AbstractDependency<TItem> { return CollectMap(dependencies, d => selectItem == null || selectItem(d.UsingItem) ? d.UsingItem : null, d => d) .ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToArray()); } public static Dictionary<TItem, List<TResult>> CollectMap<TDependency, TResult>( [NotNull, ItemNotNull] IEnumerable<TDependency> dependencies, [NotNull] Func<TDependency, TItem> getItem, [NotNull] Func<TDependency, TResult> createT) { var result = new Dictionary<TItem, List<TResult>>(); foreach (var d in dependencies) { TItem key = getItem(d); if (key != null) { List<TResult> list; if (!result.TryGetValue(key, out list)) { result.Add(key, list = new List<TResult>()); } list.Add(createT(d)); } } return result; } ////public static void Reset() { //// Intern<ItemTail>.Reset(); //// Intern<Item>.Reset(); ////} public bool IsMatch([CanBeNull] IEnumerable<ItemMatch> matches, [CanBeNull] IEnumerable<ItemMatch> excludes) { return (matches == null || !matches.Any() || matches.Any(m => m.Matches(this).Success)) && (excludes == null || !excludes.Any() || excludes.All(m => !m.Matches(this).Success)); } } public class ReadOnlyItem : AbstractItem<ReadOnlyItem> { [NotNull] private readonly ReadOnlyMarkerSet _markerSet; protected ReadOnlyItem([NotNull] ItemType type, string[] values) : base(type, values) { _markerSet = new ReadOnlyMarkerSet(type.IgnoreCase, markers: Enumerable.Empty<string>()); } public override IMarkerSet MarkerSet => _markerSet; } public interface IItemAndDependencyFactory : IPlugin { Item CreateItem([NotNull] ItemType type, [ItemNotNull] string[] values); Dependency CreateDependency([NotNull] Item usingItem, [NotNull] Item usedItem, [CanBeNull] ISourceLocation source, [CanBeNull] IMarkerSet markers, int ct, int questionableCt = 0, int badCt = 0, string notOkReason = null, [CanBeNull] string exampleInfo = null); } public class DefaultItemAndDependencyFactory : IItemAndDependencyFactory { public Item CreateItem([NotNull] ItemType type, [ItemNotNull] string[] values) { return new Item(type, values); } public Dependency CreateDependency([NotNull] Item usingItem, [NotNull] Item usedItem, [CanBeNull] ISourceLocation source, [CanBeNull] IMarkerSet markers, int ct, int questionableCt = 0, int badCt = 0, string notOkReason = null, [CanBeNull] string exampleInfo = null) { return new Dependency(usingItem, usedItem, source, markers: markers, ct: ct, questionableCt: questionableCt, badCt: badCt, notOkReason: notOkReason, exampleInfo: exampleInfo); } public string GetHelp(bool detailedHelp, string filter) { return "Default factory for generic items and dependencies"; } } public class Item : AbstractItem<Item>, IWithMutableMarkerSet { private WorkingGraph _workingGraph; internal Item SetWorkingGraph(WorkingGraph workingGraph) { _workingGraph = workingGraph; return this; } [NotNull, ItemNotNull] public IEnumerable<Dependency> GetOutgoing() => _workingGraph.VisibleOutgoingVisible.Get(this) ?? Enumerable.Empty<Dependency>(); [NotNull, ItemNotNull] public IEnumerable<Dependency> GetIncoming() => _workingGraph.VisibleIncomingVisible.Get(this) ?? Enumerable.Empty<Dependency>(); [NotNull] private readonly MutableMarkerSet _markerSet; protected internal Item([NotNull] ItemType type, string[] values) : base(type, values) { _markerSet = new MutableMarkerSet(type.IgnoreCase, markers: null); } public override IMarkerSet MarkerSet => _markerSet; [NotNull] public Item Append(WorkingGraph graph, [CanBeNull] ItemTail additionalValues) { return additionalValues == null ? this : graph.CreateItem(additionalValues.Type, Values.Concat(additionalValues.Values.Skip(Type.Length)).ToArray()); } public void MergeWithMarkers(IMarkerSet markers) { _markerSet.MergeWithMarkers(markers); MarkersHaveChanged(); } public void IncrementMarker(string marker) { _markerSet.IncrementMarker(marker); MarkersHaveChanged(); } public void SetMarker(string marker, int value) { _markerSet.SetMarker(marker, value); MarkersHaveChanged(); } public void RemoveMarkers(string markerPattern, bool ignoreCase) { _markerSet.RemoveMarkers(markerPattern, ignoreCase); MarkersHaveChanged(); } public void RemoveMarkers(IEnumerable<string> markerPatterns, bool ignoreCase) { _markerSet.RemoveMarkers(markerPatterns, ignoreCase); MarkersHaveChanged(); } public void ClearMarkers() { _markerSet.ClearMarkers(); MarkersHaveChanged(); } public static readonly string ITEM_HELP = @" TBD Item matches ============ An item match is a string that is matched against items for various plugins. An item match has the following format (unfortunately, not all plugins follow this format as of today): [ typename : ] positionfieldmatch {{ : positionfieldmatch }} [markerpattern] or typename : namedfieldmatch {{ : namedfieldmatch }} [markerpattern] For more information on types, see the help topic for 'type'. The marker pattern is described in the help text for 'marker'. A positionfieldmatch has the following format: TBD A namedfieldmatch has the following format: name=positionfieldmatch TBD "; } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Administrator Operations on the subscription (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class ManagedSubscriptionOperations : IServiceOperations<AzureStackClient>, IManagedSubscriptionOperations { /// <summary> /// Initializes a new instance of the ManagedSubscriptionOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ManagedSubscriptionOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Create or updates the subscription /// </summary> /// <param name='parameters'> /// Required. Subscription update parameters /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the create or the update operation of the subscription /// </returns> public async Task<ManagedSubscriptionCreateOrUpdateResult> CreateOrUpdateAsync(ManagedSubscriptionCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Subscription == null) { throw new ArgumentNullException("parameters.Subscription"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/subscriptions/"; if (parameters.Subscription.SubscriptionId != null) { url = url + Uri.EscapeDataString(parameters.Subscription.SubscriptionId); } List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject managedSubscriptionCreateOrUpdateParametersValue = new JObject(); requestDoc = managedSubscriptionCreateOrUpdateParametersValue; if (parameters.Subscription.Id != null) { managedSubscriptionCreateOrUpdateParametersValue["id"] = parameters.Subscription.Id; } if (parameters.Subscription.SubscriptionId != null) { managedSubscriptionCreateOrUpdateParametersValue["subscriptionId"] = parameters.Subscription.SubscriptionId; } if (parameters.Subscription.DelegatedProviderSubscriptionId != null) { managedSubscriptionCreateOrUpdateParametersValue["delegatedProviderSubscriptionId"] = parameters.Subscription.DelegatedProviderSubscriptionId; } if (parameters.Subscription.DisplayName != null) { managedSubscriptionCreateOrUpdateParametersValue["displayName"] = parameters.Subscription.DisplayName; } if (parameters.Subscription.ExternalReferenceId != null) { managedSubscriptionCreateOrUpdateParametersValue["externalReferenceId"] = parameters.Subscription.ExternalReferenceId; } if (parameters.Subscription.Owner != null) { managedSubscriptionCreateOrUpdateParametersValue["owner"] = parameters.Subscription.Owner; } if (parameters.Subscription.TenantId != null) { managedSubscriptionCreateOrUpdateParametersValue["tenantId"] = parameters.Subscription.TenantId; } managedSubscriptionCreateOrUpdateParametersValue["routingResourceManagerType"] = parameters.Subscription.RoutingResourceManagerType.ToString(); if (parameters.Subscription.OfferId != null) { managedSubscriptionCreateOrUpdateParametersValue["offerId"] = parameters.Subscription.OfferId; } if (parameters.Subscription.State != null) { managedSubscriptionCreateOrUpdateParametersValue["state"] = parameters.Subscription.State.Value.ToString(); } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedSubscriptionCreateOrUpdateResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedSubscriptionCreateOrUpdateResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AdminSubscriptionDefinition subscriptionInstance = new AdminSubscriptionDefinition(); result.Subscription = subscriptionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken delegatedProviderSubscriptionIdValue = responseDoc["delegatedProviderSubscriptionId"]; if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null) { string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue); subscriptionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = responseDoc["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken ownerValue = responseDoc["owner"]; if (ownerValue != null && ownerValue.Type != JTokenType.Null) { string ownerInstance = ((string)ownerValue); subscriptionInstance.Owner = ownerInstance; } JToken tenantIdValue = responseDoc["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { string tenantIdInstance = ((string)tenantIdValue); subscriptionInstance.TenantId = tenantIdInstance; } JToken routingResourceManagerTypeValue = responseDoc["routingResourceManagerType"]; if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null) { ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true)); subscriptionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance; } JToken offerIdValue = responseDoc["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionInstance.OfferId = offerIdInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Delete operation of the subscription /// </summary> /// <param name='subscriptionId'> /// Required. Subscription Id /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate if (subscriptionId == null) { throw new ArgumentNullException("subscriptionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/subscriptions/"; url = url + Uri.EscapeDataString(subscriptionId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the administrator view of the subscription /// </summary> /// <param name='subscriptionId'> /// Required. Subscription Id /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the subscription get operation /// </returns> public async Task<ManagedSubscriptionGetResult> GetAsync(string subscriptionId, CancellationToken cancellationToken) { // Validate if (subscriptionId == null) { throw new ArgumentNullException("subscriptionId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/subscriptions/"; url = url + Uri.EscapeDataString(subscriptionId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedSubscriptionGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedSubscriptionGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { AdminSubscriptionDefinition subscriptionInstance = new AdminSubscriptionDefinition(); result.Subscription = subscriptionInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); subscriptionInstance.Id = idInstance; } JToken subscriptionIdValue = responseDoc["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); subscriptionInstance.SubscriptionId = subscriptionIdInstance; } JToken delegatedProviderSubscriptionIdValue = responseDoc["delegatedProviderSubscriptionId"]; if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null) { string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue); subscriptionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); subscriptionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = responseDoc["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); subscriptionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken ownerValue = responseDoc["owner"]; if (ownerValue != null && ownerValue.Type != JTokenType.Null) { string ownerInstance = ((string)ownerValue); subscriptionInstance.Owner = ownerInstance; } JToken tenantIdValue = responseDoc["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { string tenantIdInstance = ((string)tenantIdValue); subscriptionInstance.TenantId = tenantIdInstance; } JToken routingResourceManagerTypeValue = responseDoc["routingResourceManagerType"]; if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null) { ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true)); subscriptionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance; } JToken offerIdValue = responseDoc["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); subscriptionInstance.OfferId = offerIdInstance; } JToken stateValue = responseDoc["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); subscriptionInstance.State = stateInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the subscriptions /// </summary> /// <param name='includeDetails'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the list operations /// </returns> public async Task<ManagedSubscriptionListResult> ListAsync(bool includeDetails, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("includeDetails", includeDetails); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Subscriptions/subscriptions"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); queryParameters.Add("includeDetails=" + Uri.EscapeDataString(includeDetails.ToString().ToLower())); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedSubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedSubscriptionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { AdminSubscriptionDefinition adminSubscriptionDefinitionInstance = new AdminSubscriptionDefinition(); result.Subscriptions.Add(adminSubscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); adminSubscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); adminSubscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken delegatedProviderSubscriptionIdValue = valueValue["delegatedProviderSubscriptionId"]; if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null) { string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue); adminSubscriptionDefinitionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); adminSubscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); adminSubscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken ownerValue = valueValue["owner"]; if (ownerValue != null && ownerValue.Type != JTokenType.Null) { string ownerInstance = ((string)ownerValue); adminSubscriptionDefinitionInstance.Owner = ownerInstance; } JToken tenantIdValue = valueValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { string tenantIdInstance = ((string)tenantIdValue); adminSubscriptionDefinitionInstance.TenantId = tenantIdInstance; } JToken routingResourceManagerTypeValue = valueValue["routingResourceManagerType"]; if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null) { ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true)); adminSubscriptionDefinitionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); adminSubscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); adminSubscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the subscription with the next link /// </summary> /// <param name='nextLink'> /// Required. The URL pointing to get the next set of subscriptions /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the list operations /// </returns> public async Task<ManagedSubscriptionListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ManagedSubscriptionListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ManagedSubscriptionListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { AdminSubscriptionDefinition adminSubscriptionDefinitionInstance = new AdminSubscriptionDefinition(); result.Subscriptions.Add(adminSubscriptionDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); adminSubscriptionDefinitionInstance.Id = idInstance; } JToken subscriptionIdValue = valueValue["subscriptionId"]; if (subscriptionIdValue != null && subscriptionIdValue.Type != JTokenType.Null) { string subscriptionIdInstance = ((string)subscriptionIdValue); adminSubscriptionDefinitionInstance.SubscriptionId = subscriptionIdInstance; } JToken delegatedProviderSubscriptionIdValue = valueValue["delegatedProviderSubscriptionId"]; if (delegatedProviderSubscriptionIdValue != null && delegatedProviderSubscriptionIdValue.Type != JTokenType.Null) { string delegatedProviderSubscriptionIdInstance = ((string)delegatedProviderSubscriptionIdValue); adminSubscriptionDefinitionInstance.DelegatedProviderSubscriptionId = delegatedProviderSubscriptionIdInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); adminSubscriptionDefinitionInstance.DisplayName = displayNameInstance; } JToken externalReferenceIdValue = valueValue["externalReferenceId"]; if (externalReferenceIdValue != null && externalReferenceIdValue.Type != JTokenType.Null) { string externalReferenceIdInstance = ((string)externalReferenceIdValue); adminSubscriptionDefinitionInstance.ExternalReferenceId = externalReferenceIdInstance; } JToken ownerValue = valueValue["owner"]; if (ownerValue != null && ownerValue.Type != JTokenType.Null) { string ownerInstance = ((string)ownerValue); adminSubscriptionDefinitionInstance.Owner = ownerInstance; } JToken tenantIdValue = valueValue["tenantId"]; if (tenantIdValue != null && tenantIdValue.Type != JTokenType.Null) { string tenantIdInstance = ((string)tenantIdValue); adminSubscriptionDefinitionInstance.TenantId = tenantIdInstance; } JToken routingResourceManagerTypeValue = valueValue["routingResourceManagerType"]; if (routingResourceManagerTypeValue != null && routingResourceManagerTypeValue.Type != JTokenType.Null) { ResourceManagerType routingResourceManagerTypeInstance = ((ResourceManagerType)Enum.Parse(typeof(ResourceManagerType), ((string)routingResourceManagerTypeValue), true)); adminSubscriptionDefinitionInstance.RoutingResourceManagerType = routingResourceManagerTypeInstance; } JToken offerIdValue = valueValue["offerId"]; if (offerIdValue != null && offerIdValue.Type != JTokenType.Null) { string offerIdInstance = ((string)offerIdValue); adminSubscriptionDefinitionInstance.OfferId = offerIdInstance; } JToken stateValue = valueValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { SubscriptionState stateInstance = ((SubscriptionState)Enum.Parse(typeof(SubscriptionState), ((string)stateValue), true)); adminSubscriptionDefinitionInstance.State = stateInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Runtime.Serialization; using System.Xml.Serialization; using System.Collections.Generic; using System.Xml; using System.Xml.Schema; using System.ServiceModel.Channels; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace System.ServiceModel.Syndication { [XmlRoot(ElementName = App10Constants.Categories, Namespace = App10Constants.Namespace)] public class AtomPub10CategoriesDocumentFormatter : CategoriesDocumentFormatter, IXmlSerializable { private Type _inlineDocumentType; private int _maxExtensionSize; private bool _preserveAttributeExtensions; private bool _preserveElementExtensions; private Type _referencedDocumentType; public AtomPub10CategoriesDocumentFormatter() : this(typeof(InlineCategoriesDocument), typeof(ReferencedCategoriesDocument)) { } public AtomPub10CategoriesDocumentFormatter(Type inlineDocumentType, Type referencedDocumentType) : base() { if (inlineDocumentType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("inlineDocumentType"); } if (!typeof(InlineCategoriesDocument).IsAssignableFrom(inlineDocumentType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("inlineDocumentType", SR.Format(SR.InvalidObjectTypePassed, "inlineDocumentType", "InlineCategoriesDocument")); } if (referencedDocumentType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("referencedDocumentType"); } if (!typeof(ReferencedCategoriesDocument).IsAssignableFrom(referencedDocumentType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("referencedDocumentType", SR.Format(SR.InvalidObjectTypePassed, "referencedDocumentType", "ReferencedCategoriesDocument")); } _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = true; _preserveElementExtensions = true; _inlineDocumentType = inlineDocumentType; _referencedDocumentType = referencedDocumentType; } public AtomPub10CategoriesDocumentFormatter(CategoriesDocument documentToWrite) : base(documentToWrite) { // No need to check that the parameter passed is valid - it is checked by the c'tor of the base class _maxExtensionSize = int.MaxValue; _preserveAttributeExtensions = true; _preserveElementExtensions = true; if (documentToWrite.IsInline) { _inlineDocumentType = documentToWrite.GetType(); _referencedDocumentType = typeof(ReferencedCategoriesDocument); } else { _referencedDocumentType = documentToWrite.GetType(); _inlineDocumentType = typeof(InlineCategoriesDocument); } } public override string Version { get { return App10Constants.Namespace; } } public override bool CanRead(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } return reader.IsStartElement(App10Constants.Categories, App10Constants.Namespace); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] XmlSchema IXmlSerializable.GetSchema() { return null; } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } TraceCategoriesDocumentReadBegin(); ReadDocument(reader); TraceCategoriesDocumentReadEnd(); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (this.Document == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.DocumentFormatterDoesNotHaveDocument))); } TraceCategoriesDocumentWriteBegin(); WriteDocument(writer); TraceCategoriesDocumentWriteEnd(); } public override void ReadFrom(XmlReader reader) { if (reader == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader"); } if (!CanRead(reader)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI))); } TraceCategoriesDocumentReadBegin(); ReadDocument(reader); TraceCategoriesDocumentReadEnd(); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer"); } if (this.Document == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.DocumentFormatterDoesNotHaveDocument))); } TraceCategoriesDocumentWriteBegin(); writer.WriteStartElement(App10Constants.Prefix, App10Constants.Categories, App10Constants.Namespace); WriteDocument(writer); writer.WriteEndElement(); TraceCategoriesDocumentWriteEnd(); } internal static void TraceCategoriesDocumentReadBegin() { } internal static void TraceCategoriesDocumentReadEnd() { } internal static void TraceCategoriesDocumentWriteBegin() { } internal static void TraceCategoriesDocumentWriteEnd() { } protected override InlineCategoriesDocument CreateInlineCategoriesDocument() { if (_inlineDocumentType == typeof(InlineCategoriesDocument)) { return new InlineCategoriesDocument(); } else { return (InlineCategoriesDocument)Activator.CreateInstance(_inlineDocumentType); } } protected override ReferencedCategoriesDocument CreateReferencedCategoriesDocument() { if (_referencedDocumentType == typeof(ReferencedCategoriesDocument)) { return new ReferencedCategoriesDocument(); } else { return (ReferencedCategoriesDocument)Activator.CreateInstance(_referencedDocumentType); } } private void ReadDocument(XmlReader reader) { try { SyndicationFeedFormatter.MoveToStartElement(reader); SetDocument(AtomPub10ServiceDocumentFormatter.ReadCategories(reader, null, delegate () { return this.CreateInlineCategoriesDocument(); }, delegate () { return this.CreateReferencedCategoriesDocument(); }, this.Version, _preserveElementExtensions, _preserveAttributeExtensions, _maxExtensionSize)); } catch (FormatException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e)); } catch (ArgumentException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e)); } } private void WriteDocument(XmlWriter writer) { // declare the atom10 namespace upfront for compactness writer.WriteAttributeString(Atom10Constants.Atom10Prefix, Atom10FeedFormatter.XmlNsNs, Atom10Constants.Atom10Namespace); AtomPub10ServiceDocumentFormatter.WriteCategoriesInnerXml(writer, this.Document, null, this.Version); } } }
// 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.Dynamic; using System.Dynamic.Utils; using System.Reflection; using System.Threading; namespace System.Linq.Expressions.Interpreter { internal partial class CallInstruction { #if FEATURE_DLG_INVOKE private const int MaxHelpers = 5; #endif #if FEATURE_FAST_CREATE private const int MaxArgs = 3; /// <summary> /// Fast creation works if we have a known primitive types for the entire /// method signature. If we have any non-primitive types then FastCreate /// falls back to SlowCreate which works for all types. /// /// Fast creation is fast because it avoids using reflection (MakeGenericType /// and Activator.CreateInstance) to create the types. It does this through /// calling a series of generic methods picking up each strong type of the /// signature along the way. When it runs out of types it news up the /// appropriate CallInstruction with the strong-types that have been built up. /// /// One relaxation is that for return types which are non-primitive types /// we can fall back to object due to relaxed delegates. /// </summary> private static CallInstruction FastCreate(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 0); if (t == null) { return new ActionCallInstruction(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(0, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<Object>(target, pi); } case TypeCode.Int16: return FastCreate<Int16>(target, pi); case TypeCode.Int32: return FastCreate<Int32>(target, pi); case TypeCode.Int64: return FastCreate<Int64>(target, pi); case TypeCode.Boolean: return FastCreate<Boolean>(target, pi); case TypeCode.Char: return FastCreate<Char>(target, pi); case TypeCode.Byte: return FastCreate<Byte>(target, pi); case TypeCode.Decimal: return FastCreate<Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<DateTime>(target, pi); case TypeCode.Double: return FastCreate<Double>(target, pi); case TypeCode.Single: return FastCreate<Single>(target, pi); case TypeCode.UInt16: return FastCreate<UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<UInt64>(target, pi); case TypeCode.String: return FastCreate<String>(target, pi); case TypeCode.SByte: return FastCreate<SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 1); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0>(target); } return new FuncCallInstruction<T0>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { if (t != typeof(object) && (IndexIsNotReturnType(1, target, pi) || t.IsValueType)) { // if we're on the return type relaxed delegates makes it ok to use object goto default; } return FastCreate<T0, Object>(target, pi); } case TypeCode.Int16: return FastCreate<T0, Int16>(target, pi); case TypeCode.Int32: return FastCreate<T0, Int32>(target, pi); case TypeCode.Int64: return FastCreate<T0, Int64>(target, pi); case TypeCode.Boolean: return FastCreate<T0, Boolean>(target, pi); case TypeCode.Char: return FastCreate<T0, Char>(target, pi); case TypeCode.Byte: return FastCreate<T0, Byte>(target, pi); case TypeCode.Decimal: return FastCreate<T0, Decimal>(target, pi); case TypeCode.DateTime: return FastCreate<T0, DateTime>(target, pi); case TypeCode.Double: return FastCreate<T0, Double>(target, pi); case TypeCode.Single: return FastCreate<T0, Single>(target, pi); case TypeCode.UInt16: return FastCreate<T0, UInt16>(target, pi); case TypeCode.UInt32: return FastCreate<T0, UInt32>(target, pi); case TypeCode.UInt64: return FastCreate<T0, UInt64>(target, pi); case TypeCode.String: return FastCreate<T0, String>(target, pi); case TypeCode.SByte: return FastCreate<T0, SByte>(target, pi); default: return SlowCreate(target, pi); } } private static CallInstruction FastCreate<T0, T1>(MethodInfo target, ParameterInfo[] pi) { Type t = TryGetParameterOrReturnType(target, pi, 2); if (t == null) { if (target.ReturnType == typeof(void)) { return new ActionCallInstruction<T0, T1>(target); } return new FuncCallInstruction<T0, T1>(target); } if (t.IsEnum) return SlowCreate(target, pi); switch (t.GetTypeCode()) { case TypeCode.Object: { Debug.Assert(pi.Length == 2); if (t.IsValueType) goto default; return new FuncCallInstruction<T0, T1, Object>(target); } case TypeCode.Int16: return new FuncCallInstruction<T0, T1, Int16>(target); case TypeCode.Int32: return new FuncCallInstruction<T0, T1, Int32>(target); case TypeCode.Int64: return new FuncCallInstruction<T0, T1, Int64>(target); case TypeCode.Boolean: return new FuncCallInstruction<T0, T1, Boolean>(target); case TypeCode.Char: return new FuncCallInstruction<T0, T1, Char>(target); case TypeCode.Byte: return new FuncCallInstruction<T0, T1, Byte>(target); case TypeCode.Decimal: return new FuncCallInstruction<T0, T1, Decimal>(target); case TypeCode.DateTime: return new FuncCallInstruction<T0, T1, DateTime>(target); case TypeCode.Double: return new FuncCallInstruction<T0, T1, Double>(target); case TypeCode.Single: return new FuncCallInstruction<T0, T1, Single>(target); case TypeCode.UInt16: return new FuncCallInstruction<T0, T1, UInt16>(target); case TypeCode.UInt32: return new FuncCallInstruction<T0, T1, UInt32>(target); case TypeCode.UInt64: return new FuncCallInstruction<T0, T1, UInt64>(target); case TypeCode.String: return new FuncCallInstruction<T0, T1, String>(target); case TypeCode.SByte: return new FuncCallInstruction<T0, T1, SByte>(target); default: return SlowCreate(target, pi); } } #endif #if FEATURE_DLG_INVOKE private static Type GetHelperType(MethodInfo info, Type[] arrTypes) { Type t; if (info.ReturnType == typeof(void)) { switch (arrTypes.Length) { case 0: t = typeof(ActionCallInstruction); break; case 1: t = typeof(ActionCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(ActionCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(ActionCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(ActionCallInstruction<,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } else { switch (arrTypes.Length) { case 1: t = typeof(FuncCallInstruction<>).MakeGenericType(arrTypes); break; case 2: t = typeof(FuncCallInstruction<,>).MakeGenericType(arrTypes); break; case 3: t = typeof(FuncCallInstruction<,,>).MakeGenericType(arrTypes); break; case 4: t = typeof(FuncCallInstruction<,,,>).MakeGenericType(arrTypes); break; case 5: t = typeof(FuncCallInstruction<,,,,>).MakeGenericType(arrTypes); break; default: throw new InvalidOperationException(); } } return t; } #endif } #if FEATURE_DLG_INVOKE internal sealed class ActionCallInstruction : CallInstruction { private readonly Action _target; public override int ArgumentCount => 0; public override int ProducedStack => 0; public ActionCallInstruction(MethodInfo target) { _target = (Action)target.CreateDelegate(typeof(Action)); } public override int Run(InterpretedFrame frame) { _target(); frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0> _target; public override int ProducedStack => 0; public override int ArgumentCount => 1; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0>)target.CreateDelegate(typeof(Action<T0>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { _target((T0)firstArg); } frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1> _target; public override int ProducedStack => 0; public override int ArgumentCount => 2; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1>)target.CreateDelegate(typeof(Action<T0, T1>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2> _target; public override int ProducedStack => 0; public override int ArgumentCount => 3; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2>)target.CreateDelegate(typeof(Action<T0, T1, T2>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class ActionCallInstruction<T0, T1, T2, T3> : CallInstruction { private readonly bool _isInstance; private readonly Action<T0, T1, T2, T3> _target; public override int ProducedStack => 0; public override int ArgumentCount => 4; public ActionCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Action<T0, T1, T2, T3>)target.CreateDelegate(typeof(Action<T0, T1, T2, T3>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.StackIndex -= 4; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<TRet> : CallInstruction { private readonly Func<TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 0; public FuncCallInstruction(MethodInfo target) { _target = (Func<TRet>)target.CreateDelegate(typeof(Func<TRet>)); } public override int Run(InterpretedFrame frame) { frame.Data[frame.StackIndex - 0] = _target(); frame.StackIndex -= -1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 1; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, TRet>)target.CreateDelegate(typeof(Func<T0, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 1]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, Array.Empty<object>()); } else { result = _target((T0)firstArg); } frame.Data[frame.StackIndex - 1] = result; frame.StackIndex -= 0; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 2; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, TRet>)target.CreateDelegate(typeof(Func<T0, T1, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 2]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 2] = result; frame.StackIndex -= 1; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 3; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 3]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 2], (T2)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 3] = result; frame.StackIndex -= 2; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } internal sealed class FuncCallInstruction<T0, T1, T2, T3, TRet> : CallInstruction { private readonly bool _isInstance; private readonly Func<T0, T1, T2, T3, TRet> _target; public override int ProducedStack => 1; public override int ArgumentCount => 4; public FuncCallInstruction(MethodInfo target) { _isInstance = !target.IsStatic; _target = (Func<T0, T1, T2, T3, TRet>)target.CreateDelegate(typeof(Func<T0, T1, T2, T3, TRet>)); } public override int Run(InterpretedFrame frame) { object firstArg = frame.Data[frame.StackIndex - 4]; object result; if (_isInstance) { NullCheck(firstArg); } if (_isInstance && TryGetLightLambdaTarget(firstArg, out var targetLambda)) { // no need to Invoke, just interpret the lambda body result = InterpretLambdaInvoke(targetLambda, new object[] { frame.Data[frame.StackIndex - 3], frame.Data[frame.StackIndex - 2], frame.Data[frame.StackIndex - 1] }); } else { result = _target((T0)firstArg, (T1)frame.Data[frame.StackIndex - 3], (T2)frame.Data[frame.StackIndex - 2], (T3)frame.Data[frame.StackIndex - 1]); } frame.Data[frame.StackIndex - 4] = result; frame.StackIndex -= 3; return 1; } public override string ToString() => "Call(" + _target.Method + ")"; } #endif }
/* * 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. */ /* Generated By:JavaCC: Do not edit this line. ParseException.java Version 4.1 */ /* JavaCCOptions:KEEP_LINE_COL=null */ using System; using Lucene.Net.Support; namespace Lucene.Net.QueryParsers { /// <summary> This exception is thrown when parse errors are encountered. /// You can explicitly create objects of this exception type by /// calling the method generateParseException in the generated /// parser. /// /// You can modify this class to customize your error reporting /// mechanisms so long as you retain the public fields. /// </summary> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class ParseException:System.Exception { /// <summary> This method has the standard behavior when this object has been /// created using the standard constructors. Otherwise, it uses /// "currentToken" and "expectedTokenSequences" to generate a parse /// error message and returns it. If this object has been created /// due to a parse error, and you do not catch it (it gets thrown /// from the parser), then this method is called during the printing /// of the final stack trace, and hence the correct error message /// gets displayed. /// </summary> public override System.String Message { get { if (!specialConstructor) { return base.Message; } System.Text.StringBuilder expected = new System.Text.StringBuilder(); int maxSize = 0; for (int i = 0; i < expectedTokenSequences.Length; i++) { if (maxSize < expectedTokenSequences[i].Length) { maxSize = expectedTokenSequences[i].Length; } for (int j = 0; j < expectedTokenSequences[i].Length; j++) { expected.Append(tokenImage[expectedTokenSequences[i][j]]).Append(' '); } if (expectedTokenSequences[i][expectedTokenSequences[i].Length - 1] != 0) { expected.Append("..."); } expected.Append(eol).Append(" "); } System.String retval = "Encountered \""; Token tok = currentToken.next; for (int i = 0; i < maxSize; i++) { if (i != 0) retval += " "; if (tok.kind == 0) { retval += tokenImage[0]; break; } retval += (" " + tokenImage[tok.kind]); retval += " \""; retval += Add_escapes(tok.image); retval += " \""; tok = tok.next; } retval += ("\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn); retval += ("." + eol); if (expectedTokenSequences.Length == 1) { retval += ("Was expecting:" + eol + " "); } else { retval += ("Was expecting one of:" + eol + " "); } retval += expected.ToString(); return retval; } } /// <summary> This constructor is used by the method "generateParseException" /// in the generated parser. Calling this constructor generates /// a new object of this type with the fields "currentToken", /// "expectedTokenSequences", and "tokenImage" set. The boolean /// flag "specialConstructor" is also set to true to indicate that /// this constructor was used to create this object. /// This constructor calls its super class with the empty string /// to force the "toString" method of parent class "Throwable" to /// print the error message in the form: /// ParseException: &lt;result of getMessage&gt; /// </summary> public ParseException(Token currentTokenVal, int[][] expectedTokenSequencesVal, System.String[] tokenImageVal):base("") { specialConstructor = true; currentToken = currentTokenVal; expectedTokenSequences = expectedTokenSequencesVal; tokenImage = tokenImageVal; } /// <summary> The following constructors are for use by you for whatever /// purpose you can think of. Constructing the exception in this /// manner makes the exception behave in the normal way - i.e., as /// documented in the class "Throwable". The fields "errorToken", /// "expectedTokenSequences", and "tokenImage" do not contain /// relevant information. The JavaCC generated code does not use /// these constructors. /// </summary> public ParseException():base() { specialConstructor = false; } /// <summary>Constructor with message. </summary> public ParseException(System.String message):base(message) { specialConstructor = false; } /// <summary>Constructor with message. </summary> public ParseException(System.String message, System.Exception ex) : base(message, ex) { specialConstructor = false; } /// <summary> This variable determines which constructor was used to create /// this object and thereby affects the semantics of the /// "getMessage" method (see below). /// </summary> protected internal bool specialConstructor; /// <summary> This is the last token that has been consumed successfully. If /// this object has been created due to a parse error, the token /// followng this token will (therefore) be the first error token. /// </summary> public Token currentToken; /// <summary> Each entry in this array is an array of integers. Each array /// of integers represents a sequence of tokens (by their ordinal /// values) that is expected at this point of the parse. /// </summary> public int[][] expectedTokenSequences; /// <summary> This is a reference to the "tokenImage" array of the generated /// parser within which the parse error occurred. This array is /// defined in the generated ...Constants interface. /// </summary> public System.String[] tokenImage; /// <summary> The end of line string for this machine.</summary> protected internal System.String eol = AppSettings.Get("line.separator", "\n"); /// <summary> Used to convert raw characters to their escaped version /// when these raw version cannot be used as part of an ASCII /// string literal. /// </summary> protected internal virtual System.String Add_escapes(System.String str) { System.Text.StringBuilder retval = new System.Text.StringBuilder(); char ch; for (int i = 0; i < str.Length; i++) { switch (str[i]) { case (char) (0): continue; case '\b': retval.Append("\\b"); continue; case '\t': retval.Append("\\t"); continue; case '\n': retval.Append("\\n"); continue; case '\f': retval.Append("\\f"); continue; case '\r': retval.Append("\\r"); continue; case '\"': retval.Append("\\\""); continue; case '\'': retval.Append("\\\'"); continue; case '\\': retval.Append("\\\\"); continue; default: if ((ch = str[i]) < 0x20 || ch > 0x7e) { System.String s = "0000" + System.Convert.ToString(ch, 16); retval.Append("\\u" + s.Substring(s.Length - 4, (s.Length) - (s.Length - 4))); } else { retval.Append(ch); } continue; } } return retval.ToString(); } } /* JavaCC - OriginalChecksum=c7631a240f7446940695eac31d9483ca (do not edit this line) */ }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using AutoRest.Core.Utilities; using AutoRest.Core.Model; using AutoRest.Extensions; using AutoRest.Extensions.Azure; using System.Collections.Generic; using System.Linq; using System.Text; namespace AutoRest.Go.Model { public class ParameterGo : Parameter { public const string ApiVersionName = "APIVersion"; public ParameterGo() { } /// <summary> /// Add imports for the parameter in parameter type. /// </summary> /// <param name="parameter"></param> /// <param name="imports"></param> public void AddImports(HashSet<string> imports) { ModelType.AddImports(imports); } /// <summary> /// Return string with formatted Go map. /// xyz["abc"] = 123 /// </summary> /// <param name="mapVariable"></param> /// <returns></returns> public string AddToMap(string mapVariable) { return string.Format("{0}[\"{1}\"] = {2}", mapVariable, NameForMap(), ValueForMap()); } public string GetParameterName() { return IsClientProperty ? "client." + Name.Value.Capitalize() : Name.Value; } public override bool IsClientProperty => base.IsClientProperty == true || SerializedName.Value.IsApiVersion(); public bool IsMethodArgument => !IsClientProperty; /// <summary> /// Get Name for parameter for Go map. /// If parameter is client parameter, then return client.<parametername> /// </summary> /// <returns></returns> public string NameForMap() { return SerializedName.Value.IsApiVersion() ? AzureExtensions.ApiVersion : SerializedName.Value; } public bool RequiresUrlEncoding() { return (Location == Core.Model.ParameterLocation.Query || Location == Core.Model.ParameterLocation.Path) && !Extensions.ContainsKey(SwaggerExtensions.SkipUrlEncodingExtension); } /// <summary> /// Return formatted value string for the parameter. /// </summary> /// <returns></returns> public string ValueForMap() { if (SerializedName.Value.IsApiVersion()) { return "client." + ApiVersionName; } var value = IsClientProperty ? "client." + CodeNamerGo.Instance.GetPropertyName(Name.Value) : Name.Value; var format = IsRequired || ModelType.CanBeEmpty() ? "{0}" : "*{0}"; var s = CollectionFormat != CollectionFormat.None ? $"{format},\"{CollectionFormat.GetSeparator()}\"" : $"{format}"; return string.Format( RequiresUrlEncoding() ? $"autorest.Encode(\"{Location.ToString().ToLower()}\",{s})" : $"{s}", value); } } public static class ParameterGoExtensions { /// <summary> /// Return a Go map of required parameters. // Refactor -> Generator /// </summary> /// <param name="parameters"></param> /// <param name="mapVariable"></param> /// <returns></returns> public static string BuildParameterMap(this IEnumerable<ParameterGo> parameters, string mapVariable) { var builder = new StringBuilder(); builder.Append(mapVariable); builder.Append(" := map[string]interface{} {"); if (parameters.Count() > 0) { builder.AppendLine(); var indented = new IndentedStringBuilder(" "); parameters .Where(p => p.IsRequired) .OrderBy(p => p.SerializedName.ToString()) .ForEach(p => indented.AppendLine("\"{0}\": {1},", p.NameForMap(), p.ValueForMap())); builder.Append(indented); } builder.AppendLine("}"); return builder.ToString(); } /// <summary> /// Return list of parameters for specified location passed in an argument. /// Refactor -> Probably CodeModeltransformer, but even with 5 references, the other mkethods are not used anywhere /// </summary> /// <param name="parameters"></param> /// <param name="location"></param> /// <returns></returns> public static IEnumerable<ParameterGo> ByLocation(this IEnumerable<ParameterGo> parameters, ParameterLocation location) { return parameters .Where(p => p.Location == location); } /// <summary> /// Return list of retuired parameters for specified location passed in an argument. /// Refactor -> CodeModelTransformer, still, 3 erefences, but no one uses the other methods. /// </summary> /// <param name="parameters"></param> /// <param name="location"></param> /// <returns></returns> public static IEnumerable<ParameterGo> ByLocationAsRequired(this IEnumerable<ParameterGo> parameters, ParameterLocation location, bool isRequired) { return parameters .Where(p => p.Location == location && p.IsRequired == isRequired); } /// <summary> /// Return list of parameters as per their location in request. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static ParameterGo BodyParameter(this IEnumerable<ParameterGo> parameters) { var bodyParameters = parameters.ByLocation(ParameterLocation.Body); return bodyParameters.Any() ? bodyParameters.First() : null; } public static IEnumerable<ParameterGo> FormDataParameters(this IEnumerable<ParameterGo> parameters) { return parameters.ByLocation(ParameterLocation.FormData); } public static IEnumerable<ParameterGo> HeaderParameters(this IEnumerable<ParameterGo> parameters) { return parameters.ByLocation(ParameterLocation.Header); } public static IEnumerable<ParameterGo> HeaderParameters(this IEnumerable<ParameterGo> parameters, bool isRequired) { return parameters.ByLocationAsRequired(ParameterLocation.Header, isRequired); } public static IEnumerable<ParameterGo> URLParameters(this IEnumerable<ParameterGo> parameters) { var urlParams = new List<ParameterGo>(); foreach (ParameterGo p in parameters.ByLocation(ParameterLocation.Path)) { if (p.Method.CodeModel.BaseUrl.Contains(p.SerializedName)) { urlParams.Add(p); } } return urlParams; } public static IEnumerable<ParameterGo> PathParameters(this IEnumerable<ParameterGo> parameters) { var pathParams = new List<ParameterGo>(); foreach (ParameterGo p in parameters.ByLocation(ParameterLocation.Path)) { if (!p.Method.CodeModel.BaseUrl.Contains(p.SerializedName)) { pathParams.Add(p); } } return pathParams; } public static IEnumerable<ParameterGo> QueryParameters(this IEnumerable<ParameterGo> parameters) { return parameters.ByLocation(ParameterLocation.Query); } public static IEnumerable<ParameterGo> QueryParameters(this IEnumerable<ParameterGo> parameters, bool isRequired) { return parameters.ByLocationAsRequired(ParameterLocation.Query, isRequired); } public static string Validate(this IEnumerable<ParameterGo> parameters, HttpMethod method) { List<string> v = new List<string>(); HashSet<string> ancestors = new HashSet<string>(); foreach (var p in parameters) { var name = p.SerializedName.Value.IsApiVersion() ? "client." + ParameterGo.ApiVersionName : !p.IsClientProperty ? p.Name.Value : "client." + p.Name.Value.Capitalize(); List<string> x = new List<string>(); if (p.ModelType is CompositeType) { ancestors.Add(p.ModelType.Name); x.AddRange(p.ValidateCompositeType(name, method, ancestors)); ancestors.Remove(p.ModelType.Name); } else x.AddRange(p.ValidateType(name, method)); if (x.Count != 0) v.Add($"{{ TargetValue: {name},\n Constraints: []validation.Constraint{{{string.Join(",\n", x)}}}}}"); } return string.Join(",\n", v); } } }
// 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 Internal.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.IO { // A MemoryStream represents a Stream in memory (i.e, it has no backing store). // This stream may reduce the need for temporary buffers and files in // an application. // // There are two ways to create a MemoryStream. You can initialize one // from an unsigned byte array, or you can create an empty one. Empty // memory streams are resizable, while ones created with a byte array provide // a stream "view" of the data. [RelocatedType("System.IO")] [RelocatedType("System.Runtime.Extensions")] [Serializable] public class MemoryStream : Stream { private byte[] _buffer; // Either allocated internally or externally. private int _origin; // For user-provided arrays, start at this origin private int _position; // read/write head. [ContractPublicPropertyName("Length")] private int _length; // Number of bytes within the memory stream private int _capacity; // length of usable portion of buffer for stream // Note that _capacity == _buffer.Length for non-user-provided byte[]'s private bool _expandable; // User-provided buffers aren't expandable. private bool _writable; // Can user write to this stream? private bool _exposable; // Whether the array can be returned to the user. private bool _isOpen; // Is this stream open or closed? // <TODO>In V2, if we get support for arrays of more than 2 GB worth of elements, // consider removing this constraint, or setting it to Int64.MaxValue.</TODO> private const int MemStreamMaxLength = int.MaxValue; public MemoryStream() : this(0) { } public MemoryStream(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity); } _buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>(); _capacity = capacity; _expandable = true; _writable = true; _exposable = true; _origin = 0; // Must be 0 for byte[]'s created by MemoryStream _isOpen = true; } public MemoryStream(byte[] buffer) : this(buffer, true) { } public MemoryStream(byte[] buffer, bool writable) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } _buffer = buffer; _length = _capacity = buffer.Length; _writable = writable; _exposable = false; _origin = 0; _isOpen = true; } public MemoryStream(byte[] buffer, int index, int count) : this(buffer, index, count, true, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable) : this(buffer, index, count, writable, false) { } public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } _buffer = buffer; _origin = _position = index; _length = _capacity = index + count; _writable = writable; _exposable = publiclyVisible; // Can TryGetBuffer return the array? _expandable = false; _isOpen = true; } public override bool CanRead { [Pure] get { return _isOpen; } } public override bool CanSeek { [Pure] get { return _isOpen; } } public override bool CanWrite { [Pure] get { return _writable; } } private void EnsureWriteable() { if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } } protected override void Dispose(bool disposing) { try { if (disposing) { _isOpen = false; _writable = false; _expandable = false; // Don't set buffer to null - allow TryGetBuffer & ToArray to work. } } finally { // Call base.Close() to cleanup async IO resources base.Dispose(disposing); } } // returns a bool saying whether we allocated a new array. private bool EnsureCapacity(int value) { // Check for overflow if (value < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (value > _capacity) { int newCapacity = value; if (newCapacity < 256) { newCapacity = 256; } if (newCapacity < _capacity * 2) { newCapacity = _capacity * 2; } Capacity = newCapacity; return true; } return false; } public override void Flush() { } #pragma warning disable 1998 //async method with no await operators public override async Task FlushAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Flush(); } #pragma warning restore 1998 public virtual bool TryGetBuffer(out ArraySegment<byte> buffer) { if (!_exposable) { buffer = default(ArraySegment<byte>); return false; } buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin)); return true; } public virtual byte[] GetBuffer() { if (!_exposable) throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer); return _buffer; } // PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer()) internal byte[] InternalGetBuffer() { return _buffer; } // PERF: True cursor position, we don't need _origin for direct access internal int InternalGetPosition() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position; } // PERF: Takes out Int32 as fast as possible internal int InternalReadInt32() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int pos = (_position += 4); // use temp to avoid race if (pos > _length) { _position = _length; throw new EndOfStreamException(SR.IO_EOF_ReadBeyondEOF); } return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24); } // PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes internal int InternalEmulateRead(int count) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n < 0) { n = 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. _position += n; return n; } // Gets & sets the capacity (number of bytes allocated) for this stream. // The capacity cannot be set to a value less than the current length // of the stream. // public virtual int Capacity { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _capacity - _origin; } set { // Only update the capacity if the MS is expandable and the value is different than the current capacity. // Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity if (value < Length) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (!_expandable && (value != Capacity)) { throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable); } // MemoryStream has this invariant: _origin > 0 => !expandable (see ctors) if (_expandable && value != _capacity) { if (value > 0) { byte[] newBuffer = new byte[value]; if (_length > 0) { Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length); } _buffer = newBuffer; } else { _buffer = null; } _capacity = value; } } } public override long Length { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _length - _origin; } } public override long Position { get { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } return _position - _origin; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (value > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } _position = _origin + (int)value; } } public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } int n = _length - _position; if (n > count) { n = count; } if (n <= 0) { return 0; } Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1. if (n <= 8) { int byteCount = n; while (--byteCount >= 0) buffer[offset + byteCount] = _buffer[_position + byteCount]; } else Buffer.BlockCopy(_buffer, _position, buffer, offset, n); _position += n; return n; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return ReadAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task<int> ReadAsyncImpl(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Read(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override int ReadByte() { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (_position >= _length) { return -1; } return _buffer[_position++]; } public override void CopyTo(Stream destination, int bufferSize) { // Since we did not originally override this method, validate the arguments // the same way Stream does for back-compat. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read) when we are not sure. if (GetType() != typeof(MemoryStream)) { base.CopyTo(destination, bufferSize); return; } int originalPosition = _position; // Seek to the end of the MemoryStream. int remaining = InternalEmulateRead(_length - originalPosition); // If we were already at or past the end, there's no copying to do so just quit. if (remaining > 0) { // Call Write() on the other Stream, using our internal buffer and avoiding any // intermediary allocations. destination.Write(_buffer, originalPosition, remaining); } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // This implementation offers better performance compared to the base class version. StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to ReadAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into ReadAsync) when we are not sure. if (GetType() != typeof(MemoryStream)) { return base.CopyToAsync(destination, bufferSize, cancellationToken); } return CopyToAsyncImpl(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncImpl(Stream destination, int bufferSize, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // Avoid copying data from this buffer into a temp buffer: // (require that InternalEmulateRead does not throw, // otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below) int pos = _position; int n = InternalEmulateRead(_length - _position); // If destination is not a memory stream, write there asynchronously: MemoryStream memStrDest = destination as MemoryStream; if (memStrDest == null) { await destination.WriteAsync(_buffer, pos, n, cancellationToken).ConfigureAwait(false); } else { memStrDest.Write(_buffer, pos, n); } } public override long Seek(long offset, SeekOrigin loc) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } if (offset > MemStreamMaxLength) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength); } switch (loc) { case SeekOrigin.Begin: { int tempPosition = unchecked(_origin + (int)offset); if (offset < 0 || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.Current: { int tempPosition = unchecked(_position + (int)offset); if (unchecked(_position + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } case SeekOrigin.End: { int tempPosition = unchecked(_length + (int)offset); if (unchecked(_length + offset) < _origin || tempPosition < _origin) { throw new IOException(SR.IO_IO_SeekBeforeBegin); } _position = tempPosition; break; } default: throw new ArgumentException(SR.Argument_InvalidSeekOrigin); } Debug.Assert(_position >= 0, "_position >= 0"); return _position; } // Sets the length of the stream to a given value. The new // value must be nonnegative and less than the space remaining in // the array, Int32.MaxValue - origin // Origin is 0 in all cases other than a MemoryStream created on // top of an existing array and a specific starting offset was passed // into the MemoryStream constructor. The upper bounds prevents any // situations where a stream may be created on top of an array then // the stream is made longer than the maximum possible length of the // array (Int32.MaxValue). // public override void SetLength(long value) { if (value < 0 || value > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } EnsureWriteable(); // Origin wasn't publicly exposed above. Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails. if (value > (int.MaxValue - _origin)) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength); } int newLength = _origin + (int)value; bool allocatedNewArray = EnsureCapacity(newLength); if (!allocatedNewArray && newLength > _length) { Array.Clear(_buffer, _length, newLength - _length); } _length = newLength; if (_position > newLength) { _position = newLength; } } public virtual byte[] ToArray() { //BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy."); int count = _length - _origin; if (count == 0) { return Array.Empty<byte>(); } byte[] copy = new byte[count]; Buffer.BlockCopy(_buffer, _origin, copy, 0, _length - _origin); return copy; } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); int i = _position + count; // Check for overflow if (i < 0) { throw new IOException(SR.IO_IO_StreamTooLong); } if (i > _length) { bool mustZero = _position > _length; if (i > _capacity) { bool allocatedNewArray = EnsureCapacity(i); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, i - _length); } _length = i; } if ((count <= 8) && (buffer != _buffer)) { int byteCount = count; while (--byteCount >= 0) { _buffer[_position + byteCount] = buffer[offset + byteCount]; } } else { Buffer.BlockCopy(buffer, offset, _buffer, _position, count); } _position = i; } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } return WriteAsyncImpl(buffer, offset, count, cancellationToken); } #pragma warning disable 1998 //async method with no await operators private async Task WriteAsyncImpl(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Write(buffer, offset, count); } #pragma warning restore 1998 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } EnsureWriteable(); if (_position >= _length) { int newLength = _position + 1; bool mustZero = _position > _length; if (newLength >= _capacity) { bool allocatedNewArray = EnsureCapacity(newLength); if (allocatedNewArray) { mustZero = false; } } if (mustZero) { Array.Clear(_buffer, _length, _position - _length); } _length = newLength; } _buffer[_position++] = value; } // Writes this MemoryStream to another stream. public virtual void WriteTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream); } if (!_isOpen) { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } stream.Write(_buffer, _origin, _length - _origin); } } }
// 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.Linq; using System.Net.Sockets; using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public abstract class HttpClientMiniStress : HttpClientHandlerTestBase { [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(GetStressOptions))] public void SingleClient_ManyGets_Sync(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (HttpClient client = CreateHttpClient()) { Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { CreateServerAndGet(client, completionOption, responseText); }); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public async Task SingleClient_ManyGets_Async(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); using (HttpClient client = CreateHttpClient()) { await ForCountAsync(numRequests, dop, i => CreateServerAndGetAsync(client, completionOption, responseText)); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(GetStressOptions))] public void ManyClients_ManyGets(int numRequests, int dop, HttpCompletionOption completionOption) { string responseText = CreateResponse("abcdefghijklmnopqrstuvwxyz"); Parallel.For(0, numRequests, new ParallelOptions { MaxDegreeOfParallelism = dop, TaskScheduler = new ThreadPerTaskScheduler() }, _ => { using (HttpClient client = CreateHttpClient()) { CreateServerAndGet(client, completionOption, responseText); } }); } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [MemberData(nameof(PostStressOptions))] public async Task ManyClients_ManyPosts_Async(int numRequests, int dop, int numBytes) { string responseText = CreateResponse(""); await ForCountAsync(numRequests, dop, async i => { using (HttpClient client = CreateHttpClient()) { await CreateServerAndPostAsync(client, numBytes, responseText); } }); } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [InlineData(1000000)] public void CreateAndDestroyManyClients(int numClients) { for (int i = 0; i < numClients; i++) { CreateHttpClient().Dispose(); } } [ConditionalTheory(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] [InlineData(5000)] public async Task MakeAndFaultManyRequests(int numRequests) { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { client.Timeout = Timeout.InfiniteTimeSpan; Task<string>[] tasks = (from i in Enumerable.Range(0, numRequests) select client.GetStringAsync(url)) .ToArray(); Assert.All(tasks, t => Assert.True(t.IsFaulted || t.Status == TaskStatus.WaitingForActivation, $"Unexpected status {t.Status}")); server.Dispose(); foreach (Task<string> task in tasks) { await Assert.ThrowsAnyAsync<HttpRequestException>(() => task); } } }, new LoopbackServer.Options { ListenBacklog = numRequests }); } public static IEnumerable<object[]> GetStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (var completionoption in new[] { HttpCompletionOption.ResponseContentRead, HttpCompletionOption.ResponseHeadersRead }) yield return new object[] { numRequests, dop, completionoption }; } private static void CreateServerAndGet(HttpClient client, HttpCompletionOption completionOption, string responseText) { LoopbackServer.CreateServerAsync((server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); server.AcceptConnectionAsync(connection => { while (!string.IsNullOrEmpty(connection.Reader.ReadLine())) ; connection.Writer.Write(responseText); connection.Socket.Shutdown(SocketShutdown.Send); return Task.CompletedTask; }).GetAwaiter().GetResult(); getAsync.GetAwaiter().GetResult().Dispose(); return Task.CompletedTask; }).GetAwaiter().GetResult(); } private static async Task CreateServerAndGetAsync(HttpClient client, HttpCompletionOption completionOption, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { Task<HttpResponseMessage> getAsync = client.GetAsync(url, completionOption); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync().ConfigureAwait(false))) ; await connection.Writer.WriteAsync(responseText).ConfigureAwait(false); connection.Socket.Shutdown(SocketShutdown.Send); }); (await getAsync.ConfigureAwait(false)).Dispose(); }); } public static IEnumerable<object[]> PostStressOptions() { foreach (int numRequests in new[] { 5000 }) // number of requests foreach (int dop in new[] { 1, 32 }) // number of threads foreach (int numBytes in new[] { 0, 100 }) // number of bytes to post yield return new object[] { numRequests, dop, numBytes }; } private static async Task CreateServerAndPostAsync(HttpClient client, int numBytes, string responseText) { await LoopbackServer.CreateServerAsync(async (server, url) => { var content = new ByteArrayContent(new byte[numBytes]); Task<HttpResponseMessage> postAsync = client.PostAsync(url, content); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync().ConfigureAwait(false))) ; for (int i = 0; i < numBytes; i++) Assert.NotEqual(-1, connection.Reader.Read()); await connection.Writer.WriteAsync(responseText).ConfigureAwait(false); connection.Socket.Shutdown(SocketShutdown.Send); }); (await postAsync.ConfigureAwait(false)).Dispose(); }); } [ConditionalFact(typeof(TestEnvironment), nameof(TestEnvironment.IsStressModeEnabled))] public async Task UnreadResponseMessage_Collectible() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Func<Task<WeakReference>> getAsync = () => client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).ContinueWith(t => new WeakReference(t.Result)); Task<WeakReference> wrt = getAsync(); await server.AcceptConnectionAsync(async connection => { while (!string.IsNullOrEmpty(await connection.Reader.ReadLineAsync())) ; await connection.Writer.WriteAsync(CreateResponse(new string('a', 32 * 1024))); WeakReference wr = wrt.GetAwaiter().GetResult(); Assert.True(SpinWait.SpinUntil(() => { GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); return !wr.IsAlive; }, 10 * 1000), "Response object should have been collected"); }); } }); } private static string CreateResponse(string asciiBody) => $"HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Type: text/plain\r\n" + $"Content-Length: {asciiBody.Length}\r\n" + "\r\n" + $"{asciiBody}"; private static Task ForCountAsync(int count, int dop, Func<int, Task> bodyAsync) { var sched = new ThreadPerTaskScheduler(); int nextAvailableIndex = 0; return Task.WhenAll(Enumerable.Range(0, dop).Select(_ => Task.Factory.StartNew(async delegate { int index; while ((index = Interlocked.Increment(ref nextAvailableIndex) - 1) < count) { try { await bodyAsync(index); } catch { Volatile.Write(ref nextAvailableIndex, count); // avoid any further iterations throw; } } }, CancellationToken.None, TaskCreationOptions.None, sched).Unwrap())); } private sealed class ThreadPerTaskScheduler : TaskScheduler { protected override void QueueTask(Task task) => Task.Factory.StartNew(() => TryExecuteTask(task), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) => TryExecuteTask(task); protected override IEnumerable<Task> GetScheduledTasks() => null; } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * 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; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// The metrics associated with a VM /// First published in XenServer 4.0. /// </summary> public partial class VM_metrics : XenObject<VM_metrics> { #region Constructors public VM_metrics() { } public VM_metrics(string uuid, long memory_actual, long VCPUs_number, Dictionary<long, double> VCPUs_utilisation, Dictionary<long, long> VCPUs_CPU, Dictionary<string, string> VCPUs_params, Dictionary<long, string[]> VCPUs_flags, string[] state, DateTime start_time, DateTime install_time, DateTime last_updated, Dictionary<string, string> other_config, bool hvm, bool nested_virt, bool nomigrate, domain_type current_domain_type) { this.uuid = uuid; this.memory_actual = memory_actual; this.VCPUs_number = VCPUs_number; this.VCPUs_utilisation = VCPUs_utilisation; this.VCPUs_CPU = VCPUs_CPU; this.VCPUs_params = VCPUs_params; this.VCPUs_flags = VCPUs_flags; this.state = state; this.start_time = start_time; this.install_time = install_time; this.last_updated = last_updated; this.other_config = other_config; this.hvm = hvm; this.nested_virt = nested_virt; this.nomigrate = nomigrate; this.current_domain_type = current_domain_type; } /// <summary> /// Creates a new VM_metrics from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VM_metrics(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new VM_metrics from a Proxy_VM_metrics. /// </summary> /// <param name="proxy"></param> public VM_metrics(Proxy_VM_metrics proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VM_metrics. /// </summary> public override void UpdateFrom(VM_metrics record) { uuid = record.uuid; memory_actual = record.memory_actual; VCPUs_number = record.VCPUs_number; VCPUs_utilisation = record.VCPUs_utilisation; VCPUs_CPU = record.VCPUs_CPU; VCPUs_params = record.VCPUs_params; VCPUs_flags = record.VCPUs_flags; state = record.state; start_time = record.start_time; install_time = record.install_time; last_updated = record.last_updated; other_config = record.other_config; hvm = record.hvm; nested_virt = record.nested_virt; nomigrate = record.nomigrate; current_domain_type = record.current_domain_type; } internal void UpdateFrom(Proxy_VM_metrics proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; memory_actual = proxy.memory_actual == null ? 0 : long.Parse(proxy.memory_actual); VCPUs_number = proxy.VCPUs_number == null ? 0 : long.Parse(proxy.VCPUs_number); VCPUs_utilisation = proxy.VCPUs_utilisation == null ? null : Maps.convert_from_proxy_long_double(proxy.VCPUs_utilisation); VCPUs_CPU = proxy.VCPUs_CPU == null ? null : Maps.convert_from_proxy_long_long(proxy.VCPUs_CPU); VCPUs_params = proxy.VCPUs_params == null ? null : Maps.convert_from_proxy_string_string(proxy.VCPUs_params); VCPUs_flags = proxy.VCPUs_flags == null ? null : Maps.convert_from_proxy_long_string_array(proxy.VCPUs_flags); state = proxy.state == null ? new string[] {} : (string [])proxy.state; start_time = proxy.start_time; install_time = proxy.install_time; last_updated = proxy.last_updated; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); hvm = (bool)proxy.hvm; nested_virt = (bool)proxy.nested_virt; nomigrate = (bool)proxy.nomigrate; current_domain_type = proxy.current_domain_type == null ? (domain_type) 0 : (domain_type)Helper.EnumParseDefault(typeof(domain_type), (string)proxy.current_domain_type); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VM_metrics /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("memory_actual")) memory_actual = Marshalling.ParseLong(table, "memory_actual"); if (table.ContainsKey("VCPUs_number")) VCPUs_number = Marshalling.ParseLong(table, "VCPUs_number"); if (table.ContainsKey("VCPUs_utilisation")) VCPUs_utilisation = Maps.convert_from_proxy_long_double(Marshalling.ParseHashTable(table, "VCPUs_utilisation")); if (table.ContainsKey("VCPUs_CPU")) VCPUs_CPU = Maps.convert_from_proxy_long_long(Marshalling.ParseHashTable(table, "VCPUs_CPU")); if (table.ContainsKey("VCPUs_params")) VCPUs_params = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "VCPUs_params")); if (table.ContainsKey("VCPUs_flags")) VCPUs_flags = Maps.convert_from_proxy_long_string_array(Marshalling.ParseHashTable(table, "VCPUs_flags")); if (table.ContainsKey("state")) state = Marshalling.ParseStringArray(table, "state"); if (table.ContainsKey("start_time")) start_time = Marshalling.ParseDateTime(table, "start_time"); if (table.ContainsKey("install_time")) install_time = Marshalling.ParseDateTime(table, "install_time"); if (table.ContainsKey("last_updated")) last_updated = Marshalling.ParseDateTime(table, "last_updated"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("hvm")) hvm = Marshalling.ParseBool(table, "hvm"); if (table.ContainsKey("nested_virt")) nested_virt = Marshalling.ParseBool(table, "nested_virt"); if (table.ContainsKey("nomigrate")) nomigrate = Marshalling.ParseBool(table, "nomigrate"); if (table.ContainsKey("current_domain_type")) current_domain_type = (domain_type)Helper.EnumParseDefault(typeof(domain_type), Marshalling.ParseString(table, "current_domain_type")); } public Proxy_VM_metrics ToProxy() { Proxy_VM_metrics result_ = new Proxy_VM_metrics(); result_.uuid = uuid ?? ""; result_.memory_actual = memory_actual.ToString(); result_.VCPUs_number = VCPUs_number.ToString(); result_.VCPUs_utilisation = Maps.convert_to_proxy_long_double(VCPUs_utilisation); result_.VCPUs_CPU = Maps.convert_to_proxy_long_long(VCPUs_CPU); result_.VCPUs_params = Maps.convert_to_proxy_string_string(VCPUs_params); result_.VCPUs_flags = Maps.convert_to_proxy_long_string_array(VCPUs_flags); result_.state = state; result_.start_time = start_time; result_.install_time = install_time; result_.last_updated = last_updated; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.hvm = hvm; result_.nested_virt = nested_virt; result_.nomigrate = nomigrate; result_.current_domain_type = domain_type_helper.ToString(current_domain_type); return result_; } public bool DeepEquals(VM_metrics other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._memory_actual, other._memory_actual) && Helper.AreEqual2(this._VCPUs_number, other._VCPUs_number) && Helper.AreEqual2(this._VCPUs_utilisation, other._VCPUs_utilisation) && Helper.AreEqual2(this._VCPUs_CPU, other._VCPUs_CPU) && Helper.AreEqual2(this._VCPUs_params, other._VCPUs_params) && Helper.AreEqual2(this._VCPUs_flags, other._VCPUs_flags) && Helper.AreEqual2(this._state, other._state) && Helper.AreEqual2(this._start_time, other._start_time) && Helper.AreEqual2(this._install_time, other._install_time) && Helper.AreEqual2(this._last_updated, other._last_updated) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._hvm, other._hvm) && Helper.AreEqual2(this._nested_virt, other._nested_virt) && Helper.AreEqual2(this._nomigrate, other._nomigrate) && Helper.AreEqual2(this._current_domain_type, other._current_domain_type); } public override string SaveChanges(Session session, string opaqueRef, VM_metrics server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VM_metrics.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static VM_metrics get_record(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_record(session.opaque_ref, _vm_metrics); else return new VM_metrics(session.XmlRpcProxy.vm_metrics_get_record(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get a reference to the VM_metrics instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VM_metrics> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VM_metrics>.Create(session.XmlRpcProxy.vm_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static string get_uuid(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_uuid(session.opaque_ref, _vm_metrics); else return session.XmlRpcProxy.vm_metrics_get_uuid(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the memory/actual field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static long get_memory_actual(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_memory_actual(session.opaque_ref, _vm_metrics); else return long.Parse(session.XmlRpcProxy.vm_metrics_get_memory_actual(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the VCPUs/number field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static long get_VCPUs_number(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_vcpus_number(session.opaque_ref, _vm_metrics); else return long.Parse(session.XmlRpcProxy.vm_metrics_get_vcpus_number(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the VCPUs/utilisation field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary<long, double> get_VCPUs_utilisation(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_vcpus_utilisation(session.opaque_ref, _vm_metrics); else return Maps.convert_from_proxy_long_double(session.XmlRpcProxy.vm_metrics_get_vcpus_utilisation(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the VCPUs/CPU field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary<long, long> get_VCPUs_CPU(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_vcpus_cpu(session.opaque_ref, _vm_metrics); else return Maps.convert_from_proxy_long_long(session.XmlRpcProxy.vm_metrics_get_vcpus_cpu(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the VCPUs/params field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary<string, string> get_VCPUs_params(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_vcpus_params(session.opaque_ref, _vm_metrics); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_metrics_get_vcpus_params(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the VCPUs/flags field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary<long, string[]> get_VCPUs_flags(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_vcpus_flags(session.opaque_ref, _vm_metrics); else return Maps.convert_from_proxy_long_string_array(session.XmlRpcProxy.vm_metrics_get_vcpus_flags(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the state field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static string[] get_state(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_state(session.opaque_ref, _vm_metrics); else return (string [])session.XmlRpcProxy.vm_metrics_get_state(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the start_time field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static DateTime get_start_time(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_start_time(session.opaque_ref, _vm_metrics); else return session.XmlRpcProxy.vm_metrics_get_start_time(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the install_time field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static DateTime get_install_time(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_install_time(session.opaque_ref, _vm_metrics); else return session.XmlRpcProxy.vm_metrics_get_install_time(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the last_updated field of the given VM_metrics. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static DateTime get_last_updated(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_last_updated(session.opaque_ref, _vm_metrics); else return session.XmlRpcProxy.vm_metrics_get_last_updated(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static Dictionary<string, string> get_other_config(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_other_config(session.opaque_ref, _vm_metrics); else return Maps.convert_from_proxy_string_string(session.XmlRpcProxy.vm_metrics_get_other_config(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Get the hvm field of the given VM_metrics. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static bool get_hvm(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_hvm(session.opaque_ref, _vm_metrics); else return (bool)session.XmlRpcProxy.vm_metrics_get_hvm(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the nested_virt field of the given VM_metrics. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static bool get_nested_virt(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_nested_virt(session.opaque_ref, _vm_metrics); else return (bool)session.XmlRpcProxy.vm_metrics_get_nested_virt(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the nomigrate field of the given VM_metrics. /// First published in XenServer 7.1. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static bool get_nomigrate(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_nomigrate(session.opaque_ref, _vm_metrics); else return (bool)session.XmlRpcProxy.vm_metrics_get_nomigrate(session.opaque_ref, _vm_metrics ?? "").parse(); } /// <summary> /// Get the current_domain_type field of the given VM_metrics. /// First published in XenServer 7.5. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> public static domain_type get_current_domain_type(Session session, string _vm_metrics) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_current_domain_type(session.opaque_ref, _vm_metrics); else return (domain_type)Helper.EnumParseDefault(typeof(domain_type), (string)session.XmlRpcProxy.vm_metrics_get_current_domain_type(session.opaque_ref, _vm_metrics ?? "").parse()); } /// <summary> /// Set the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vm_metrics, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_metrics_set_other_config(session.opaque_ref, _vm_metrics, _other_config); else session.XmlRpcProxy.vm_metrics_set_other_config(session.opaque_ref, _vm_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VM_metrics. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vm_metrics, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_metrics_add_to_other_config(session.opaque_ref, _vm_metrics, _key, _value); else session.XmlRpcProxy.vm_metrics_add_to_other_config(session.opaque_ref, _vm_metrics ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VM_metrics. If the key is not in that Map, then do nothing. /// First published in XenServer 5.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vm_metrics">The opaque_ref of the given vm_metrics</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vm_metrics, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.vm_metrics_remove_from_other_config(session.opaque_ref, _vm_metrics, _key); else session.XmlRpcProxy.vm_metrics_remove_from_other_config(session.opaque_ref, _vm_metrics ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the VM_metrics instances known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VM_metrics>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_all(session.opaque_ref); else return XenRef<VM_metrics>.Create(session.XmlRpcProxy.vm_metrics_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the VM_metrics Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VM_metrics>, VM_metrics> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vm_metrics_get_all_records(session.opaque_ref); else return XenRef<VM_metrics>.Create<Proxy_VM_metrics>(session.XmlRpcProxy.vm_metrics_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// Guest's actual memory (bytes) /// </summary> public virtual long memory_actual { get { return _memory_actual; } set { if (!Helper.AreEqual(value, _memory_actual)) { _memory_actual = value; NotifyPropertyChanged("memory_actual"); } } } private long _memory_actual; /// <summary> /// Current number of VCPUs /// </summary> public virtual long VCPUs_number { get { return _VCPUs_number; } set { if (!Helper.AreEqual(value, _VCPUs_number)) { _VCPUs_number = value; NotifyPropertyChanged("VCPUs_number"); } } } private long _VCPUs_number; /// <summary> /// Utilisation for all of guest's current VCPUs /// </summary> public virtual Dictionary<long, double> VCPUs_utilisation { get { return _VCPUs_utilisation; } set { if (!Helper.AreEqual(value, _VCPUs_utilisation)) { _VCPUs_utilisation = value; NotifyPropertyChanged("VCPUs_utilisation"); } } } private Dictionary<long, double> _VCPUs_utilisation = new Dictionary<long, double>() {}; /// <summary> /// VCPU to PCPU map /// </summary> public virtual Dictionary<long, long> VCPUs_CPU { get { return _VCPUs_CPU; } set { if (!Helper.AreEqual(value, _VCPUs_CPU)) { _VCPUs_CPU = value; NotifyPropertyChanged("VCPUs_CPU"); } } } private Dictionary<long, long> _VCPUs_CPU = new Dictionary<long, long>() {}; /// <summary> /// The live equivalent to VM.VCPUs_params /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> VCPUs_params { get { return _VCPUs_params; } set { if (!Helper.AreEqual(value, _VCPUs_params)) { _VCPUs_params = value; NotifyPropertyChanged("VCPUs_params"); } } } private Dictionary<string, string> _VCPUs_params = new Dictionary<string, string>() {}; /// <summary> /// CPU flags (blocked,online,running) /// </summary> public virtual Dictionary<long, string[]> VCPUs_flags { get { return _VCPUs_flags; } set { if (!Helper.AreEqual(value, _VCPUs_flags)) { _VCPUs_flags = value; NotifyPropertyChanged("VCPUs_flags"); } } } private Dictionary<long, string[]> _VCPUs_flags = new Dictionary<long, string[]>() {}; /// <summary> /// The state of the guest, eg blocked, dying etc /// </summary> public virtual string[] state { get { return _state; } set { if (!Helper.AreEqual(value, _state)) { _state = value; NotifyPropertyChanged("state"); } } } private string[] _state = {}; /// <summary> /// Time at which this VM was last booted /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime start_time { get { return _start_time; } set { if (!Helper.AreEqual(value, _start_time)) { _start_time = value; NotifyPropertyChanged("start_time"); } } } private DateTime _start_time; /// <summary> /// Time at which the VM was installed /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime install_time { get { return _install_time; } set { if (!Helper.AreEqual(value, _install_time)) { _install_time = value; NotifyPropertyChanged("install_time"); } } } private DateTime _install_time; /// <summary> /// Time at which this information was last updated /// </summary> [JsonConverter(typeof(XenDateTimeConverter))] public virtual DateTime last_updated { get { return _last_updated; } set { if (!Helper.AreEqual(value, _last_updated)) { _last_updated = value; NotifyPropertyChanged("last_updated"); } } } private DateTime _last_updated; /// <summary> /// additional configuration /// First published in XenServer 5.0. /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// hardware virtual machine /// First published in XenServer 7.1. /// </summary> public virtual bool hvm { get { return _hvm; } set { if (!Helper.AreEqual(value, _hvm)) { _hvm = value; NotifyPropertyChanged("hvm"); } } } private bool _hvm = false; /// <summary> /// VM supports nested virtualisation /// First published in XenServer 7.1. /// </summary> public virtual bool nested_virt { get { return _nested_virt; } set { if (!Helper.AreEqual(value, _nested_virt)) { _nested_virt = value; NotifyPropertyChanged("nested_virt"); } } } private bool _nested_virt = false; /// <summary> /// VM is immobile and can't migrate between hosts /// First published in XenServer 7.1. /// </summary> public virtual bool nomigrate { get { return _nomigrate; } set { if (!Helper.AreEqual(value, _nomigrate)) { _nomigrate = value; NotifyPropertyChanged("nomigrate"); } } } private bool _nomigrate = false; /// <summary> /// The current domain type of the VM (for running,suspended, or paused VMs). The last-known domain type for halted VMs. /// First published in XenServer 7.5. /// </summary> [JsonConverter(typeof(domain_typeConverter))] public virtual domain_type current_domain_type { get { return _current_domain_type; } set { if (!Helper.AreEqual(value, _current_domain_type)) { _current_domain_type = value; NotifyPropertyChanged("current_domain_type"); } } } private domain_type _current_domain_type = domain_type.unspecified; } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Xva { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security.Cryptography; using System.Text; using DiscUtils.Archives; using DiskRecord = DiscUtils.Tuple<string, DiscUtils.SparseStream, DiscUtils.Ownership>; /// <summary> /// A class that can be used to create Xen Virtual Appliance (XVA) files. /// </summary> /// <remarks>This class is not intended to be a general purpose XVA generator, /// the options to control the VM properties are strictly limited. The class /// generates a minimal VM really as a wrapper for one or more disk images, /// making them easy to import into XenServer.</remarks> public sealed class VirtualMachineBuilder : StreamBuilder, IDisposable { private List<DiskRecord> _disks; private string _vmDisplayName; /// <summary> /// Initializes a new instance of the VirtualMachineBuilder class. /// </summary> public VirtualMachineBuilder() { _disks = new List<DiskRecord>(); _vmDisplayName = "VM"; } /// <summary> /// Gets or sets the display name of the VM. /// </summary> public string DisplayName { get { return _vmDisplayName; } set { _vmDisplayName = value; } } /// <summary> /// Disposes this instance, including any underlying resources. /// </summary> public void Dispose() { foreach (DiskRecord r in _disks) { if (r.Third == Ownership.Dispose) { r.Second.Dispose(); } } } /// <summary> /// Adds a sparse disk image to the XVA file. /// </summary> /// <param name="label">The admin-visible name of the disk</param> /// <param name="content">The content of the disk</param> /// <param name="ownsContent">Indicates if ownership of content is transfered</param> public void AddDisk(string label, SparseStream content, Ownership ownsContent) { _disks.Add(new DiskRecord(label, content, ownsContent)); } /// <summary> /// Adds a disk image to the XVA file. /// </summary> /// <param name="label">The admin-visible name of the disk</param> /// <param name="content">The content of the disk</param> /// <param name="ownsContent">Indicates if ownership of content is transfered</param> public void AddDisk(string label, Stream content, Ownership ownsContent) { _disks.Add(new DiskRecord(label, SparseStream.FromStream(content, ownsContent), Ownership.Dispose)); } /// <summary> /// Creates a new stream that contains the XVA image. /// </summary> /// <returns>The new stream</returns> public override SparseStream Build() { TarFileBuilder tarBuilder = new TarFileBuilder(); int[] diskIds; string ovaFileContent = GenerateOvaXml(out diskIds); tarBuilder.AddFile("ova.xml", Encoding.ASCII.GetBytes(ovaFileContent)); int diskIdx = 0; foreach (var diskRec in _disks) { SparseStream diskStream = diskRec.Second; List<StreamExtent> extents = new List<StreamExtent>(diskStream.Extents); int lastChunkAdded = -1; foreach (StreamExtent extent in extents) { int firstChunk = (int)(extent.Start / Sizes.OneMiB); int lastChunk = (int)((extent.Start + extent.Length - 1) / Sizes.OneMiB); for (int i = firstChunk; i <= lastChunk; ++i) { if (i != lastChunkAdded) { HashAlgorithm hashAlg = new SHA1Managed(); Stream chunkStream; long diskBytesLeft = diskStream.Length - (i * Sizes.OneMiB); if (diskBytesLeft < Sizes.OneMiB) { chunkStream = new ConcatStream( Ownership.Dispose, new SubStream(diskStream, i * Sizes.OneMiB, diskBytesLeft), new ZeroStream(Sizes.OneMiB - diskBytesLeft)); } else { chunkStream = new SubStream(diskStream, i * Sizes.OneMiB, Sizes.OneMiB); } HashStream chunkHashStream = new HashStream(chunkStream, Ownership.Dispose, hashAlg); tarBuilder.AddFile(string.Format(CultureInfo.InvariantCulture, "Ref:{0}/{1:D8}", diskIds[diskIdx], i), chunkHashStream); tarBuilder.AddFile(string.Format(CultureInfo.InvariantCulture, "Ref:{0}/{1:D8}.checksum", diskIds[diskIdx], i), new ChecksumStream(hashAlg)); lastChunkAdded = i; } } } // Make sure the last chunk is present, filled with zero's if necessary int lastActualChunk = (int)((diskStream.Length - 1) / Sizes.OneMiB); if (lastChunkAdded < lastActualChunk) { HashAlgorithm hashAlg = new SHA1Managed(); Stream chunkStream = new ZeroStream(Sizes.OneMiB); HashStream chunkHashStream = new HashStream(chunkStream, Ownership.Dispose, hashAlg); tarBuilder.AddFile(string.Format(CultureInfo.InvariantCulture, "Ref:{0}/{1:D8}", diskIds[diskIdx], lastActualChunk), chunkHashStream); tarBuilder.AddFile(string.Format(CultureInfo.InvariantCulture, "Ref:{0}/{1:D8}.checksum", diskIds[diskIdx], lastActualChunk), new ChecksumStream(hashAlg)); } ++diskIdx; } return tarBuilder.Build(); } internal override List<BuilderExtent> FixExtents(out long totalLength) { // Not required - deferred to TarFileBuilder throw new NotSupportedException(); } private string GenerateOvaXml(out int[] diskIds) { int id = 0; Guid vmGuid = Guid.NewGuid(); string vmName = _vmDisplayName; int vmId = id++; // Establish per-disk info Guid[] vbdGuids = new Guid[_disks.Count]; int[] vbdIds = new int[_disks.Count]; Guid[] vdiGuids = new Guid[_disks.Count]; string[] vdiNames = new string[_disks.Count]; int[] vdiIds = new int[_disks.Count]; long[] vdiSizes = new long[_disks.Count]; int diskIdx = 0; foreach (var disk in _disks) { vbdGuids[diskIdx] = Guid.NewGuid(); vbdIds[diskIdx] = id++; vdiGuids[diskIdx] = Guid.NewGuid(); vdiIds[diskIdx] = id++; vdiNames[diskIdx] = disk.First; vdiSizes[diskIdx] = Utilities.RoundUp(disk.Second.Length, Sizes.OneMiB); diskIdx++; } // Establish SR info Guid srGuid = Guid.NewGuid(); string srName = "SR"; int srId = id++; string vbdRefs = string.Empty; for (int i = 0; i < _disks.Count; ++i) { vbdRefs += string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_ref, "Ref:" + vbdIds[i]); } string vdiRefs = string.Empty; for (int i = 0; i < _disks.Count; ++i) { vdiRefs += string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_ref, "Ref:" + vdiIds[i]); } StringBuilder objectsString = new StringBuilder(); objectsString.Append(string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_vm, "Ref:" + vmId, vmGuid, vmName, vbdRefs)); for (int i = 0; i < _disks.Count; ++i) { objectsString.Append(string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_vbd, "Ref:" + vbdIds[i], vbdGuids[i], "Ref:" + vmId, "Ref:" + vdiIds[i], i)); } for (int i = 0; i < _disks.Count; ++i) { objectsString.Append( string.Format( CultureInfo.InvariantCulture, Resources.XVA_ova_vdi, "Ref:" + vdiIds[i], vdiGuids[i], vdiNames[i], "Ref:" + srId, "Ref:" + vbdIds[i], vdiSizes[i])); } objectsString.Append(string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_sr, "Ref:" + srId, srGuid, srName, vdiRefs)); diskIds = vdiIds; return string.Format(CultureInfo.InvariantCulture, Resources.XVA_ova_base, objectsString.ToString()); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Rulesets.Osu; using osu.Game.Scoring; using osu.Game.Screens.Ranking; using osuTK.Input; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneScorePanelList : OsuManualInputManagerTestScene { private ScorePanelList list; [Test] public void TestEmptyList() { createListStep(() => new ScorePanelList()); } [Test] public void TestEmptyListWithSelectedScore() { createListStep(() => new ScorePanelList { SelectedScore = { Value = new TestScoreInfo(new OsuRuleset().RulesetInfo) } }); } [Test] public void TestAddPanelAfterSelectingScore() { var score = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => new ScorePanelList { SelectedScore = { Value = score } }); AddStep("add panel", () => list.AddScore(score)); assertScoreState(score, true); assertExpandedPanelCentred(); } [Test] public void TestAddPanelBeforeSelectingScore() { var score = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => new ScorePanelList()); AddStep("add panel", () => list.AddScore(score)); assertScoreState(score, false); assertFirstPanelCentred(); AddStep("select score", () => list.SelectedScore.Value = score); assertScoreState(score, true); assertExpandedPanelCentred(); } [Test] public void TestAddManyNonExpandedPanels() { createListStep(() => new ScorePanelList()); AddStep("add many scores", () => { for (int i = 0; i < 20; i++) list.AddScore(new TestScoreInfo(new OsuRuleset().RulesetInfo)); }); assertFirstPanelCentred(); } [Test] public void TestAddManyScoresAfterExpandedPanel() { var initialScore = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => new ScorePanelList()); AddStep("add initial panel and select", () => { list.AddScore(initialScore); list.SelectedScore.Value = initialScore; }); AddStep("add many scores", () => { for (int i = 0; i < 20; i++) list.AddScore(new TestScoreInfo(new OsuRuleset().RulesetInfo) { TotalScore = initialScore.TotalScore - i - 1 }); }); assertScoreState(initialScore, true); assertExpandedPanelCentred(); } [Test] public void TestAddManyScoresBeforeExpandedPanel() { var initialScore = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => new ScorePanelList()); AddStep("add initial panel and select", () => { list.AddScore(initialScore); list.SelectedScore.Value = initialScore; }); AddStep("add scores", () => { for (int i = 0; i < 20; i++) list.AddScore(new TestScoreInfo(new OsuRuleset().RulesetInfo) { TotalScore = initialScore.TotalScore + i + 1 }); }); assertScoreState(initialScore, true); assertExpandedPanelCentred(); } [Test] public void TestAddManyPanelsOnBothSidesOfExpandedPanel() { var initialScore = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => new ScorePanelList()); AddStep("add initial panel and select", () => { list.AddScore(initialScore); list.SelectedScore.Value = initialScore; }); AddStep("add scores after", () => { for (int i = 0; i < 20; i++) list.AddScore(new TestScoreInfo(new OsuRuleset().RulesetInfo) { TotalScore = initialScore.TotalScore - i - 1 }); for (int i = 0; i < 20; i++) list.AddScore(new TestScoreInfo(new OsuRuleset().RulesetInfo) { TotalScore = initialScore.TotalScore + i + 1 }); }); assertScoreState(initialScore, true); assertExpandedPanelCentred(); } [Test] public void TestSelectMultipleScores() { var firstScore = new TestScoreInfo(new OsuRuleset().RulesetInfo); var secondScore = new TestScoreInfo(new OsuRuleset().RulesetInfo); firstScore.User.Username = "A"; secondScore.User.Username = "B"; createListStep(() => new ScorePanelList()); AddStep("add scores and select first", () => { list.AddScore(firstScore); list.AddScore(secondScore); list.SelectedScore.Value = firstScore; }); AddUntilStep("wait for load", () => list.AllPanelsVisible); assertScoreState(firstScore, true); assertScoreState(secondScore, false); AddStep("select second score", () => { InputManager.MoveMouseTo(list.ChildrenOfType<ScorePanel>().Single(p => p.Score == secondScore)); InputManager.Click(MouseButton.Left); }); assertScoreState(firstScore, false); assertScoreState(secondScore, true); assertExpandedPanelCentred(); } [Test] public void TestAddScoreImmediately() { var score = new TestScoreInfo(new OsuRuleset().RulesetInfo); createListStep(() => { var newList = new ScorePanelList { SelectedScore = { Value = score } }; newList.AddScore(score); return newList; }); assertScoreState(score, true); assertExpandedPanelCentred(); } [Test] public void TestKeyboardNavigation() { var lowestScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { MaxCombo = 100 }; var middleScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { MaxCombo = 200 }; var highestScore = new TestScoreInfo(new OsuRuleset().RulesetInfo) { MaxCombo = 300 }; createListStep(() => new ScorePanelList()); AddStep("add scores and select middle", () => { // order of addition purposefully scrambled. list.AddScore(middleScore); list.AddScore(lowestScore); list.AddScore(highestScore); list.SelectedScore.Value = middleScore; }); AddUntilStep("wait for all scores to be visible", () => list.ChildrenOfType<ScorePanelTrackingContainer>().All(t => t.IsPresent)); assertScoreState(highestScore, false); assertScoreState(middleScore, true); assertScoreState(lowestScore, false); AddStep("press left", () => InputManager.Key(Key.Left)); assertScoreState(highestScore, true); assertScoreState(middleScore, false); assertScoreState(lowestScore, false); assertExpandedPanelCentred(); AddStep("press left at start of list", () => InputManager.Key(Key.Left)); assertScoreState(highestScore, true); assertScoreState(middleScore, false); assertScoreState(lowestScore, false); assertExpandedPanelCentred(); AddStep("press right", () => InputManager.Key(Key.Right)); assertScoreState(highestScore, false); assertScoreState(middleScore, true); assertScoreState(lowestScore, false); assertExpandedPanelCentred(); AddStep("press right again", () => InputManager.Key(Key.Right)); assertScoreState(highestScore, false); assertScoreState(middleScore, false); assertScoreState(lowestScore, true); assertExpandedPanelCentred(); AddStep("press right at end of list", () => InputManager.Key(Key.Right)); assertScoreState(highestScore, false); assertScoreState(middleScore, false); assertScoreState(lowestScore, true); assertExpandedPanelCentred(); AddStep("press left", () => InputManager.Key(Key.Left)); assertScoreState(highestScore, false); assertScoreState(middleScore, true); assertScoreState(lowestScore, false); assertExpandedPanelCentred(); } private void createListStep(Func<ScorePanelList> creationFunc) { AddStep("create list", () => Child = list = creationFunc().With(d => { d.Anchor = Anchor.Centre; d.Origin = Anchor.Centre; })); AddUntilStep("wait for load", () => list.IsLoaded); } private void assertExpandedPanelCentred() => AddUntilStep("expanded panel centred", () => { var expandedPanel = list.ChildrenOfType<ScorePanel>().Single(p => p.State == PanelState.Expanded); return Precision.AlmostEquals(expandedPanel.ScreenSpaceDrawQuad.Centre.X, list.ScreenSpaceDrawQuad.Centre.X, 1); }); private void assertFirstPanelCentred() => AddUntilStep("first panel centred", () => Precision.AlmostEquals(list.ChildrenOfType<ScorePanel>().First().ScreenSpaceDrawQuad.Centre.X, list.ScreenSpaceDrawQuad.Centre.X, 1)); private void assertScoreState(ScoreInfo score, bool expanded) => AddUntilStep($"score expanded = {expanded}", () => (list.ChildrenOfType<ScorePanel>().Single(p => p.Score == score).State == PanelState.Expanded) == expanded); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; namespace System.Xml { // Represents an entity reference node. // <code>EntityReference</code> objects may be inserted into the structure // model when an entity reference is in the source document, or when the user // wishes to insert an entity reference. Note that character references and // references to predefined entities are considered to be expanded by the // HTML or XML processor so that characters are represented by their Unicode // equivalent rather than by an entity reference. Moreover, the XML // processor may completely expand references to entities while building the // structure model, instead of providing <code>EntityReference</code> // objects. If it does provide such objects, then for a given // <code>EntityReference</code> node, it may be that there is no // <code>Entity</code> node representing the referenced entity; but if such // an <code>Entity</code> exists, then the child list of the // <code>EntityReference</code> node is the same as that of the // <code>Entity</code> node. As with the <code>Entity</code> node, all // descendants of the <code>EntityReference</code> are readonly. // <p>The resolution of the children of the <code>EntityReference</code> (the // replacement value of the referenced <code>Entity</code>) may be lazily // evaluated; actions by the user (such as calling the // <code>childNodes</code> method on the <code>EntityReference</code> node) // are assumed to trigger the evaluation. internal class XmlEntityReference : XmlLinkedNode { private string _name; private XmlLinkedNode _lastChild; protected internal XmlEntityReference(string name, XmlDocument doc) : base(doc) { if (!doc.IsLoading) { if (name.Length > 0 && name[0] == '#') { throw new ArgumentException(SR.Xdom_InvalidCharacter_EntityReference); } } _name = doc.NameTable.Add(name); doc.fEntRefNodesPresent = true; } // Gets the name of the node. public override string Name { get { return _name; } } // Gets the name of the node without the namespace prefix. public override string LocalName { get { return _name; } } // Gets or sets the value of the node. public override String Value { get { return null; } set { throw new InvalidOperationException(SR.Xdom_EntRef_SetVal); } } // Gets the type of the node. public override XmlNodeType NodeType { get { return XmlNodeType.EntityReference; } } // Creates a duplicate of this node. public override XmlNode CloneNode(bool deep) { Debug.Assert(OwnerDocument != null); XmlEntityReference eref = OwnerDocument.CreateEntityReference(_name); return eref; } // // Microsoft extensions // // Gets a value indicating whether the node is read-only. public override bool IsReadOnly { get { return true; // Make entity references readonly } } internal override bool IsContainer { get { return true; } } internal override void SetParent(XmlNode node) { base.SetParent(node); if (LastNode == null && node != null && node != OwnerDocument) { //first time insert the entity reference into the tree, we should expand its children now XmlLoader loader = new XmlLoader(); loader.ExpandEntityReference(this); } } internal override void SetParentForLoad(XmlNode node) { this.SetParent(node); } internal override XmlLinkedNode LastNode { get { return _lastChild; } set { _lastChild = value; } } internal override bool IsValidChildType(XmlNodeType type) { switch (type) { case XmlNodeType.Element: case XmlNodeType.Text: case XmlNodeType.EntityReference: case XmlNodeType.Comment: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.ProcessingInstruction: case XmlNodeType.CDATA: return true; default: return false; } } // Saves the node to the specified XmlWriter. public override void WriteTo(XmlWriter w) { w.WriteEntityRef(_name); } // Saves all the children of the node to the specified XmlWriter. public override void WriteContentTo(XmlWriter w) { // -- eventually will the fix. commented out waiting for finalizing on the issue. foreach (XmlNode n in this) { n.WriteTo(w); } //still use the old code to generate the output /* foreach( XmlNode n in this ) { if ( n.NodeType != XmlNodeType.EntityReference ) n.WriteTo( w ); else n.WriteContentTo( w ); }*/ } public override String BaseURI { get { return OwnerDocument.BaseURI; } } private string ConstructBaseURI(string baseURI, string systemId) { if (baseURI == null) return systemId; int nCount = baseURI.LastIndexOf('/') + 1; string buf = baseURI; if (nCount > 0 && nCount < baseURI.Length) buf = baseURI.Substring(0, nCount); else if (nCount == 0) buf = buf + "\\"; return (buf + systemId.Replace('\\', '/')); } //childrenBaseURI returns where the entity reference node's children come from internal String ChildBaseURI { get { //get the associate entity and return its baseUri XmlEntity ent = OwnerDocument.GetEntityNode(_name); if (ent != null) { if (!string.IsNullOrEmpty(ent.SystemId)) return ConstructBaseURI(ent.BaseURI, ent.SystemId); else return ent.BaseURI; } return String.Empty; } } } }
// <copyright file="OptionalValue.cs" company="Fubar Development Junker"> // Copyright (c) 2016 Fubar Development Junker. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // </copyright> using System; namespace BeanIO.Internal.Parser { internal sealed class OptionalValue : IComparable<OptionalValue>, IEquatable<OptionalValue>, IComparable { /// <summary> /// Constant indicating the field did not pass validation /// </summary> public static readonly OptionalValue Invalid = new OptionalValue(Status.Invalid); /// <summary> /// Constant indicating the field was not present in the stream /// </summary> public static readonly OptionalValue Missing = new OptionalValue(Status.Missing); /// <summary> /// Constant indicating the field was nil (XML only) /// </summary> public static readonly OptionalValue Nil = new OptionalValue(Status.Nil); private readonly Status _status; private readonly string _value; /// <summary> /// Initializes a new instance of the <see cref="OptionalValue"/> class. /// </summary> /// <param name="text">The text value to initialize the <see cref="OptionalValue"/> with.</param> public OptionalValue(string text) { _value = text; _status = Status.HasValue; } private OptionalValue(Status status) { _value = null; _status = status; } private enum Status { Invalid, Missing, Nil, HasValue } public bool IsInvalid => _status == Status.Invalid; public bool IsMissing => _status == Status.Missing; public bool IsNil => _status == Status.Nil; public bool HasText => _status == Status.HasValue; public string Text { get { if (!HasText) throw new InvalidOperationException(); return _value; } } internal int StatusHashCode => _status.GetHashCode(); public static implicit operator OptionalValue(string text) { return new OptionalValue(text); } public static implicit operator string(OptionalValue value) { return value.GetTextOrDefault(); } public static bool operator ==(OptionalValue value1, OptionalValue value2) { return OptionalValueComparer.Default.Equals(value1, value2); } public static bool operator !=(OptionalValue value1, OptionalValue value2) { return !OptionalValueComparer.Default.Equals(value1, value2); } public static bool operator <(OptionalValue value1, OptionalValue value2) { return OptionalValueComparer.Default.Compare(value1, value2) < 0; } public static bool operator >(OptionalValue value1, OptionalValue value2) { return OptionalValueComparer.Default.Compare(value1, value2) > 0; } public static bool operator <=(OptionalValue value1, OptionalValue value2) { return OptionalValueComparer.Default.Compare(value1, value2) <= 0; } public static bool operator >=(OptionalValue value1, OptionalValue value2) { return OptionalValueComparer.Default.Compare(value1, value2) >= 0; } public string GetTextOrDefault() { return GetTextOrDefault(null); } public string GetTextOrDefault(string defaultValue) { if (HasText) return Text; return defaultValue; } /// <summary> /// Compare this object to another /// </summary> /// <param name="obj">The other object to compare to</param> /// <returns>0, if equal, &lt;0 if less and &gt;0 if greater</returns> public int CompareTo(object obj) { return CompareTo((OptionalValue)obj); } /// <summary> /// Compare this object to another /// </summary> /// <param name="other">The other object to compare to</param> /// <returns>0, if equal, &lt;0 if less and &gt;0 if greater</returns> public int CompareTo(OptionalValue other) { return OptionalValueComparer.Default.Compare(this, other); } /// <summary> /// Determines whether this object equals to another of the same type. /// </summary> /// <param name="other">The object to compare to</param> /// <returns>true, when both objects are equal</returns> public bool Equals(OptionalValue other) { return OptionalValueComparer.Default.Equals(this, other); } /// <summary> /// Determines whether this object equals to another of the same type. /// </summary> /// <param name="obj">The object to compare to</param> /// <returns>true, when both objects are equal</returns> public override bool Equals(object obj) { return Equals((OptionalValue)obj); } /// <summary> /// Returns the hash code. /// </summary> /// <returns> /// The hash code for the current object. /// </returns> public override int GetHashCode() { return OptionalValueComparer.Default.GetHashCode(this); } /// <summary> /// Returns the status and value of the <see cref="OptionalValue"/>. /// </summary> /// <returns>the status and value of the <see cref="OptionalValue"/></returns> public override string ToString() { switch (_status) { case Status.Invalid: return "-invalid-"; case Status.Missing: return "-missing-"; case Status.Nil: return "-nil-"; } return _value ?? string.Empty; } internal int CompareStatus(OptionalValue other) { return ((int)_status).CompareTo((int)other._status); } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using Rotorz.Games.EditorExtensions; using System; using System.Linq; using System.Text.RegularExpressions; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace Rotorz.Tile.Editor { /// <summary> /// Utility functions to asset with the management and usage of tile system presets. /// </summary> /// <seealso cref="TileSystemPreset"/> /// <seealso cref="TileSystem"/> public static class TileSystemPresetUtility { #region Preset Management /// <summary> /// Gets the default preset GUID based upon whether the project is in 2D or 3D mode. /// </summary> internal static string DefaultPresetGUID { get { return EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode3D ? "F:3D" : "F:2D"; } } /// <summary> /// Determines whether the specified name is valid for a tile system preset. /// </summary> /// <remarks> /// <para>The name of a preset may contain alphanumeric characters (A-Z, a-z, 0-9), /// underscores _, hyphens - and spaces.</para> /// </remarks> /// <param name="presetName">The candidate preset name.</param> /// <returns> /// A value of <c>true</c> if the name was valid; otherwise, a value of <c>false</c> /// if the name was invalid or <c>null</c>. /// </returns> public static bool IsValidPresetName(string presetName) { if (presetName == null) { return false; } presetName = presetName.Trim(); return presetName != "" && Regex.IsMatch(presetName, @"^[a-z0-9_\- ]+$", RegexOptions.IgnoreCase); } /// <summary> /// Determines whether the specified tile system preset is located within the /// main "User Data" directory structure. /// </summary> /// <param name="preset">Tile system preset.</param> /// <returns> /// A value of <c>true</c> if the preset is located in the main "User Data" /// directory; otherwise, a value of <c>false</c>. /// </returns> /// <exception cref="System.ArgumentNullException"> /// If <paramref name="preset"/> is <c>null</c>. /// </exception> public static bool IsUserPreset(TileSystemPreset preset) { if (preset == null) { throw new ArgumentNullException("preset"); } string presetAssetPath = AssetDatabase.GetAssetPath(preset); string userPresetsBasePath = PackageUtility.ResolveDataAssetPath("@rotorz/unity3d-tile-system", "Presets") + "/"; return presetAssetPath.StartsWith(userPresetsBasePath); } internal static string GetPresetGUID(TileSystemPreset preset) { return preset != null ? AssetDatabase.AssetPathToGUID(AssetDatabase.GetAssetPath(preset)) : null; } /// <summary> /// Loads the <see cref="TileSystemPreset"/> from the specified preset asset GUID. /// </summary> /// <param name="presetGuid">GUID of the preset.</param> /// <returns> /// The <see cref="TileSystemPreset"/> reference when found; otherwise, a value /// of <c>null</c> if preset does not exist. /// </returns> public static TileSystemPreset LoadPresetFromGUID(string presetGuid) { return presetGuid != "F:3D" && presetGuid != "F:2D" ? AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(presetGuid), typeof(TileSystemPreset)) as TileSystemPreset : null; } /// <summary> /// Gets an array of all the <see cref="TileSystemPreset"/> assets in the project. /// </summary> /// <returns> /// Array of <see cref="TileSystemPreset"/> assets. /// </returns> public static TileSystemPreset[] GetPresets() { return ( from assetGuid in AssetDatabase.FindAssets("t:Rotorz.Tile.Editor.TileSystemPreset") select AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(assetGuid), typeof(TileSystemPreset)) as TileSystemPreset ).ToArray(); } private static TileSystemPreset SavePresetAsHelper(TileSystemPreset source, string presetAssetPath) { if (source == null) { throw new ArgumentNullException("source"); } if (string.IsNullOrEmpty(presetAssetPath)) { throw new ArgumentNullException("presetAssetPath"); } // Load existing preset if it exists. var preset = AssetDatabase.LoadAssetAtPath(presetAssetPath, typeof(TileSystemPreset)) as TileSystemPreset; if (preset != null) { EditorUtility.CopySerialized(source, preset); EditorUtility.SetDirty(preset); AssetDatabase.SaveAssets(); } else { preset = Object.Instantiate(source) as TileSystemPreset; preset.name = Regex.Match(presetAssetPath, @"/([a-z0-9_\- ]+)\.asset$", RegexOptions.IgnoreCase).Groups[1].Value; AssetDatabase.CreateAsset(preset, presetAssetPath); AssetDatabase.Refresh(); } return preset; } /// <summary> /// Creates a new tile system preset by copying the properties of the source /// preset. If a preset already exists with the same name then it will be /// overwritten. /// </summary> /// <param name="source">Source preset.</param> /// <param name="presetName">Name of the new preset.</param> /// <returns> /// A reference to the new <see cref="TileSystemPreset"/> asset. /// </returns> /// <exception cref="System.ArgumentNullException"> /// <list type="bullet"> /// <item>If <paramref name="source"/> is <c>null</c>.</item> /// <item>If <paramref name="presetName"/> is <c>null</c>.</item> /// </list> /// </exception> /// <exception cref="System.ArgumentException"> /// If <paramref name="presetName"/> is not a valid preset name. /// </exception> public static TileSystemPreset CreatePreset(TileSystemPreset source, string presetName) { if (presetName == null) { throw new ArgumentNullException("presetName"); } if (!IsValidPresetName(presetName)) { throw new ArgumentException("Invalid preset name.", "presetName"); } string presetAssetPath = PackageUtility.GetDataAssetPath("@rotorz/unity3d-tile-system", "Presets", presetName.Trim() + ".asset"); return SavePresetAsHelper(source, presetAssetPath); } /// <summary> /// Overwrites an existing tile system preset by copying the properties of the /// source preset into the destination preset. /// </summary> /// <param name="source">Source preset.</param> /// <param name="dest">Destination preset.</param> /// <exception cref="System.ArgumentNullException"> /// <list type="bullet"> /// <item>If <paramref name="source"/> is <c>null</c>.</item> /// <item>If <paramref name="dest"/> is <c>null</c>.</item> /// </list> /// </exception> /// <exception cref="System.ArgumentException"> /// If <paramref name="dest"/> is not a persisted asset file. /// </exception> public static void OverwritePreset(TileSystemPreset source, TileSystemPreset dest) { if (dest == null) { throw new ArgumentNullException("dest"); } if (!EditorUtility.IsPersistent(dest)) { throw new InvalidOperationException("Cannot overwrite non-persistent preset."); } string presetAssetPath = AssetDatabase.GetAssetPath(dest); SavePresetAsHelper(source, presetAssetPath); } /// <summary> /// Deletes an unwanted tile system preset. /// </summary> /// <param name="preset">Tile system preset.</param> /// <exception cref="System.ArgumentNullException"> /// If <paramref name="preset"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// If <paramref name="preset"/> is not a known asset file. /// </exception> public static void DeletePreset(TileSystemPreset preset) { if (preset == null) { throw new ArgumentNullException("preset"); } if (!AssetDatabase.Contains(preset)) { throw new InvalidOperationException(string.Format("Cannot delete preset '{0}' because it is not an asset file.", preset.name)); } string assetPath = AssetDatabase.GetAssetPath(preset); AssetDatabase.MoveAssetToTrash(assetPath); PackageUtility.DeleteDataFolderIfEmpty("@rotorz/unity3d-tile-system", "Presets"); } #endregion #region Tile System Creation /// <summary> /// Creates a new tile system using properties from the specified preset. /// </summary> /// <remarks> /// <para>This method does not automatically record the new game object with /// Unity's undo system. If undo functionality is desired then the callee should /// do this.</para> /// </remarks> /// <param name="preset">Tile system preset.</param> /// <returns> /// A new game object with an initialized <see cref="TileSystem"/>. /// </returns> /// <exception cref="System.ArgumentNullException"> /// If <paramref name="preset"/> is <c>null</c>. /// </exception> /// <exception cref="System.InvalidOperationException"> /// <list type="bullet"> /// <item>If preset defines an invalid name for a tile system.</item> /// <item>If preset defines a tile system with less than one cell.</item> /// </list> /// </exception> public static GameObject CreateTileSystemFromPreset(TileSystemPreset preset) { if (preset == null) { throw new ArgumentNullException("preset"); } string name = preset.SystemName.Trim(); if (string.IsNullOrEmpty(name)) { throw new InvalidOperationException("Invalid name for tile system."); } if (preset.Rows < 1 || preset.Columns < 1) { throw new InvalidOperationException("Tile system must have at least one cell."); } // Create empty game object and add tile system component. var go = new GameObject(name); var tileSystem = go.AddComponent<TileSystem>(); tileSystem.CreateSystem(preset.TileWidth, preset.TileHeight, preset.TileDepth, preset.Rows, preset.Columns, preset.ChunkWidth, preset.ChunkHeight); TransformTileSystemUsingPreset(preset, go.transform); SetTileSystemPropertiesFromPreset(preset, tileSystem); // Place at end of the scene palette listing. tileSystem.sceneOrder = int.MaxValue; ToolUtility.RepaintScenePalette(); return go; } private static void TransformTileSystemUsingPreset(TileSystemPreset preset, Transform tileSystemTransform) { switch (preset.Direction) { default: case WorldDirection.Forward: break; case WorldDirection.Backward: tileSystemTransform.Rotate(Vector3.up, 180f, Space.Self); break; case WorldDirection.Up: tileSystemTransform.Rotate(Vector3.right, 90f, Space.Self); break; case WorldDirection.Down: tileSystemTransform.Rotate(Vector3.right, 270f, Space.Self); break; case WorldDirection.Left: tileSystemTransform.Rotate(Vector3.up, 90f, Space.Self); break; case WorldDirection.Right: tileSystemTransform.Rotate(Vector3.up, 270f, Space.Self); break; } } private static void SetTileSystemPropertiesFromPreset(TileSystemPreset preset, TileSystem tileSystem) { // Grid tileSystem.TilesFacing = preset.TilesFacing; // Stripping tileSystem.StrippingPreset = preset.StrippingPreset; if (preset.StrippingPreset == StrippingPreset.Custom) { tileSystem.StrippingOptions = preset.StrippingOptions; } // Build Options tileSystem.combineMethod = preset.CombineMethod; tileSystem.combineChunkWidth = preset.CombineChunkWidth; tileSystem.combineChunkHeight = preset.CombineChunkHeight; tileSystem.combineIntoSubmeshes = preset.CombineIntoSubmeshes; tileSystem.staticVertexSnapping = preset.StaticVertexSnapping; tileSystem.vertexSnapThreshold = preset.VertexSnapThreshold; tileSystem.GenerateSecondUVs = preset.GenerateSecondUVs; tileSystem.SecondUVsHardAngle = preset.GenerateSecondUVsParams.hardAngle; tileSystem.SecondUVsPackMargin = preset.GenerateSecondUVsParams.packMargin; tileSystem.SecondUVsAngleError = preset.GenerateSecondUVsParams.angleError; tileSystem.SecondUVsAreaError = preset.GenerateSecondUVsParams.areaError; tileSystem.pregenerateProcedural = preset.PregenerateProcedural; tileSystem.ReduceColliders.SetFrom(preset.ReduceColliders); // Runtime Options tileSystem.hintEraseEmptyChunks = preset.HintEraseEmptyChunks; tileSystem.applyRuntimeStripping = preset.ApplyRuntimeStripping; tileSystem.updateProceduralAtStart = preset.UpdateProceduralAtStart; tileSystem.MarkProceduralDynamic = preset.MarkProceduralDynamic; tileSystem.addProceduralNormals = preset.AddProceduralNormals; tileSystem.SortingLayerID = preset.SortingLayerID; tileSystem.SortingOrder = preset.SortingOrder; } #endregion } }
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ using System; using System.IO; using System.Collections.Generic; using System.Text; using erl.Oracle.TnsNames.Antlr4.Runtime; using erl.Oracle.TnsNames.Antlr4.Runtime.Atn; using erl.Oracle.TnsNames.Antlr4.Runtime.Misc; using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen; namespace erl.Oracle.TnsNames.Antlr4.Runtime { /// <summary>A lexer is recognizer that draws input symbols from a character stream.</summary> /// <remarks> /// A lexer is recognizer that draws input symbols from a character stream. /// lexer grammars result in a subclass of this object. A Lexer object /// uses simplified match() and error recovery mechanisms in the interest /// of speed. /// </remarks> public abstract class Lexer : Recognizer<int, LexerATNSimulator>, ITokenSource { public const int DEFAULT_MODE = 0; public const int DefaultTokenChannel = TokenConstants.DefaultChannel; public const int Hidden = TokenConstants.HiddenChannel; public const int MinCharValue = 0x0000; public const int MaxCharValue = 0x10FFFF; private ICharStream _input; protected readonly TextWriter Output; protected readonly TextWriter ErrorOutput; private Tuple<ITokenSource, ICharStream> _tokenFactorySourcePair; /// <summary>How to create token objects</summary> private ITokenFactory _factory = CommonTokenFactory.Default; /// <summary>The goal of all lexer rules/methods is to create a token object.</summary> /// <remarks> /// The goal of all lexer rules/methods is to create a token object. /// This is an instance variable as multiple rules may collaborate to /// create a single token. nextToken will return this object after /// matching lexer rule(s). If you subclass to allow multiple token /// emissions, then set this to the last token to be matched or /// something nonnull so that the auto token emit mechanism will not /// emit another token. /// </remarks> private IToken _token; /// <summary> /// What character index in the stream did the current token start at? /// Needed, for example, to get the text for current token. /// </summary> /// <remarks> /// What character index in the stream did the current token start at? /// Needed, for example, to get the text for current token. Set at /// the start of nextToken. /// </remarks> private int _tokenStartCharIndex = -1; /// <summary>The line on which the first character of the token resides</summary> private int _tokenStartLine; /// <summary>The character position of first character within the line</summary> private int _tokenStartColumn; /// <summary>Once we see EOF on char stream, next token will be EOF.</summary> /// <remarks> /// Once we see EOF on char stream, next token will be EOF. /// If you have DONE : EOF ; then you see DONE EOF. /// </remarks> private bool _hitEOF; /// <summary>The channel number for the current token</summary> private int _channel; /// <summary>The token type for the current token</summary> private int _type; private readonly Stack<int> _modeStack = new Stack<int>(); private int _mode = erl.Oracle.TnsNames.Antlr4.Runtime.Lexer.DEFAULT_MODE; /// <summary> /// You can set the text for the current token to override what is in /// the input char buffer. /// </summary> /// <remarks> /// You can set the text for the current token to override what is in /// the input char buffer. Use setText() or can set this instance var. /// </remarks> private string _text; public Lexer(ICharStream input) : this(input, Console.Out, Console.Error) { } public Lexer(ICharStream input, TextWriter output, TextWriter errorOutput) { this._input = input; this.Output = output; this.ErrorOutput = errorOutput; this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, input); } public virtual void Reset() { // wack Lexer state variables if (_input != null) { _input.Seek(0); } // rewind the input _token = null; _type = TokenConstants.InvalidType; _channel = TokenConstants.DefaultChannel; _tokenStartCharIndex = -1; _tokenStartColumn = -1; _tokenStartLine = -1; _text = null; _hitEOF = false; _mode = erl.Oracle.TnsNames.Antlr4.Runtime.Lexer.DEFAULT_MODE; _modeStack.Clear(); Interpreter.Reset(); } /// <summary> /// Return a token from this source; i.e., match a token on the char /// stream. /// </summary> /// <remarks> /// Return a token from this source; i.e., match a token on the char /// stream. /// </remarks> public virtual IToken NextToken() { if (_input == null) { throw new InvalidOperationException("nextToken requires a non-null input stream."); } // Mark start location in char stream so unbuffered streams are // guaranteed at least have text of current token int tokenStartMarker = _input.Mark(); try { while (true) { if (_hitEOF) { EmitEOF(); return _token; } _token = null; _channel = TokenConstants.DefaultChannel; _tokenStartCharIndex = _input.Index; _tokenStartColumn = Interpreter.Column; _tokenStartLine = Interpreter.Line; _text = null; do { _type = TokenConstants.InvalidType; // System.out.println("nextToken line "+tokenStartLine+" at "+((char)input.LA(1))+ // " in mode "+mode+ // " at index "+input.index()); int ttype; try { ttype = Interpreter.Match(_input, _mode); } catch (LexerNoViableAltException e) { NotifyListeners(e); // report error Recover(e); ttype = TokenTypes.Skip; } if (_input.LA(1) == IntStreamConstants.EOF) { _hitEOF = true; } if (_type == TokenConstants.InvalidType) { _type = ttype; } if (_type == TokenTypes.Skip) { goto outer_continue; } } while (_type == TokenTypes.More); if (_token == null) { Emit(); } return _token; outer_continue: ; } } finally { // make sure we release marker after match or // unbuffered char stream will keep buffering _input.Release(tokenStartMarker); } } /// <summary> /// Instruct the lexer to skip creating a token for current lexer rule /// and look for another token. /// </summary> /// <remarks> /// Instruct the lexer to skip creating a token for current lexer rule /// and look for another token. nextToken() knows to keep looking when /// a lexer rule finishes with token set to SKIP_TOKEN. Recall that /// if token==null at end of any token rule, it creates one for you /// and emits it. /// </remarks> public virtual void Skip() { _type = TokenTypes.Skip; } public virtual void More() { _type = TokenTypes.More; } public virtual void Mode(int m) { _mode = m; } public virtual void PushMode(int m) { _modeStack.Push(_mode); Mode(m); } public virtual int PopMode() { if (_modeStack.Count == 0) { throw new InvalidOperationException(); } int mode = _modeStack.Pop(); Mode(mode); return _mode; } public virtual ITokenFactory TokenFactory { get { return _factory; } set { ITokenFactory factory = value; this._factory = factory; } } /// <summary>Set the char stream and reset the lexer</summary> public virtual void SetInputStream(ICharStream input) { this._input = null; this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input); Reset(); this._input = input; this._tokenFactorySourcePair = Tuple.Create((ITokenSource)this, _input); } public virtual string SourceName { get { return _input.SourceName; } } public override IIntStream InputStream { get { return _input; } } ICharStream ITokenSource.InputStream { get { return _input; } } /// <summary> /// By default does not support multiple emits per nextToken invocation /// for efficiency reasons. /// </summary> /// <remarks> /// By default does not support multiple emits per nextToken invocation /// for efficiency reasons. Subclass and override this method, nextToken, /// and getToken (to push tokens into a list and pull from that list /// rather than a single variable as this implementation does). /// </remarks> public virtual void Emit(IToken token) { //System.err.println("emit "+token); this._token = token; } /// <summary> /// The standard method called to automatically emit a token at the /// outermost lexical rule. /// </summary> /// <remarks> /// The standard method called to automatically emit a token at the /// outermost lexical rule. The token object should point into the /// char buffer start..stop. If there is a text override in 'text', /// use that to set the token's text. Override this method to emit /// custom Token objects or provide a new factory. /// </remarks> public virtual IToken Emit() { IToken t = _factory.Create(_tokenFactorySourcePair, _type, _text, _channel, _tokenStartCharIndex, CharIndex - 1, _tokenStartLine, _tokenStartColumn); Emit(t); return t; } public virtual IToken EmitEOF() { int cpos = Column; int line = Line; IToken eof = _factory.Create(_tokenFactorySourcePair, TokenConstants.EOF, null, TokenConstants.DefaultChannel, _input.Index, _input.Index - 1, line, cpos); Emit(eof); return eof; } public virtual int Line { get { return Interpreter.Line; } set { int line = value; Interpreter.Line = line; } } public virtual int Column { get { return Interpreter.Column; } set { int charPositionInLine = value; Interpreter.Column = charPositionInLine; } } /// <summary>What is the index of the current character of lookahead?</summary> public virtual int CharIndex { get { return _input.Index; } } public virtual int TokenStartCharIndex { get { return _tokenStartCharIndex; } } public virtual int TokenStartLine { get { return _tokenStartLine; } } public virtual int TokenStartColumn { get { return _tokenStartColumn; } } /// <summary> /// Return the text matched so far for the current token or any text /// override. /// </summary> /// <remarks> /// Return the text matched so far for the current token or any text /// override. /// </remarks> /// <summary> /// Set the complete text of this token; it wipes any previous changes to the /// text. /// </summary> /// <remarks> /// Set the complete text of this token; it wipes any previous changes to the /// text. /// </remarks> public virtual string Text { get { if (_text != null) { return _text; } return Interpreter.GetText(_input); } set { string text = value; this._text = text; } } /// <summary>Override if emitting multiple tokens.</summary> /// <remarks>Override if emitting multiple tokens.</remarks> public virtual IToken Token { get { return _token; } set { IToken _token = value; this._token = _token; } } public virtual int Type { get { return _type; } set { int ttype = value; _type = ttype; } } public virtual int Channel { get { return _channel; } set { int channel = value; _channel = channel; } } public virtual Stack<int> ModeStack { get { return _modeStack; } } public virtual int CurrentMode { get { return _mode; } set { int mode = value; _mode = mode; } } public virtual bool HitEOF { get { return _hitEOF; } set { bool hitEOF = value; _hitEOF = hitEOF; } } public virtual string[] ChannelNames { get { return null; } } public virtual string[] ModeNames { get { return null; } } /// <summary>Return a list of all Token objects in input char stream.</summary> /// <remarks> /// Return a list of all Token objects in input char stream. /// Forces load of all tokens. Does not include EOF token. /// </remarks> public virtual IList<IToken> GetAllTokens() { IList<IToken> tokens = new List<IToken>(); IToken t = NextToken(); while (t.Type != TokenConstants.EOF) { tokens.Add(t); t = NextToken(); } return tokens; } public virtual void Recover(LexerNoViableAltException e) { if (_input.LA(1) != IntStreamConstants.EOF) { // skip a char and try again Interpreter.Consume(_input); } } public virtual void NotifyListeners(LexerNoViableAltException e) { string text = _input.GetText(Interval.Of(_tokenStartCharIndex, _input.Index)); string msg = "token recognition error at: '" + GetErrorDisplay(text) + "'"; IAntlrErrorListener<int> listener = ErrorListenerDispatch; listener.SyntaxError(ErrorOutput, this, 0, _tokenStartLine, _tokenStartColumn, msg, e); } public virtual string GetErrorDisplay(string s) { StringBuilder buf = new StringBuilder(); for (var i = 0; i < s.Length; ) { var codePoint = Char.ConvertToUtf32(s, i); buf.Append(GetErrorDisplay(codePoint)); i += (codePoint > 0xFFFF) ? 2 : 1; } return buf.ToString(); } public virtual string GetErrorDisplay(int c) { string s; switch (c) { case TokenConstants.EOF: { s = "<EOF>"; break; } case '\n': { s = "\\n"; break; } case '\t': { s = "\\t"; break; } case '\r': { s = "\\r"; break; } default: { s = Char.ConvertFromUtf32(c); break; } } return s; } public virtual string GetCharErrorDisplay(int c) { string s = GetErrorDisplay(c); return "'" + s + "'"; } /// <summary> /// Lexers can normally match any char in it's vocabulary after matching /// a token, so do the easy thing and just kill a character and hope /// it all works out. /// </summary> /// <remarks> /// Lexers can normally match any char in it's vocabulary after matching /// a token, so do the easy thing and just kill a character and hope /// it all works out. You can instead use the rule invocation stack /// to do sophisticated error recovery if you are in a fragment rule. /// </remarks> public virtual void Recover(RecognitionException re) { //System.out.println("consuming char "+(char)input.LA(1)+" during recovery"); //re.printStackTrace(); // TODO: Do we lose character or line position information? _input.Consume(); } } }
// 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 Permute2x128SByte2() { var test = new ImmBinaryOpTest__Permute2x128SByte2(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__Permute2x128SByte2 { private struct TestStruct { public Vector256<SByte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__Permute2x128SByte2 testClass) { var result = Avx.Permute2x128(_fld1, _fld2, 2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<SByte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<SByte> _fld1; private Vector256<SByte> _fld2; private SimpleBinaryOpTest__DataTable<SByte, SByte, SByte> _dataTable; static ImmBinaryOpTest__Permute2x128SByte2() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public ImmBinaryOpTest__Permute2x128SByte2() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new SimpleBinaryOpTest__DataTable<SByte, SByte, SByte>(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Permute2x128( Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Permute2x128( Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Permute2x128( Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)), 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Permute2x128), new Type[] { typeof(Vector256<SByte>), typeof(Vector256<SByte>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)), (byte)2 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Permute2x128( _clsVar1, _clsVar2, 2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx.Permute2x128(left, right, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__Permute2x128SByte2(); var result = Avx.Permute2x128(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Permute2x128(_fld1, _fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Permute2x128(test._fld1, test._fld2, 2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<SByte> left, Vector256<SByte> right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != right[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i < 16 ? right[i] : left[i-16])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Permute2x128)}<SByte>(Vector256<SByte>.2, Vector256<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using NiL.JS.BaseLibrary; using NiL.JS.Core.Functions; #if NET40 || NETCORE using NiL.JS.Backward; #endif namespace NiL.JS.Core.Interop { #if !(PORTABLE || NETCORE) [Serializable] #endif internal abstract class Proxy : JSObject { internal Type _hostedType; #if !(PORTABLE || NETCORE) [NonSerialized] #endif internal StringMap<IList<MemberInfo>> _members; internal GlobalContext _context; private PropertyPair _indexerProperty; private bool _indexersSupported; private ConstructorInfo _instanceCtor; private JSObject _prototypeInstance; internal virtual JSObject PrototypeInstance { get { #if (PORTABLE || NETCORE) if (_prototypeInstance == null && IsInstancePrototype && !_hostedType.GetTypeInfo().IsAbstract) { #else if (_prototypeInstance == null && IsInstancePrototype && !_hostedType.IsAbstract) { try { #endif if (_instanceCtor != null) { if (_hostedType == typeof(JSObject)) { _prototypeInstance = CreateObject(); _prototypeInstance._objectPrototype = @null; _prototypeInstance._fields = _fields; _prototypeInstance._attributes |= JSValueAttributesInternal.ProxyPrototype; } else if (typeof(JSObject).IsAssignableFrom(_hostedType)) { _prototypeInstance = _instanceCtor.Invoke(null) as JSObject; _prototypeInstance._objectPrototype = __proto__; _prototypeInstance._attributes |= JSValueAttributesInternal.ProxyPrototype; _prototypeInstance._fields = _fields; //_prototypeInstance.valueType = (JSValueType)System.Math.Max((int)JSValueType.Object, (int)_prototypeInstance.valueType); _valueType = (JSValueType)System.Math.Max((int)JSValueType.Object, (int)_prototypeInstance._valueType); } else { var instance = _instanceCtor.Invoke(null); _prototypeInstance = new ObjectWrapper(instance, this) { _attributes = _attributes | JSValueAttributesInternal.ProxyPrototype, _fields = _fields, _objectPrototype = _context.GlobalContext._GlobalPrototype }; } } #if !(PORTABLE || NETCORE) } catch (COMException) { } #endif } return _prototypeInstance; } } internal abstract bool IsInstancePrototype { get; } internal Proxy(GlobalContext context, Type type, bool indexersSupport) { _indexersSupported = indexersSupport; _valueType = JSValueType.Object; _oValue = this; _attributes |= JSValueAttributesInternal.SystemObject | JSValueAttributesInternal.DoNotEnumerate; _fields = getFieldsContainer(); _context = context; _hostedType = type; #if (PORTABLE || NETCORE) _instanceCtor = _hostedType.GetTypeInfo().DeclaredConstructors.FirstOrDefault(x => x.GetParameters().Length == 0 && !x.IsStatic); #else _instanceCtor = _hostedType.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy, null, Type.EmptyTypes, null); #endif } private void fillMembers() { lock (this) { if (_members != null) return; var tempMembers = new StringMap<IList<MemberInfo>>(); string prewName = null; IList<MemberInfo> temp = null; bool instanceAttribute = false; #if (PORTABLE || NETCORE) var members = _hostedType.GetTypeInfo().DeclaredMembers .Union(_hostedType.GetRuntimeMethods()) .Union(_hostedType.GetRuntimeProperties()) .Union(_hostedType.GetRuntimeFields()) .Union(_hostedType.GetRuntimeEvents()).ToArray(); #else var members = _hostedType.GetMembers(); #endif for (int i = 0; i < members.Length; i++) { var member = members[i]; if (member.IsDefined(typeof(HiddenAttribute), false)) continue; instanceAttribute = member.IsDefined(typeof(InstanceMemberAttribute), false); if (!IsInstancePrototype && instanceAttribute) continue; var property = member as PropertyInfo; if (property != null) { if ((property.GetSetMethod(true) ?? property.GetGetMethod(true)).IsStatic != !(IsInstancePrototype ^ instanceAttribute)) continue; if ((property.GetSetMethod(true) == null || !property.GetSetMethod(true).IsPublic) && (property.GetGetMethod(true) == null || !property.GetGetMethod(true).IsPublic)) continue; var parentProperty = property; while (parentProperty != null && parentProperty.DeclaringType != typeof(object) && ((property.GetGetMethod() ?? property.GetSetMethod()).Attributes & MethodAttributes.NewSlot) == 0) { property = parentProperty; #if (PORTABLE || NETCORE) parentProperty = property.DeclaringType.GetTypeInfo().BaseType?.GetRuntimeProperty(property.Name); #else parentProperty = property.DeclaringType.GetTypeInfo().BaseType?.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance); #endif } member = property; } if (member is EventInfo && (!(member as EventInfo).GetAddMethod(true).IsPublic || (member as EventInfo).GetAddMethod(true).IsStatic != !IsInstancePrototype)) continue; if (member is FieldInfo && (!(member as FieldInfo).IsPublic || (member as FieldInfo).IsStatic != !IsInstancePrototype)) continue; #if (PORTABLE || NETCORE) if ((members[i] is TypeInfo) && !(members[i] as TypeInfo).IsPublic) continue; #else if (member is Type && !(member as Type).IsPublic && !(member as Type).IsNestedPublic) continue; #endif var method = member as MethodBase; if (method != null) { if (method.IsStatic != !(IsInstancePrototype ^ instanceAttribute)) continue; if (!method.IsPublic) continue; if (method.DeclaringType == typeof(object) && member.Name == "GetType") continue; if (method is ConstructorInfo) continue; if (method.IsVirtual && (method.Attributes & MethodAttributes.NewSlot) == 0) { var parameterTypes = method.GetParameters().Select(x => x.ParameterType).ToArray(); var parentMethod = method; while (parentMethod != null && parentMethod.DeclaringType != typeof(object) && (method.Attributes & MethodAttributes.NewSlot) == 0) { method = parentMethod; #if (PORTABLE || NETCORE) parentMethod = method.DeclaringType.GetTypeInfo().BaseType?.GetMethod(method.Name, parameterTypes); #else parentMethod = method.DeclaringType.BaseType?.GetMethod(method.Name, BindingFlags.Public | BindingFlags.Instance, null, parameterTypes, null); #endif } } member = method; } var membername = member.Name; if (member.IsDefined(typeof(JavaScriptNameAttribute), false)) { var nameOverrideAttribute = member.GetCustomAttributes(typeof(JavaScriptNameAttribute), false).ToArray(); membername = (nameOverrideAttribute[0] as JavaScriptNameAttribute).Name; } else { membername = membername[0] == '.' ? membername : membername.Contains(".") ? membername.Substring(membername.LastIndexOf('.') + 1) : membername; #if (PORTABLE || NETCORE) if (members[i] is TypeInfo && membername.Contains("`")) #else if (member is Type && membername.Contains('`')) #endif { membername = membername.Substring(0, membername.IndexOf('`')); } } if (prewName != membername) { if (temp != null && temp.Count > 1) { var type = temp[0].DeclaringType; for (var j = 1; j < temp.Count; j++) { if (type != temp[j].DeclaringType && type.IsAssignableFrom(temp[j].DeclaringType)) type = temp[j].DeclaringType; } int offset = 0; for (var j = 1; j < temp.Count; j++) { if (!type.IsAssignableFrom(temp[j].DeclaringType)) { temp.RemoveAt(j--); tempMembers.Remove(prewName + "$" + (++offset + j)); } } if (temp.Count == 1) tempMembers.Remove(prewName + "$0"); } if (!tempMembers.TryGetValue(membername, out temp)) tempMembers[membername] = temp = new List<MemberInfo>(); prewName = membername; } if (membername.StartsWith("@@")) { if (_symbols == null) _symbols = new Dictionary<Symbol, JSValue>(); _symbols.Add(Symbol.@for(membername.Substring(2)), proxyMember(false, new[] { member })); } else { if (temp.Count == 1) tempMembers.Add(membername + "$0", new[] { temp[0] }); temp.Add(member); if (temp.Count != 1) tempMembers.Add(membername + "$" + (temp.Count - 1), new[] { member }); } } _members = tempMembers; if (IsInstancePrototype) { if (typeof(IIterable).IsAssignableFrom(_hostedType)) { IList<MemberInfo> iterator = null; if (_members.TryGetValue("iterator", out iterator)) { if (_symbols == null) _symbols = new Dictionary<Symbol, JSValue>(); _symbols.Add(Symbol.iterator, proxyMember(false, iterator)); _members.Remove("iterator"); } } #if NET40 var toStringTag = _hostedType.GetCustomAttribute<ToStringTagAttribute>(); #else var toStringTag = _hostedType.GetTypeInfo().GetCustomAttribute<ToStringTagAttribute>(); #endif if (toStringTag != null) { if (_symbols == null) _symbols = new Dictionary<Symbol, JSValue>(); _symbols.Add(Symbol.toStringTag, toStringTag.Tag); } } if (_indexersSupported) { IList<MemberInfo> getter = null; IList<MemberInfo> setter = null; _members.TryGetValue("get_Item", out getter); _members.TryGetValue("set_Item", out setter); if (getter != null || setter != null) { _indexerProperty = new PropertyPair(); if (getter != null) { _indexerProperty.getter = (Function)proxyMember(false, getter); _fields["get_Item"] = _indexerProperty.getter; } if (setter != null) { _indexerProperty.setter = (Function)proxyMember(false, setter); _fields["set_Item"] = _indexerProperty.setter; } } else { _indexersSupported = false; } } } } internal protected override JSValue GetProperty(JSValue key, bool forWrite, PropertyScope memberScope) { if (_members == null) fillMembers(); if (memberScope == PropertyScope.Super || key._valueType == JSValueType.Symbol) return base.GetProperty(key, forWrite, memberScope); forWrite &= (_attributes & JSValueAttributesInternal.Immutable) == 0; string name = key.ToString(); JSValue r = null; if (_fields.TryGetValue(name, out r)) { if (!r.Exists && !forWrite) { var t = base.GetProperty(key, false, memberScope); if (t.Exists) { r.Assign(t); r._valueType = t._valueType; } } if (forWrite && r.NeedClone) _fields[name] = r = r.CloneImpl(false); return r; } IList<MemberInfo> m = null; _members.TryGetValue(name, out m); if (m == null || m.Count == 0) { JSValue property; var protoInstanceAsJs = PrototypeInstance as JSValue; if (protoInstanceAsJs != null) property = protoInstanceAsJs.GetProperty(key, forWrite && !_indexersSupported, memberScope); else property = base.GetProperty(key, forWrite && !_indexersSupported, memberScope); if (!_indexersSupported) return property; if (property.Exists) { if (forWrite) { if ((property._attributes & (JSValueAttributesInternal.SystemObject & JSValueAttributesInternal.ReadOnly)) == JSValueAttributesInternal.SystemObject) { if (protoInstanceAsJs != null) property = protoInstanceAsJs.GetProperty(key, true, memberScope); else property = base.GetProperty(key, true, memberScope); } } return property; } if (forWrite) { return new JSValue { _valueType = JSValueType.Property, _oValue = new PropertyPair(null, _indexerProperty.setter.bind(new Arguments { null, key })) }; } else { return new JSValue { _valueType = JSValueType.Property, _oValue = new PropertyPair(_indexerProperty.getter.bind(new Arguments { null, key }), null) }; } } var result = proxyMember(forWrite, m); _fields[name] = result; return result; } internal JSValue proxyMember(bool forWrite, IList<MemberInfo> m) { JSValue r = null; if (m.Count > 1) { for (int i = 0; i < m.Count; i++) if (!(m[i] is MethodBase)) ExceptionHelper.Throw(_context.ProxyValue(new TypeError("Incompatible fields types."))); var cache = new MethodProxy[m.Count]; for (int i = 0; i < m.Count; i++) cache[i] = new MethodProxy(_context, m[i] as MethodBase); r = new MethodGroup(cache); } else { #if PORTABLE || NETCORE switch (m[0].GetMemberType()) #else switch (m[0].MemberType) #endif { case MemberTypes.Method: { var method = (MethodInfo)m[0]; r = new MethodProxy(_context, method); r._attributes &= ~(JSValueAttributesInternal.ReadOnly | JSValueAttributesInternal.DoNotDelete | JSValueAttributesInternal.NonConfigurable | JSValueAttributesInternal.DoNotEnumerate); break; } case MemberTypes.Field: { var field = (m[0] as FieldInfo); if ((field.Attributes & (FieldAttributes.Literal | FieldAttributes.InitOnly)) != 0 && (field.Attributes & FieldAttributes.Static) != 0) { r = _context.ProxyValue(field.GetValue(null)); r._attributes |= JSValueAttributesInternal.ReadOnly; } else { r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( new ExternalFunction((thisBind, a) => _context.ProxyValue(field.GetValue(field.IsStatic ? null : thisBind.Value))), !m[0].IsDefined(typeof(ReadOnlyAttribute), false) ? new ExternalFunction((thisBind, a) => { field.SetValue(field.IsStatic ? null : thisBind.Value, a[0].Value); return null; }) : null ) }; r._attributes = JSValueAttributesInternal.Immutable | JSValueAttributesInternal.Field; if ((r._oValue as PropertyPair).setter == null) r._attributes |= JSValueAttributesInternal.ReadOnly; } break; } case MemberTypes.Property: { var pinfo = (PropertyInfo)m[0]; r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( #if (PORTABLE || NETCORE) pinfo.CanRead && pinfo.GetMethod != null ? new MethodProxy(_context, pinfo.GetMethod) : null, pinfo.CanWrite && pinfo.SetMethod != null && !pinfo.IsDefined(typeof(ReadOnlyAttribute), false) ? new MethodProxy(_context, pinfo.SetMethod) : null #else pinfo.CanRead && pinfo.GetGetMethod(false) != null ? new MethodProxy(_context, pinfo.GetGetMethod(false)) : null, pinfo.CanWrite && pinfo.GetSetMethod(false) != null && !pinfo.IsDefined(typeof(ReadOnlyAttribute), false) ? new MethodProxy(_context, pinfo.GetSetMethod(false)) : null #endif ) }; r._attributes = JSValueAttributesInternal.Immutable; if ((r._oValue as PropertyPair).setter == null) r._attributes |= JSValueAttributesInternal.ReadOnly; if (pinfo.IsDefined(typeof(FieldAttribute), false)) r._attributes |= JSValueAttributesInternal.Field; break; } case MemberTypes.Event: { var pinfo = (EventInfo)m[0]; r = new JSValue() { _valueType = JSValueType.Property, _oValue = new PropertyPair ( null, #if (PORTABLE || NETCORE) new MethodProxy(_context, pinfo.AddMethod) #else new MethodProxy(_context, pinfo.GetAddMethod()) #endif ) }; break; } case MemberTypes.TypeInfo: #if (PORTABLE || NETCORE) { r = GetConstructor((m[0] as TypeInfo).AsType()); break; } #else case MemberTypes.NestedType: { r = _context.GetConstructor((Type)m[0]); break; } default: throw new NotImplementedException("Convertion from " + m[0].MemberType + " not implemented"); #endif } } if (m[0].IsDefined(typeof(DoNotEnumerateAttribute), false)) r._attributes |= JSValueAttributesInternal.DoNotEnumerate; if (forWrite && r.NeedClone) r = r.CloneImpl(false); for (var i = m.Count; i-- > 0;) { if (!m[i].IsDefined(typeof(DoNotEnumerateAttribute), false)) r._attributes &= ~JSValueAttributesInternal.DoNotEnumerate; if (m[i].IsDefined(typeof(ReadOnlyAttribute), false)) r._attributes |= JSValueAttributesInternal.ReadOnly; if (m[i].IsDefined(typeof(NotConfigurable), false)) r._attributes |= JSValueAttributesInternal.NonConfigurable; if (m[i].IsDefined(typeof(DoNotDeleteAttribute), false)) r._attributes |= JSValueAttributesInternal.DoNotDelete; } return r; } protected internal override bool DeleteProperty(JSValue name) { if (_members == null) fillMembers(); string stringName = null; JSValue field = null; if (_fields != null && _fields.TryGetValue(stringName = name.ToString(), out field) && (!field.Exists || (field._attributes & JSValueAttributesInternal.DoNotDelete) == 0)) { if ((field._attributes & JSValueAttributesInternal.SystemObject) == 0) field._valueType = JSValueType.NotExistsInObject; return _fields.Remove(stringName) | _members.Remove(stringName); // it's not mistake } else { IList<MemberInfo> m = null; if (_members.TryGetValue(stringName.ToString(), out m)) { for (var i = m.Count; i-- > 0;) { if (m[i].IsDefined(typeof(DoNotDeleteAttribute), false)) return false; } } if (!_members.Remove(stringName) && PrototypeInstance != null) return _prototypeInstance.DeleteProperty(stringName); } return true; } public override JSValue propertyIsEnumerable(Arguments args) { if (args == null) throw new ArgumentNullException("args"); var name = args[0].ToString(); JSValue temp; if (_fields != null && _fields.TryGetValue(name, out temp)) return temp.Exists && (temp._attributes & JSValueAttributesInternal.DoNotEnumerate) == 0; IList<MemberInfo> m = null; if (_members.TryGetValue(name, out m)) { for (var i = m.Count; i-- > 0;) if (!m[i].IsDefined(typeof(DoNotEnumerateAttribute), false)) return true; return false; } return false; } protected internal override IEnumerator<KeyValuePair<string, JSValue>> GetEnumerator(bool hideNonEnumerable, EnumerationMode enumerationMode) { if (_members == null) fillMembers(); if (PrototypeInstance != null) { var @enum = PrototypeInstance.GetEnumerator(hideNonEnumerable, enumerationMode); while (@enum.MoveNext()) yield return @enum.Current; } else { foreach (var f in _fields) { if (!hideNonEnumerable || (f.Value._attributes & JSValueAttributesInternal.DoNotEnumerate) == 0) yield return f; } } foreach (var item in _members) { if (_fields.ContainsKey(item.Key)) continue; for (var i = item.Value.Count; i-- > 0;) { if (item.Value[i].IsDefined(typeof(HiddenAttribute), false)) continue; if (!hideNonEnumerable || !item.Value[i].IsDefined(typeof(DoNotEnumerateAttribute), false)) { switch (enumerationMode) { case EnumerationMode.KeysOnly: { yield return new KeyValuePair<string, JSValue>(item.Key, null); break; } case EnumerationMode.RequireValues: case EnumerationMode.RequireValuesForWrite: { yield return new KeyValuePair<string, JSValue>( item.Key, _fields[item.Key] = proxyMember(enumerationMode == EnumerationMode.RequireValuesForWrite, item.Value)); break; } } break; } } } } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** // **************************************************************** // Generated by the NUnit Syntax Generator // // Command Line: GenSyntax.exe SyntaxElements.txt // // DO NOT MODIFY THIS FILE DIRECTLY // **************************************************************** using System; using System.Collections; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Helper class with properties and methods that supply /// a number of constraints used in Asserts. /// </summary> public class Is { #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public static ConstraintExpression Not { get { return new ConstraintExpression().Not; } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public static ConstraintExpression All { get { return new ConstraintExpression().All; } } #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public static NullConstraint Null { get { return new NullConstraint(); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public static TrueConstraint True { get { return new TrueConstraint(); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public static FalseConstraint False { get { return new FalseConstraint(); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public static NaNConstraint NaN { get { return new NaNConstraint(); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public static EmptyConstraint Empty { get { return new EmptyConstraint(); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public static UniqueItemsConstraint Unique { get { return new UniqueItemsConstraint(); } } #endregion #region BinarySerializable #if !NETCF /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public static BinarySerializableConstraint BinarySerializable { get { return new BinarySerializableConstraint(); } } #endif #endregion #region XmlSerializable #if !NETCF_1_0 /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public static XmlSerializableConstraint XmlSerializable { get { return new XmlSerializableConstraint(); } } #endif #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public static EqualConstraint EqualTo(object expected) { return new EqualConstraint(expected); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public static SameAsConstraint SameAs(object expected) { return new SameAsConstraint(expected); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the suppled argument /// </summary> public static GreaterThanConstraint GreaterThan(object expected) { return new GreaterThanConstraint(expected); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return new GreaterThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public static GreaterThanOrEqualConstraint AtLeast(object expected) { return new GreaterThanOrEqualConstraint(expected); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the suppled argument /// </summary> public static LessThanConstraint LessThan(object expected) { return new LessThanConstraint(expected); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return new LessThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public static LessThanOrEqualConstraint AtMost(object expected) { return new LessThanOrEqualConstraint(expected); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public static ExactTypeConstraint TypeOf(Type expectedType) { return new ExactTypeConstraint(expectedType); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public static ExactTypeConstraint TypeOf<T>() { return new ExactTypeConstraint(typeof(T)); } #endif #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public static InstanceOfTypeConstraint InstanceOf(Type expectedType) { return new InstanceOfTypeConstraint(expectedType); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public static InstanceOfTypeConstraint InstanceOf<T>() { return new InstanceOfTypeConstraint(typeof(T)); } #endif /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf(expectedType)")] public static InstanceOfTypeConstraint InstanceOfType(Type expectedType) { return new InstanceOfTypeConstraint(expectedType); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf<T>()")] public static InstanceOfTypeConstraint InstanceOfType<T>() { return new InstanceOfTypeConstraint(typeof(T)); } #endif #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableFromConstraint AssignableFrom(Type expectedType) { return new AssignableFromConstraint(expectedType); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableFromConstraint AssignableFrom<T>() { return new AssignableFromConstraint(typeof(T)); } #endif #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableToConstraint AssignableTo(Type expectedType) { return new AssignableToConstraint(expectedType); } #if NET_2_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableToConstraint AssignableTo<T>() { return new AssignableToConstraint(typeof(T)); } #endif #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return new CollectionEquivalentConstraint(expected); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public static CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return new CollectionSubsetConstraint(expected); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public static CollectionOrderedConstraint Ordered { get { return new CollectionOrderedConstraint(); } } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public static SubstringConstraint StringContaining(string expected) { return new SubstringConstraint(expected); } #endregion #region StringStarting /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public static StartsWithConstraint StringStarting(string expected) { return new StartsWithConstraint(expected); } #endregion #region StringEnding /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public static EndsWithConstraint StringEnding(string expected) { return new EndsWithConstraint(expected); } #endregion #region StringMatching #if !NETCF /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public static RegexConstraint StringMatching(string pattern) { return new RegexConstraint(pattern); } #endif #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public static SamePathConstraint SamePath(string expected) { return new SamePathConstraint(expected); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public static SamePathOrUnderConstraint SamePathOrUnder(string expected) { return new SamePathOrUnderConstraint(expected); } #endregion #region InRange /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public static RangeConstraint InRange(IComparable from, IComparable to) { return new RangeConstraint(from, to); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Collections; using System.DirectoryServices.Interop; using System.Globalization; namespace System.DirectoryServices { /// <devdoc> /// Contains the properties on a <see cref='System.DirectoryServices.DirectoryEntry'/>. /// </devdoc> public class PropertyCollection : IDictionary { private readonly DirectoryEntry _entry; internal readonly Hashtable valueTable = null; internal PropertyCollection(DirectoryEntry entry) { _entry = entry; Hashtable tempTable = new Hashtable(); valueTable = Hashtable.Synchronized(tempTable); } /// <devdoc> /// Gets the property with the given name. /// </devdoc> public PropertyValueCollection this[string propertyName] { get { if (propertyName == null) throw new ArgumentNullException("propertyName"); string name = propertyName.ToLower(CultureInfo.InvariantCulture); if (valueTable.Contains(name)) return (PropertyValueCollection)valueTable[name]; else { PropertyValueCollection value = new PropertyValueCollection(_entry, propertyName); valueTable.Add(name, value); return value; } } } /// <devdoc> /// Gets the number of properties available on this entry. /// </devdoc> public int Count { get { if (!(_entry.AdsObject is UnsafeNativeMethods.IAdsPropertyList)) throw new NotSupportedException(SR.DSCannotCount); _entry.FillCache(""); UnsafeNativeMethods.IAdsPropertyList propList = (UnsafeNativeMethods.IAdsPropertyList)_entry.AdsObject; return propList.PropertyCount; } } /// </devdoc> public ICollection PropertyNames => new KeysCollection(this); public ICollection Values => new ValuesCollection(this); public bool Contains(string propertyName) { object var; int unmanagedResult = _entry.AdsObject.GetEx(propertyName, out var); if (unmanagedResult != 0) { // property not found (IIS provider returns 0x80005006, other provides return 0x8000500D). if ((unmanagedResult == unchecked((int)0x8000500D)) || (unmanagedResult == unchecked((int)0x80005006))) { return false; } else { throw COMExceptionHelper.CreateFormattedComException(unmanagedResult); } } return true; } /// <devdoc> /// Copies the elements of this instance into an <see cref='System.Array'/>, starting at a particular index into the array. /// </devdoc> public void CopyTo(PropertyValueCollection[] array, int index) { ((ICollection)this).CopyTo((Array)array, index); } /// <devdoc> /// Returns an enumerator, which can be used to iterate through the collection. /// </devdoc> public IDictionaryEnumerator GetEnumerator() { if (!(_entry.AdsObject is UnsafeNativeMethods.IAdsPropertyList)) throw new NotSupportedException(SR.DSCannotEmunerate); // Once an object has been used for an enumerator once, it can't be used again, because it only // maintains a single cursor. Re-bind to the ADSI object to get a new instance. // That's why we must clone entry here. It will be automatically disposed inside Enumerator. DirectoryEntry entryToUse = _entry.CloneBrowsable(); entryToUse.FillCache(""); UnsafeNativeMethods.IAdsPropertyList propList = (UnsafeNativeMethods.IAdsPropertyList)entryToUse.AdsObject; entryToUse.propertiesAlreadyEnumerated = true; return new PropertyEnumerator(_entry, entryToUse); } object IDictionary.this[object key] { get => this[(string)key]; set => throw new NotSupportedException(SR.DSPropertySetSupported); } bool IDictionary.IsFixedSize => true; bool IDictionary.IsReadOnly => true; ICollection IDictionary.Keys => new KeysCollection(this); void IDictionary.Add(object key, object value) { throw new NotSupportedException(SR.DSAddNotSupported); } void IDictionary.Clear() { throw new NotSupportedException(SR.DSClearNotSupported); } bool IDictionary.Contains(object value) => Contains((string)value); void IDictionary.Remove(object key) { throw new NotSupportedException(SR.DSRemoveNotSupported); } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; void ICollection.CopyTo(Array array, Int32 index) { if (array == null) throw new ArgumentNullException("array"); if (array.Rank != 1) throw new ArgumentException(SR.OnlyAllowSingleDimension, "array"); if (index < 0) throw new ArgumentOutOfRangeException(SR.LessThanZero, "index"); if (((index + Count) > array.Length) || ((index + Count) < index)) throw new ArgumentException(SR.DestinationArrayNotLargeEnough); foreach (PropertyValueCollection value in this) { array.SetValue(value, index); index++; } } private class PropertyEnumerator : IDictionaryEnumerator, IDisposable { private DirectoryEntry _entry; // clone (to be disposed) private DirectoryEntry _parentEntry; // original entry to pass to PropertyValueCollection private string _currentPropName = null; public PropertyEnumerator(DirectoryEntry parent, DirectoryEntry clone) { _entry = clone; _parentEntry = parent; } ~PropertyEnumerator() => Dispose(true); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { _entry.Dispose(); } } public object Current => Entry.Value; public DictionaryEntry Entry { get { if (_currentPropName == null) throw new InvalidOperationException(SR.DSNoCurrentProperty); return new DictionaryEntry(_currentPropName, new PropertyValueCollection(_parentEntry, _currentPropName)); } } public object Key => Entry.Key; public object Value => Entry.Value; public bool MoveNext() { object prop; int hr = 0; try { hr = ((UnsafeNativeMethods.IAdsPropertyList)_entry.AdsObject).Next(out prop); } catch (COMException e) { hr = e.ErrorCode; prop = null; } if (hr == 0) { if (prop != null) _currentPropName = ((UnsafeNativeMethods.IAdsPropertyEntry)prop).Name; else _currentPropName = null; return true; } else { _currentPropName = null; return false; } } public void Reset() { ((UnsafeNativeMethods.IAdsPropertyList)_entry.AdsObject).Reset(); _currentPropName = null; } } private class ValuesCollection : ICollection { protected PropertyCollection props; public ValuesCollection(PropertyCollection props) { this.props = props; } public int Count => props.Count; public bool IsReadOnly => true; public bool IsSynchronized => false; public object SyncRoot => ((ICollection)props).SyncRoot; public void CopyTo(Array array, int index) { foreach (object value in this) array.SetValue(value, index++); } public virtual IEnumerator GetEnumerator() => new ValuesEnumerator(props); } private class KeysCollection : ValuesCollection { public KeysCollection(PropertyCollection props) : base(props) { } public override IEnumerator GetEnumerator() { props._entry.FillCache(""); return new KeysEnumerator(props); } } private class ValuesEnumerator : IEnumerator { private int _currentIndex = -1; protected PropertyCollection propCollection; public ValuesEnumerator(PropertyCollection propCollection) { this.propCollection = propCollection; } protected int CurrentIndex { get { if (_currentIndex == -1) throw new InvalidOperationException(SR.DSNoCurrentValue); return _currentIndex; } } public virtual object Current { get { UnsafeNativeMethods.IAdsPropertyList propList = (UnsafeNativeMethods.IAdsPropertyList)propCollection._entry.AdsObject; return propCollection[((UnsafeNativeMethods.IAdsPropertyEntry)propList.Item(CurrentIndex)).Name]; } } public bool MoveNext() { _currentIndex++; if (_currentIndex >= propCollection.Count) { _currentIndex = -1; return false; } else return true; } public void Reset() => _currentIndex = -1; } private class KeysEnumerator : ValuesEnumerator { public KeysEnumerator(PropertyCollection collection) : base(collection) { } public override object Current { get { UnsafeNativeMethods.IAdsPropertyList propList = (UnsafeNativeMethods.IAdsPropertyList)propCollection._entry.AdsObject; return ((UnsafeNativeMethods.IAdsPropertyEntry)propList.Item(CurrentIndex)).Name; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { public partial class Process : IDisposable { /// <summary> /// Creates an array of <see cref="Process"/> components that are associated with process resources on a /// remote computer. These process resources share the specified process name. /// </summary> public static Process[] GetProcessesByName(string processName, string machineName) { if (processName == null) { processName = string.Empty; } Process[] procs = GetProcesses(machineName); var list = new List<Process>(); for (int i = 0; i < procs.Length; i++) { if (string.Equals(processName, procs[i].ProcessName, StringComparison.OrdinalIgnoreCase)) { list.Add(procs[i]); } else { procs[i].Dispose(); } } return list.ToArray(); } [CLSCompliant(false)] public static Process Start(string fileName, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } [CLSCompliant(false)] public static Process Start(string fileName, string arguments, string userName, SecureString password, string domain) { ProcessStartInfo startInfo = new ProcessStartInfo(fileName, arguments); startInfo.UserName = userName; startInfo.Password = password; startInfo.Domain = domain; startInfo.UseShellExecute = false; return Start(startInfo); } /// <summary> /// Puts a Process component in state to interact with operating system processes that run in a /// special mode by enabling the native property SeDebugPrivilege on the current thread. /// </summary> public static void EnterDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, (int)Interop.Advapi32.SEPrivileges.SE_PRIVILEGE_ENABLED); } /// <summary> /// Takes a Process component out of the state that lets it interact with operating system processes /// that run in a special mode. /// </summary> public static void LeaveDebugMode() { SetPrivilege(Interop.Advapi32.SeDebugPrivilege, 0); } /// <summary>Stops the associated process immediately.</summary> public void Kill() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_TERMINATE)) { if (!Interop.Kernel32.TerminateProcess(handle, -1)) throw new Win32Exception(); } } /// <summary>Discards any information about the associated process.</summary> private void RefreshCore() { _signaled = false; } /// <summary>Additional logic invoked when the Process is closed.</summary> private void CloseCore() { // Nop } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for the associated process to exit. /// </summary> private bool WaitForExitCore(int milliseconds) { SafeProcessHandle handle = null; try { handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false); if (handle.IsInvalid) return true; using (ProcessWaitHandle processWaitHandle = new ProcessWaitHandle(handle)) { return _signaled = processWaitHandle.WaitOne(milliseconds); } } finally { // If we have a hard timeout, we cannot wait for the streams if (_output != null && milliseconds == Timeout.Infinite) _output.WaitUtilEOF(); if (_error != null && milliseconds == Timeout.Infinite) _error.WaitUtilEOF(); handle?.Dispose(); } } /// <summary>Gets the main module for the associated process.</summary> public ProcessModule MainModule { get { // We only return null if we couldn't find a main module. This could be because // the process hasn't finished loading the main module (most likely). // On NT, the first module is the main module. EnsureState(State.HaveId | State.IsLocal); return NtProcessManager.GetFirstModule(_processId); } } /// <summary>Checks whether the process has exited and updates state accordingly.</summary> private void UpdateHasExited() { using (SafeProcessHandle handle = GetProcessHandle( Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION | Interop.Advapi32.ProcessOptions.SYNCHRONIZE, false)) { if (handle.IsInvalid) { _exited = true; } else { int localExitCode; // Although this is the wrong way to check whether the process has exited, // it was historically the way we checked for it, and a lot of code then took a dependency on // the fact that this would always be set before the pipes were closed, so they would read // the exit code out after calling ReadToEnd() or standard output or standard error. In order // to allow 259 to function as a valid exit code and to break as few people as possible that // took the ReadToEnd dependency, we check for an exit code before doing the more correct // check to see if we have been signaled. if (Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode) && localExitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { _exitCode = localExitCode; _exited = true; } else { // The best check for exit is that the kernel process object handle is invalid, // or that it is valid and signaled. Checking if the exit code != STILL_ACTIVE // does not guarantee the process is closed, // since some process could return an actual STILL_ACTIVE exit code (259). if (!_signaled) // if we just came from WaitForExit, don't repeat { using (var wh = new ProcessWaitHandle(handle)) { _signaled = wh.WaitOne(0); } } if (_signaled) { if (!Interop.Kernel32.GetExitCodeProcess(handle, out localExitCode)) throw new Win32Exception(); _exitCode = localExitCode; _exited = true; } } } } } /// <summary>Gets the time that the associated process exited.</summary> private DateTime ExitTimeCore { get { return GetProcessTimes().ExitTime; } } /// <summary>Gets the amount of time the process has spent running code inside the operating system core.</summary> public TimeSpan PrivilegedProcessorTime { get { return GetProcessTimes().PrivilegedProcessorTime; } } /// <summary>Gets the time the associated process was started.</summary> internal DateTime StartTimeCore { get { return GetProcessTimes().StartTime; } } /// <summary> /// Gets the amount of time the associated process has spent utilizing the CPU. /// It is the sum of the <see cref='System.Diagnostics.Process.UserProcessorTime'/> and /// <see cref='System.Diagnostics.Process.PrivilegedProcessorTime'/>. /// </summary> public TimeSpan TotalProcessorTime { get { return GetProcessTimes().TotalProcessorTime; } } /// <summary> /// Gets the amount of time the associated process has spent running code /// inside the application portion of the process (not the operating system core). /// </summary> public TimeSpan UserProcessorTime { get { return GetProcessTimes().UserProcessorTime; } } /// <summary> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </summary> private bool PriorityBoostEnabledCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { bool disabled; if (!Interop.Kernel32.GetProcessPriorityBoost(handle, out disabled)) { throw new Win32Exception(); } return !disabled; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessPriorityBoost(handle, !value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets the overall priority category for the associated process. /// </summary> private ProcessPriorityClass PriorityClassCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int value = Interop.Kernel32.GetPriorityClass(handle); if (value == 0) { throw new Win32Exception(); } return (ProcessPriorityClass)value; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetPriorityClass(handle, (int)value)) throw new Win32Exception(); } } } /// <summary> /// Gets or sets which processors the threads in this process can be scheduled to run on. /// </summary> private IntPtr ProcessorAffinityCore { get { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { IntPtr processAffinity, systemAffinity; if (!Interop.Kernel32.GetProcessAffinityMask(handle, out processAffinity, out systemAffinity)) throw new Win32Exception(); return processAffinity; } } set { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_SET_INFORMATION)) { if (!Interop.Kernel32.SetProcessAffinityMask(handle, value)) throw new Win32Exception(); } } } /// <summary>Gets the ID of the current process.</summary> private static int GetCurrentProcessId() { return unchecked((int)Interop.Kernel32.GetCurrentProcessId()); } /// <summary> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle GetProcessHandle() { return GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_ALL_ACCESS); } /// <summary>Get the minimum and maximum working set limits.</summary> private void GetWorkingSetLimits(out IntPtr minWorkingSet, out IntPtr maxWorkingSet) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION)) { int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out minWorkingSet, out maxWorkingSet, out ignoredFlags)) throw new Win32Exception(); } } /// <summary>Sets one or both of the minimum and maximum working set limits.</summary> /// <param name="newMin">The new minimum working set limit, or null not to change it.</param> /// <param name="newMax">The new maximum working set limit, or null not to change it.</param> /// <param name="resultingMin">The resulting minimum working set limit after any changes applied.</param> /// <param name="resultingMax">The resulting maximum working set limit after any changes applied.</param> private void SetWorkingSetLimitsCore(IntPtr? newMin, IntPtr? newMax, out IntPtr resultingMin, out IntPtr resultingMax) { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_SET_QUOTA)) { IntPtr min, max; int ignoredFlags; if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } if (newMin.HasValue) { min = newMin.Value; } if (newMax.HasValue) { max = newMax.Value; } if ((long)min > (long)max) { if (newMin != null) { throw new ArgumentException(SR.BadMinWorkset); } else { throw new ArgumentException(SR.BadMaxWorkset); } } // We use SetProcessWorkingSetSizeEx which gives an option to follow // the max and min value even in low-memory and abundant-memory situations. // However, we do not use these flags to emulate the existing behavior if (!Interop.Kernel32.SetProcessWorkingSetSizeEx(handle, min, max, 0)) { throw new Win32Exception(); } // The value may be rounded/changed by the OS, so go get it if (!Interop.Kernel32.GetProcessWorkingSetSizeEx(handle, out min, out max, out ignoredFlags)) { throw new Win32Exception(); } resultingMin = min; resultingMax = max; } } private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); /// <summary>Starts the process using the supplied start info.</summary> /// <param name="startInfo">The start info with which to start the process.</param> private bool StartWithCreateProcess(ProcessStartInfo startInfo) { // See knowledge base article Q190351 for an explanation of the following code. Noteworthy tricky points: // * The handles are duplicated as non-inheritable before they are passed to CreateProcess so // that the child process can not close them // * CreateProcess allows you to redirect all or none of the standard IO handles, so we use // GetStdHandle for the handles that are not being redirected StringBuilder commandLine = BuildCommandLine(startInfo.FileName, startInfo.Arguments); Interop.Kernel32.STARTUPINFO startupInfo = new Interop.Kernel32.STARTUPINFO(); Interop.Kernel32.PROCESS_INFORMATION processInfo = new Interop.Kernel32.PROCESS_INFORMATION(); Interop.Kernel32.SECURITY_ATTRIBUTES unused_SecAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); SafeProcessHandle procSH = new SafeProcessHandle(); SafeThreadHandle threadSH = new SafeThreadHandle(); bool retVal; int errorCode = 0; // handles used in parent process SafeFileHandle standardInputWritePipeHandle = null; SafeFileHandle standardOutputReadPipeHandle = null; SafeFileHandle standardErrorReadPipeHandle = null; GCHandle environmentHandle = new GCHandle(); lock (s_createProcessLock) { try { // set up the streams if (startInfo.RedirectStandardInput || startInfo.RedirectStandardOutput || startInfo.RedirectStandardError) { if (startInfo.RedirectStandardInput) { CreatePipe(out standardInputWritePipeHandle, out startupInfo.hStdInput, true); } else { startupInfo.hStdInput = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_INPUT_HANDLE), false); } if (startInfo.RedirectStandardOutput) { CreatePipe(out standardOutputReadPipeHandle, out startupInfo.hStdOutput, false); } else { startupInfo.hStdOutput = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_OUTPUT_HANDLE), false); } if (startInfo.RedirectStandardError) { CreatePipe(out standardErrorReadPipeHandle, out startupInfo.hStdError, false); } else { startupInfo.hStdError = new SafeFileHandle(Interop.Kernel32.GetStdHandle(Interop.Kernel32.HandleTypes.STD_ERROR_HANDLE), false); } startupInfo.dwFlags = Interop.Advapi32.StartupInfoOptions.STARTF_USESTDHANDLES; } // set up the creation flags parameter int creationFlags = 0; if (startInfo.CreateNoWindow) creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_NO_WINDOW; // set up the environment block parameter IntPtr environmentPtr = (IntPtr)0; if (startInfo._environmentVariables != null) { creationFlags |= Interop.Advapi32.StartupInfoOptions.CREATE_UNICODE_ENVIRONMENT; byte[] environmentBytes = EnvironmentVariablesToByteArray(startInfo._environmentVariables); environmentHandle = GCHandle.Alloc(environmentBytes, GCHandleType.Pinned); environmentPtr = environmentHandle.AddrOfPinnedObject(); } string workingDirectory = startInfo.WorkingDirectory; if (workingDirectory == string.Empty) workingDirectory = Directory.GetCurrentDirectory(); if (startInfo.UserName.Length != 0) { if (startInfo.Password != null && startInfo.PasswordInClearText != null) { throw new ArgumentException(SR.CantSetDuplicatePassword); } Interop.Advapi32.LogonFlags logonFlags = (Interop.Advapi32.LogonFlags)0; if (startInfo.LoadUserProfile) { logonFlags = Interop.Advapi32.LogonFlags.LOGON_WITH_PROFILE; } if (startInfo.Password != null) { IntPtr passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(startInfo.Password); try { retVal = Interop.Advapi32.CreateProcessWithLogonW( startInfo.UserName, startInfo.Domain, passwordPtr, logonFlags, null, // we don't need this since all the info is in commandLine commandLine, creationFlags, environmentPtr, workingDirectory, startupInfo, // pointer to STARTUPINFO processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); } finally { Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } else { unsafe { fixed (char* passwordPtr = startInfo.PasswordInClearText ?? string.Empty) { retVal = Interop.Advapi32.CreateProcessWithLogonW( startInfo.UserName, startInfo.Domain, (IntPtr)passwordPtr, logonFlags, null, // we don't need this since all the info is in commandLine commandLine, creationFlags, environmentPtr, workingDirectory, startupInfo, // pointer to STARTUPINFO processInfo // pointer to PROCESS_INFORMATION ); } } if (!retVal) errorCode = Marshal.GetLastWin32Error(); } if (processInfo.hProcess != IntPtr.Zero && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != IntPtr.Zero && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(processInfo.hThread); if (!retVal) { if (errorCode == Interop.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) { throw new Win32Exception(errorCode, SR.InvalidApplication); } throw new Win32Exception(errorCode); } } else { retVal = Interop.Kernel32.CreateProcess( null, // we don't need this since all the info is in commandLine commandLine, // pointer to the command line string ref unused_SecAttrs, // address to process security attributes, we don't need to inherit the handle ref unused_SecAttrs, // address to thread security attributes. true, // handle inheritance flag creationFlags, // creation flags environmentPtr, // pointer to new environment block workingDirectory, // pointer to current directory name startupInfo, // pointer to STARTUPINFO processInfo // pointer to PROCESS_INFORMATION ); if (!retVal) errorCode = Marshal.GetLastWin32Error(); if (processInfo.hProcess != (IntPtr)0 && processInfo.hProcess != (IntPtr)INVALID_HANDLE_VALUE) procSH.InitialSetHandle(processInfo.hProcess); if (processInfo.hThread != (IntPtr)0 && processInfo.hThread != (IntPtr)INVALID_HANDLE_VALUE) threadSH.InitialSetHandle(processInfo.hThread); if (!retVal) { if (errorCode == Interop.Errors.ERROR_BAD_EXE_FORMAT || errorCode == Interop.Errors.ERROR_EXE_MACHINE_TYPE_MISMATCH) { throw new Win32Exception(errorCode, SR.InvalidApplication); } throw new Win32Exception(errorCode); } } } finally { // free environment block if (environmentHandle.IsAllocated) { environmentHandle.Free(); } startupInfo.Dispose(); } } if (startInfo.RedirectStandardInput) { Encoding enc = GetEncoding((int)Interop.Kernel32.GetConsoleCP()); _standardInput = new StreamWriter(new FileStream(standardInputWritePipeHandle, FileAccess.Write, 4096, false), enc, 4096); _standardInput.AutoFlush = true; } if (startInfo.RedirectStandardOutput) { Encoding enc = startInfo.StandardOutputEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardOutput = new StreamReader(new FileStream(standardOutputReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } if (startInfo.RedirectStandardError) { Encoding enc = startInfo.StandardErrorEncoding ?? GetEncoding((int)Interop.Kernel32.GetConsoleOutputCP()); _standardError = new StreamReader(new FileStream(standardErrorReadPipeHandle, FileAccess.Read, 4096, false), enc, true, 4096); } bool ret = false; if (!procSH.IsInvalid) { SetProcessHandle(procSH); SetProcessId((int)processInfo.dwProcessId); threadSH.Dispose(); ret = true; } return ret; } private static Encoding GetEncoding(int codePage) { Encoding enc = EncodingHelper.GetSupportedConsoleEncoding(codePage); return new ConsoleEncoding(enc); // ensure encoding doesn't output a preamble } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private bool _signaled; private static StringBuilder BuildCommandLine(string executableFileName, string arguments) { // Construct a StringBuilder with the appropriate command line // to pass to CreateProcess. If the filename isn't already // in quotes, we quote it here. This prevents some security // problems (it specifies exactly which part of the string // is the file to execute). StringBuilder commandLine = new StringBuilder(); string fileName = executableFileName.Trim(); bool fileNameIsQuoted = (fileName.StartsWith("\"", StringComparison.Ordinal) && fileName.EndsWith("\"", StringComparison.Ordinal)); if (!fileNameIsQuoted) { commandLine.Append("\""); } commandLine.Append(fileName); if (!fileNameIsQuoted) { commandLine.Append("\""); } if (!string.IsNullOrEmpty(arguments)) { commandLine.Append(" "); commandLine.Append(arguments); } return commandLine; } /// <summary>Gets timing information for the current process.</summary> private ProcessThreadTimes GetProcessTimes() { using (SafeProcessHandle handle = GetProcessHandle(Interop.Advapi32.ProcessOptions.PROCESS_QUERY_LIMITED_INFORMATION, false)) { if (handle.IsInvalid) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } ProcessThreadTimes processTimes = new ProcessThreadTimes(); if (!Interop.Kernel32.GetProcessTimes(handle, out processTimes._create, out processTimes._exit, out processTimes._kernel, out processTimes._user)) { throw new Win32Exception(); } return processTimes; } } private static void SetPrivilege(string privilegeName, int attrib) { SafeTokenHandle hToken = null; Interop.Advapi32.LUID debugValue = new Interop.Advapi32.LUID(); // this is only a "pseudo handle" to the current process - no need to close it later SafeProcessHandle processHandle = Interop.Kernel32.GetCurrentProcess(); // get the process token so we can adjust the privilege on it. We DO need to // close the token when we're done with it. if (!Interop.Advapi32.OpenProcessToken(processHandle, Interop.Kernel32.HandleOptions.TOKEN_ADJUST_PRIVILEGES, out hToken)) { throw new Win32Exception(); } try { if (!Interop.Advapi32.LookupPrivilegeValue(null, privilegeName, out debugValue)) { throw new Win32Exception(); } Interop.Advapi32.TokenPrivileges tkp = new Interop.Advapi32.TokenPrivileges(); tkp.Luid = debugValue; tkp.Attributes = attrib; Interop.Advapi32.AdjustTokenPrivileges(hToken, false, tkp, 0, IntPtr.Zero, IntPtr.Zero); // AdjustTokenPrivileges can return true even if it failed to // set the privilege, so we need to use GetLastError if (Marshal.GetLastWin32Error() != Interop.Errors.ERROR_SUCCESS) { throw new Win32Exception(); } } finally { #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(processToken)"); #endif if (hToken != null) { hToken.Dispose(); } } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. /// If a handle is stored in current process object, then use it. /// Note that the handle we stored in current process object will have all access we need. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access, bool throwIfExited) { #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "GetProcessHandle(access = 0x" + access.ToString("X8", CultureInfo.InvariantCulture) + ", throwIfExited = " + throwIfExited + ")"); #if DEBUG if (_processTracing.TraceVerbose) { StackFrame calledFrom = new StackTrace(true).GetFrame(0); Debug.WriteLine(" called from " + calledFrom.GetFileName() + ", line " + calledFrom.GetFileLineNumber()); } #endif #endif if (_haveProcessHandle) { if (throwIfExited) { // Since haveProcessHandle is true, we know we have the process handle // open with at least SYNCHRONIZE access, so we can wait on it with // zero timeout to see if the process has exited. using (ProcessWaitHandle waitHandle = new ProcessWaitHandle(_processHandle)) { if (waitHandle.WaitOne(0)) { if (_haveProcessId) throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); else throw new InvalidOperationException(SR.ProcessHasExitedNoId); } } } // If we dispose of our contained handle we'll be in a bad state. NetFX dealt with this // by doing a try..finally around every usage of GetProcessHandle and only disposed if // it wasn't our handle. return new SafeProcessHandle(_processHandle.DangerousGetHandle(), ownsHandle: false); } else { EnsureState(State.HaveId | State.IsLocal); SafeProcessHandle handle = SafeProcessHandle.InvalidHandle; handle = ProcessManager.OpenProcess(_processId, access, throwIfExited); if (throwIfExited && (access & Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION) != 0) { if (Interop.Kernel32.GetExitCodeProcess(handle, out _exitCode) && _exitCode != Interop.Kernel32.HandleOptions.STILL_ACTIVE) { throw new InvalidOperationException(SR.Format(SR.ProcessHasExited, _processId.ToString(CultureInfo.CurrentCulture))); } } return handle; } } /// <devdoc> /// Gets a short-term handle to the process, with the given access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </devdoc> /// <internalonly/> private SafeProcessHandle GetProcessHandle(int access) { return GetProcessHandle(access, true); } private static void CreatePipeWithSecurityAttributes(out SafeFileHandle hReadPipe, out SafeFileHandle hWritePipe, ref Interop.Kernel32.SECURITY_ATTRIBUTES lpPipeAttributes, int nSize) { bool ret = Interop.Kernel32.CreatePipe(out hReadPipe, out hWritePipe, ref lpPipeAttributes, nSize); if (!ret || hReadPipe.IsInvalid || hWritePipe.IsInvalid) { throw new Win32Exception(); } } // Using synchronous Anonymous pipes for process input/output redirection means we would end up // wasting a worker threadpool thread per pipe instance. Overlapped pipe IO is desirable, since // it will take advantage of the NT IO completion port infrastructure. But we can't really use // Overlapped I/O for process input/output as it would break Console apps (managed Console class // methods such as WriteLine as well as native CRT functions like printf) which are making an // assumption that the console standard handles (obtained via GetStdHandle()) are opened // for synchronous I/O and hence they can work fine with ReadFile/WriteFile synchronously! private void CreatePipe(out SafeFileHandle parentHandle, out SafeFileHandle childHandle, bool parentInputs) { Interop.Kernel32.SECURITY_ATTRIBUTES securityAttributesParent = new Interop.Kernel32.SECURITY_ATTRIBUTES(); securityAttributesParent.bInheritHandle = Interop.BOOL.TRUE; SafeFileHandle hTmp = null; try { if (parentInputs) { CreatePipeWithSecurityAttributes(out childHandle, out hTmp, ref securityAttributesParent, 0); } else { CreatePipeWithSecurityAttributes(out hTmp, out childHandle, ref securityAttributesParent, 0); } // Duplicate the parent handle to be non-inheritable so that the child process // doesn't have access. This is done for correctness sake, exact reason is unclear. // One potential theory is that child process can do something brain dead like // closing the parent end of the pipe and there by getting into a blocking situation // as parent will not be draining the pipe at the other end anymore. SafeProcessHandle currentProcHandle = Interop.Kernel32.GetCurrentProcess(); if (!Interop.Kernel32.DuplicateHandle(currentProcHandle, hTmp, currentProcHandle, out parentHandle, 0, false, Interop.Kernel32.HandleOptions.DUPLICATE_SAME_ACCESS)) { throw new Win32Exception(); } } finally { if (hTmp != null && !hTmp.IsInvalid) { hTmp.Dispose(); } } } private static byte[] EnvironmentVariablesToByteArray(IDictionary<string, string> sd) { // get the keys string[] keys = new string[sd.Count]; byte[] envBlock = null; sd.Keys.CopyTo(keys, 0); // sort both by the keys // Windows 2000 requires the environment block to be sorted by the key // It will first converting the case the strings and do ordinal comparison. // We do not use Array.Sort(keys, values, IComparer) since it is only supported // in System.Runtime contract from 4.20.0.0 and Test.Net depends on System.Runtime 4.0.10.0 // we workaround this by sorting only the keys and then lookup the values form the keys. Array.Sort(keys, StringComparer.OrdinalIgnoreCase); // create a list of null terminated "key=val" strings StringBuilder stringBuff = new StringBuilder(); for (int i = 0; i < sd.Count; ++i) { stringBuff.Append(keys[i]); stringBuff.Append('='); stringBuff.Append(sd[keys[i]]); stringBuff.Append('\0'); } // an extra null at the end indicates end of list. stringBuff.Append('\0'); envBlock = Encoding.Unicode.GetBytes(stringBuff.ToString()); return envBlock; } } }
/* * 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 OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Threading; using System.Xml; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.CoreModules.Avatar.Voice.VivoxVoice { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "VivoxVoiceModule")] public class VivoxVoiceModule : ISharedRegionModule { // channel distance model values public const int CHAN_DIST_NONE = 0; // no attenuation public const int CHAN_DIST_INVERSE = 1; // inverse distance attenuation public const int CHAN_DIST_LINEAR = 2; // linear attenuation public const int CHAN_DIST_EXPONENT = 3; // exponential attenuation public const int CHAN_DIST_DEFAULT = CHAN_DIST_LINEAR; // channel type values public static readonly string CHAN_TYPE_POSITIONAL = "positional"; public static readonly string CHAN_TYPE_CHANNEL = "channel"; public static readonly string CHAN_TYPE_DEFAULT = CHAN_TYPE_POSITIONAL; // channel mode values public static readonly string CHAN_MODE_OPEN = "open"; public static readonly string CHAN_MODE_LECTURE = "lecture"; public static readonly string CHAN_MODE_PRESENTATION = "presentation"; public static readonly string CHAN_MODE_AUDITORIUM = "auditorium"; public static readonly string CHAN_MODE_DEFAULT = CHAN_MODE_OPEN; // unconstrained default values public const double CHAN_ROLL_OFF_DEFAULT = 2.0; // rate of attenuation public const double CHAN_ROLL_OFF_MIN = 1.0; public const double CHAN_ROLL_OFF_MAX = 4.0; public const int CHAN_MAX_RANGE_DEFAULT = 80; // distance at which channel is silent public const int CHAN_MAX_RANGE_MIN = 0; public const int CHAN_MAX_RANGE_MAX = 160; public const int CHAN_CLAMPING_DISTANCE_DEFAULT = 10; // distance before attenuation applies public const int CHAN_CLAMPING_DISTANCE_MIN = 0; public const int CHAN_CLAMPING_DISTANCE_MAX = 160; // Infrastructure private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly Object vlock = new Object(); // Capability strings private static readonly string m_parcelVoiceInfoRequestPath = "0107/"; private static readonly string m_provisionVoiceAccountRequestPath = "0108/"; //private static readonly string m_chatSessionRequestPath = "0109/"; // Control info, e.g. vivox server, admin user, admin password private static bool m_pluginEnabled = false; private static bool m_adminConnected = false; private static string m_vivoxServer; private static string m_vivoxSipUri; private static string m_vivoxVoiceAccountApi; private static string m_vivoxAdminUser; private static string m_vivoxAdminPassword; private static string m_authToken = String.Empty; private static int m_vivoxChannelDistanceModel; private static double m_vivoxChannelRollOff; private static int m_vivoxChannelMaximumRange; private static string m_vivoxChannelMode; private static string m_vivoxChannelType; private static int m_vivoxChannelClampingDistance; private static Dictionary<string, string> m_parents = new Dictionary<string, string>(); private static bool m_dumpXml; private IConfig m_config; private object m_Lock; public void Initialise(IConfigSource config) { m_config = config.Configs["VivoxVoice"]; if (null == m_config) return; if (!m_config.GetBoolean("enabled", false)) return; m_Lock = new object(); try { // retrieve configuration variables m_vivoxServer = m_config.GetString("vivox_server", String.Empty); m_vivoxSipUri = m_config.GetString("vivox_sip_uri", String.Empty); m_vivoxAdminUser = m_config.GetString("vivox_admin_user", String.Empty); m_vivoxAdminPassword = m_config.GetString("vivox_admin_password", String.Empty); m_vivoxChannelDistanceModel = m_config.GetInt("vivox_channel_distance_model", CHAN_DIST_DEFAULT); m_vivoxChannelRollOff = m_config.GetDouble("vivox_channel_roll_off", CHAN_ROLL_OFF_DEFAULT); m_vivoxChannelMaximumRange = m_config.GetInt("vivox_channel_max_range", CHAN_MAX_RANGE_DEFAULT); m_vivoxChannelMode = m_config.GetString("vivox_channel_mode", CHAN_MODE_DEFAULT).ToLower(); m_vivoxChannelType = m_config.GetString("vivox_channel_type", CHAN_TYPE_DEFAULT).ToLower(); m_vivoxChannelClampingDistance = m_config.GetInt("vivox_channel_clamping_distance", CHAN_CLAMPING_DISTANCE_DEFAULT); m_dumpXml = m_config.GetBoolean("dump_xml", false); // Validate against constraints and default if necessary if (m_vivoxChannelRollOff < CHAN_ROLL_OFF_MIN || m_vivoxChannelRollOff > CHAN_ROLL_OFF_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for roll off ({0}), reset to {1}.", m_vivoxChannelRollOff, CHAN_ROLL_OFF_DEFAULT); m_vivoxChannelRollOff = CHAN_ROLL_OFF_DEFAULT; } if (m_vivoxChannelMaximumRange < CHAN_MAX_RANGE_MIN || m_vivoxChannelMaximumRange > CHAN_MAX_RANGE_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for maximum range ({0}), reset to {1}.", m_vivoxChannelMaximumRange, CHAN_MAX_RANGE_DEFAULT); m_vivoxChannelMaximumRange = CHAN_MAX_RANGE_DEFAULT; } if (m_vivoxChannelClampingDistance < CHAN_CLAMPING_DISTANCE_MIN || m_vivoxChannelClampingDistance > CHAN_CLAMPING_DISTANCE_MAX) { m_log.WarnFormat("[VivoxVoice] Invalid value for clamping distance ({0}), reset to {1}.", m_vivoxChannelClampingDistance, CHAN_CLAMPING_DISTANCE_DEFAULT); m_vivoxChannelClampingDistance = CHAN_CLAMPING_DISTANCE_DEFAULT; } switch (m_vivoxChannelMode) { case "open": break; case "lecture": break; case "presentation": break; case "auditorium": break; default: m_log.WarnFormat("[VivoxVoice] Invalid value for channel mode ({0}), reset to {1}.", m_vivoxChannelMode, CHAN_MODE_DEFAULT); m_vivoxChannelMode = CHAN_MODE_DEFAULT; break; } switch (m_vivoxChannelType) { case "positional": break; case "channel": break; default: m_log.WarnFormat("[VivoxVoice] Invalid value for channel type ({0}), reset to {1}.", m_vivoxChannelType, CHAN_TYPE_DEFAULT); m_vivoxChannelType = CHAN_TYPE_DEFAULT; break; } m_vivoxVoiceAccountApi = String.Format("http://{0}/api2", m_vivoxServer); // Admin interface required values if (String.IsNullOrEmpty(m_vivoxServer) || String.IsNullOrEmpty(m_vivoxSipUri) || String.IsNullOrEmpty(m_vivoxAdminUser) || String.IsNullOrEmpty(m_vivoxAdminPassword)) { m_log.Error("[VivoxVoice] plugin mis-configured"); m_log.Info("[VivoxVoice] plugin disabled: incomplete configuration"); return; } m_log.InfoFormat("[VivoxVoice] using vivox server {0}", m_vivoxServer); // Get admin rights and cleanup any residual channel definition DoAdminLogin(); m_pluginEnabled = true; m_log.Info("[VivoxVoice] plugin enabled"); } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice] plugin initialization failed: {0}", e.Message); m_log.DebugFormat("[VivoxVoice] plugin initialization failed: {0}", e.ToString()); return; } } public void AddRegion(Scene scene) { if (m_pluginEnabled) { lock (vlock) { string channelId; string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. // This assumes that there is just one directory per // region. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId)) { m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}", sceneName, sceneUUID, channelId); XmlElement children = VivoxListChildren(channelId); string count; if (XmlFind(children, "response.level0.channel-search.count", out count)) { int cnum = Convert.ToInt32(count); for (int i = 0; i < cnum; i++) { string id; if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); } } } } else { if (!VivoxTryCreateDirectory(sceneUUID + "D", sceneName, out channelId)) { m_log.WarnFormat("[VivoxVoice] Create failed <{0}:{1}:{2}>", "*", sceneUUID, sceneName); channelId = String.Empty; } } // Create a dictionary entry unconditionally. This eliminates the // need to check for a parent in the core code. The end result is // the same, if the parent table entry is an empty string, then // region channels will be created as first-level channels. lock (m_parents) { if (m_parents.ContainsKey(sceneUUID)) { RemoveRegion(scene); m_parents.Add(sceneUUID, channelId); } else { m_parents.Add(sceneUUID, channelId); } } } // we need to capture scene in an anonymous method // here as we need it later in the callbacks scene.EventManager.OnRegisterCaps += delegate(UUID agentID, Caps caps) { OnRegisterCaps(scene, agentID, caps); }; } } public void RegionLoaded(Scene scene) { // Do nothing. } public void RemoveRegion(Scene scene) { if (m_pluginEnabled) { lock (vlock) { string channelId; string sceneUUID = scene.RegionInfo.RegionID.ToString(); string sceneName = scene.RegionInfo.RegionName; // Make sure that all local channels are deleted. // So we have to search for the children, and then do an // iteration over the set of chidren identified. // This assumes that there is just one directory per // region. if (VivoxTryGetDirectory(sceneUUID + "D", out channelId)) { m_log.DebugFormat("[VivoxVoice]: region {0}: uuid {1}: located directory id {2}", sceneName, sceneUUID, channelId); XmlElement children = VivoxListChildren(channelId); string count; if (XmlFind(children, "response.level0.channel-search.count", out count)) { int cnum = Convert.ToInt32(count); for (int i = 0; i < cnum; i++) { string id; if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { if (!IsOK(VivoxDeleteChannel(channelId, id))) m_log.WarnFormat("[VivoxVoice] Channel delete failed {0}:{1}:{2}", i, channelId, id); } } } } if (!IsOK(VivoxDeleteChannel(null, channelId))) m_log.WarnFormat("[VivoxVoice] Parent channel delete failed {0}:{1}:{2}", sceneName, sceneUUID, channelId); // Remove the channel umbrella entry lock (m_parents) { if (m_parents.ContainsKey(sceneUUID)) { m_parents.Remove(sceneUUID); } } } } } public void PostInitialise() { // Do nothing. } public void Close() { if (m_pluginEnabled) VivoxLogout(); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "VivoxVoiceModule"; } } public bool IsSharedModule { get { return true; } } // <summary> // OnRegisterCaps is invoked via the scene.EventManager // everytime OpenSim hands out capabilities to a client // (login, region crossing). We contribute two capabilities to // the set of capabilities handed back to the client: // ProvisionVoiceAccountRequest and ParcelVoiceInfoRequest. // // ProvisionVoiceAccountRequest allows the client to obtain // the voice account credentials for the avatar it is // controlling (e.g., user name, password, etc). // // ParcelVoiceInfoRequest is invoked whenever the client // changes from one region or parcel to another. // // Note that OnRegisterCaps is called here via a closure // delegate containing the scene of the respective region (see // Initialise()). // </summary> public void OnRegisterCaps(Scene scene, UUID agentID, Caps caps) { m_log.DebugFormat("[VivoxVoice] OnRegisterCaps: agentID {0} caps {1}", agentID, caps); string capsBase = "/CAPS/" + caps.CapsObjectPath; caps.RegisterHandler( "ProvisionVoiceAccountRequest", new RestStreamHandler( "POST", capsBase + m_provisionVoiceAccountRequestPath, (request, path, param, httpRequest, httpResponse) => ProvisionVoiceAccountRequest(scene, request, path, param, agentID, caps), "ProvisionVoiceAccountRequest", agentID.ToString())); caps.RegisterHandler( "ParcelVoiceInfoRequest", new RestStreamHandler( "POST", capsBase + m_parcelVoiceInfoRequestPath, (request, path, param, httpRequest, httpResponse) => ParcelVoiceInfoRequest(scene, request, path, param, agentID, caps), "ParcelVoiceInfoRequest", agentID.ToString())); //caps.RegisterHandler( // "ChatSessionRequest", // new RestStreamHandler( // "POST", // capsBase + m_chatSessionRequestPath, // (request, path, param, httpRequest, httpResponse) // => ChatSessionRequest(scene, request, path, param, agentID, caps), // "ChatSessionRequest", // agentID.ToString())); } /// <summary> /// Callback for a client request for Voice Account Details /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ProvisionVoiceAccountRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { try { ScenePresence avatar = null; string avatarName = null; if (scene == null) throw new Exception("[VivoxVoice][PROVISIONVOICE]: Invalid scene"); avatar = scene.GetScenePresence(agentID); while (avatar == null) { Thread.Sleep(100); avatar = scene.GetScenePresence(agentID); } avatarName = avatar.Name; m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: scene = {0}, agentID = {1}", scene, agentID); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: request: {0}, path: {1}, param: {2}", request, path, param); XmlElement resp; bool retry = false; string agentname = "x" + Convert.ToBase64String(agentID.GetBytes()); string password = new UUID(Guid.NewGuid()).ToString().Replace('-', 'Z').Substring(0, 16); string code = String.Empty; agentname = agentname.Replace('+', '-').Replace('/', '_'); do { resp = VivoxGetAccountInfo(agentname); if (XmlFind(resp, "response.level0.status", out code)) { if (code != "OK") { if (XmlFind(resp, "response.level0.body.code", out code)) { // If the request was recognized, then this should be set to something switch (code) { case "201": // Account expired m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : expired credentials", avatarName); m_adminConnected = false; retry = DoAdminLogin(); break; case "202": // Missing credentials m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : missing credentials", avatarName); break; case "212": // Not authorized m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : not authorized", avatarName); break; case "300": // Required parameter missing m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : parameter missing", avatarName); break; case "403": // Account does not exist resp = VivoxCreateAccount(agentname, password); // Note: This REALLY MUST BE status. Create Account does not return code. if (XmlFind(resp, "response.level0.status", out code)) { switch (code) { case "201": // Account expired m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : expired credentials", avatarName); m_adminConnected = false; retry = DoAdminLogin(); break; case "202": // Missing credentials m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : missing credentials", avatarName); break; case "212": // Not authorized m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : not authorized", avatarName); break; case "300": // Required parameter missing m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : parameter missing", avatarName); break; case "400": // Create failed m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Create account information failed : create failed", avatarName); break; } } break; case "404": // Failed to retrieve account m_log.ErrorFormat("[VivoxVoice]: avatar \"{0}\": Get account information failed : retrieve failed"); // [AMW] Sleep and retry for a fixed period? Or just abandon? break; } } } } } while (retry); if (code != "OK") { m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: Get Account Request failed for \"{0}\"", avatarName); throw new Exception("Unable to execute request"); } // Unconditionally change the password on each request VivoxPassword(agentname, password); LLSDVoiceAccountResponse voiceAccountResponse = new LLSDVoiceAccountResponse(agentname, password, m_vivoxSipUri, m_vivoxVoiceAccountApi); string r = LLSDHelpers.SerialiseLLSDReply(voiceAccountResponse); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: avatar \"{0}\": {1}", avatarName, r); return r; } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice][PROVISIONVOICE]: : {0}, retry later", e.Message); m_log.DebugFormat("[VivoxVoice][PROVISIONVOICE]: : {0} failed", e.ToString()); return "<llsd><undef /></llsd>"; } } /// <summary> /// Callback for a client request for ParcelVoiceInfo /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ParcelVoiceInfoRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { ScenePresence avatar = scene.GetScenePresence(agentID); string avatarName = avatar.Name; // - check whether we have a region channel in our cache // - if not: // create it and cache it // - send it to the client // - send channel_uri: as "sip:regionID@m_sipDomain" try { LLSDParcelVoiceInfoResponse parcelVoiceInfo; string channel_uri; if (null == scene.LandChannel) throw new Exception(String.Format("region \"{0}\": avatar \"{1}\": land data not yet available", scene.RegionInfo.RegionName, avatarName)); // get channel_uri: check first whether estate // settings allow voice, then whether parcel allows // voice, if all do retrieve or obtain the parcel // voice channel LandData land = scene.GetLandData(avatar.AbsolutePosition); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": request: {4}, path: {5}, param: {6}", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, request, path, param); // m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: avatar \"{0}\": location: {1} {2} {3}", // avatarName, avatar.AbsolutePosition.X, avatar.AbsolutePosition.Y, avatar.AbsolutePosition.Z); // TODO: EstateSettings don't seem to get propagated... if (!scene.RegionInfo.EstateSettings.AllowVoice) { m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": voice not enabled in estate settings", scene.RegionInfo.RegionName); channel_uri = String.Empty; } if ((land.Flags & (uint)ParcelFlags.AllowVoiceChat) == 0) { m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": voice not enabled for parcel", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName); channel_uri = String.Empty; } else { channel_uri = RegionGetOrCreateChannel(scene, land); } // fill in our response to the client Hashtable creds = new Hashtable(); creds["channel_uri"] = channel_uri; parcelVoiceInfo = new LLSDParcelVoiceInfoResponse(scene.RegionInfo.RegionName, land.LocalID, creds); string r = LLSDHelpers.SerialiseLLSDReply(parcelVoiceInfo); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": Parcel \"{1}\" ({2}): avatar \"{3}\": {4}", scene.RegionInfo.RegionName, land.Name, land.LocalID, avatarName, r); return r; } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2}, retry later", scene.RegionInfo.RegionName, avatarName, e.Message); m_log.DebugFormat("[VivoxVoice][PARCELVOICE]: region \"{0}\": avatar \"{1}\": {2} failed", scene.RegionInfo.RegionName, avatarName, e.ToString()); return "<llsd><undef /></llsd>"; } } /// <summary> /// Callback for a client request for a private chat channel /// </summary> /// <param name="scene">current scene object of the client</param> /// <param name="request"></param> /// <param name="path"></param> /// <param name="param"></param> /// <param name="agentID"></param> /// <param name="caps"></param> /// <returns></returns> public string ChatSessionRequest(Scene scene, string request, string path, string param, UUID agentID, Caps caps) { ScenePresence avatar = scene.GetScenePresence(agentID); string avatarName = avatar.Name; m_log.DebugFormat("[VivoxVoice][CHATSESSION]: avatar \"{0}\": request: {1}, path: {2}, param: {3}", avatarName, request, path, param); return "<llsd>true</llsd>"; } private string RegionGetOrCreateChannel(Scene scene, LandData land) { string channelUri = null; string channelId = null; string landUUID; string landName; string parentId; lock (m_parents) parentId = m_parents[scene.RegionInfo.RegionID.ToString()]; // Create parcel voice channel. If no parcel exists, then the voice channel ID is the same // as the directory ID. Otherwise, it reflects the parcel's ID. if (land.LocalID != 1 && (land.Flags & (uint)ParcelFlags.UseEstateVoiceChan) == 0) { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, land.Name); landUUID = land.GlobalID.ToString(); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } else { landName = String.Format("{0}:{1}", scene.RegionInfo.RegionName, scene.RegionInfo.RegionName); landUUID = scene.RegionInfo.RegionID.ToString(); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parcel id {1}: using channel name {2}", landName, land.LocalID, landUUID); } lock (vlock) { // Added by Adam to help debug channel not availible errors. if (VivoxTryGetChannel(parentId, landUUID, out channelId, out channelUri)) m_log.DebugFormat("[VivoxVoice] Found existing channel at " + channelUri); else if (VivoxTryCreateChannel(parentId, landUUID, landName, out channelUri)) m_log.DebugFormat("[VivoxVoice] Created new channel at " + channelUri); else throw new Exception("vivox channel uri not available"); m_log.DebugFormat("[VivoxVoice]: Region:Parcel \"{0}\": parent channel id {1}: retrieved parcel channel_uri {2} ", landName, parentId, channelUri); } return channelUri; } private static readonly string m_vivoxLoginPath = "http://{0}/api2/viv_signin.php?userid={1}&pwd={2}"; /// <summary> /// Perform administrative login for Vivox. /// Returns a hash table containing values returned from the request. /// </summary> private XmlElement VivoxLogin(string name, string password) { string requrl = String.Format(m_vivoxLoginPath, m_vivoxServer, name, password); return VivoxCall(requrl, false); } private static readonly string m_vivoxLogoutPath = "http://{0}/api2/viv_signout.php?auth_token={1}"; /// <summary> /// Perform administrative logout for Vivox. /// </summary> private XmlElement VivoxLogout() { string requrl = String.Format(m_vivoxLogoutPath, m_vivoxServer, m_authToken); return VivoxCall(requrl, false); } private static readonly string m_vivoxGetAccountPath = "http://{0}/api2/viv_get_acct.php?auth_token={1}&user_name={2}"; /// <summary> /// Retrieve account information for the specified user. /// Returns a hash table containing values returned from the request. /// </summary> private XmlElement VivoxGetAccountInfo(string user) { string requrl = String.Format(m_vivoxGetAccountPath, m_vivoxServer, m_authToken, user); return VivoxCall(requrl, true); } private static readonly string m_vivoxNewAccountPath = "http://{0}/api2/viv_adm_acct_new.php?username={1}&pwd={2}&auth_token={3}"; /// <summary> /// Creates a new account. /// For now we supply the minimum set of values, which /// is user name and password. We *can* supply a lot more /// demographic data. /// </summary> private XmlElement VivoxCreateAccount(string user, string password) { string requrl = String.Format(m_vivoxNewAccountPath, m_vivoxServer, user, password, m_authToken); return VivoxCall(requrl, true); } private static readonly string m_vivoxPasswordPath = "http://{0}/api2/viv_adm_password.php?user_name={1}&new_pwd={2}&auth_token={3}"; /// <summary> /// Change the user's password. /// </summary> private XmlElement VivoxPassword(string user, string password) { string requrl = String.Format(m_vivoxPasswordPath, m_vivoxServer, user, password, m_authToken); return VivoxCall(requrl, true); } private static readonly string m_vivoxChannelPath = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_name={2}&auth_token={3}"; /// <summary> /// Create a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// /// In this case the call handles parent and description as optional values. /// </summary> private bool VivoxTryCreateChannel(string parent, string channelId, string description, out string channelUri) { string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", channelId, m_authToken); if (!string.IsNullOrEmpty(parent)) { requrl = String.Format("{0}&chan_parent={1}", requrl, parent); } if (!string.IsNullOrEmpty(description)) { requrl = String.Format("{0}&chan_desc={1}", requrl, description); } requrl = String.Format("{0}&chan_type={1}", requrl, m_vivoxChannelType); requrl = String.Format("{0}&chan_mode={1}", requrl, m_vivoxChannelMode); requrl = String.Format("{0}&chan_roll_off={1}", requrl, m_vivoxChannelRollOff); requrl = String.Format("{0}&chan_dist_model={1}", requrl, m_vivoxChannelDistanceModel); requrl = String.Format("{0}&chan_max_range={1}", requrl, m_vivoxChannelMaximumRange); requrl = String.Format("{0}&chan_clamping_distance={1}", requrl, m_vivoxChannelClampingDistance); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.body.chan_uri", out channelUri)) return true; channelUri = String.Empty; return false; } /// <summary> /// Create a directory. /// Create a channel with an unconditional type of "dir" (indicating directory). /// This is used to create an arbitrary name tree for partitioning of the /// channel name space. /// The parent and description are optional values. /// </summary> private bool VivoxTryCreateDirectory(string dirId, string description, out string channelId) { string requrl = String.Format(m_vivoxChannelPath, m_vivoxServer, "create", dirId, m_authToken); // if (parent != null && parent != String.Empty) // { // requrl = String.Format("{0}&chan_parent={1}", requrl, parent); // } if (!string.IsNullOrEmpty(description)) { requrl = String.Format("{0}&chan_desc={1}", requrl, description); } requrl = String.Format("{0}&chan_type={1}", requrl, "dir"); XmlElement resp = VivoxCall(requrl, true); if (IsOK(resp) && XmlFind(resp, "response.level0.body.chan_id", out channelId)) return true; channelId = String.Empty; return false; } private static readonly string m_vivoxChannelSearchPath = "http://{0}/api2/viv_chan_search.php?cond_channame={1}&auth_token={2}"; /// <summary> /// Retrieve a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// </summary> private bool VivoxTryGetChannel(string channelParent, string channelName, out string channelId, out string channelUri) { string count; string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, channelName, m_authToken); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.channel-search.count", out count)) { int channels = Convert.ToInt32(count); // Bug in Vivox Server r2978 where count returns 0 // Found by Adam if (channels == 0) { for (int j = 0; j < 100; j++) { string tmpId; if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", j, out tmpId)) break; channels = j + 1; } } for (int i = 0; i < channels; i++) { string name; string id; string type; string uri; string parent; // skip if not a channel if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || (type != "channel" && type != "positional_M")) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it's not a channel."); continue; } // skip if not the name we are looking for if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) || name != channelName) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + " as it has no name."); continue; } // skip if parent does not match if (channelParent != null && !XmlFind(resp, "response.level0.channel-search.channels.channels.level4.parent", i, out parent)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it's parent doesnt match"); continue; } // skip if no channel id available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel ID"); continue; } // skip if no channel uri available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.uri", i, out uri)) { m_log.Debug("[VivoxVoice] Skipping Channel " + i + "/" + name + " as it has no channel URI"); continue; } channelId = id; channelUri = uri; return true; } } else { m_log.Debug("[VivoxVoice] No count element?"); } channelId = String.Empty; channelUri = String.Empty; // Useful incase something goes wrong. //m_log.Debug("[VivoxVoice] Could not find channel in XMLRESP: " + resp.InnerXml); return false; } private bool VivoxTryGetDirectory(string directoryName, out string directoryId) { string count; string requrl = String.Format(m_vivoxChannelSearchPath, m_vivoxServer, directoryName, m_authToken); XmlElement resp = VivoxCall(requrl, true); if (XmlFind(resp, "response.level0.channel-search.count", out count)) { int channels = Convert.ToInt32(count); for (int i = 0; i < channels; i++) { string name; string id; string type; // skip if not a directory if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.type", i, out type) || type != "dir") continue; // skip if not the name we are looking for if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.name", i, out name) || name != directoryName) continue; // skip if no channel id available if (!XmlFind(resp, "response.level0.channel-search.channels.channels.level4.id", i, out id)) continue; directoryId = id; return true; } } directoryId = String.Empty; return false; } // private static readonly string m_vivoxChannelById = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; // private XmlElement VivoxGetChannelById(string parent, string channelid) // { // string requrl = String.Format(m_vivoxChannelById, m_vivoxServer, "get", channelid, m_authToken); // if (parent != null && parent != String.Empty) // return VivoxGetChild(parent, channelid); // else // return VivoxCall(requrl, true); // } private static readonly string m_vivoxChannelDel = "http://{0}/api2/viv_chan_mod.php?mode={1}&chan_id={2}&auth_token={3}"; /// <summary> /// Delete a channel. /// Once again, there a multitude of options possible. In the simplest case /// we specify only the name and get a non-persistent cannel in return. Non /// persistent means that the channel gets deleted if no-one uses it for /// 5 hours. To accomodate future requirements, it may be a good idea to /// initially create channels under the umbrella of a parent ID based upon /// the region name. That way we have a context for side channels, if those /// are required in a later phase. /// In this case the call handles parent and description as optional values. /// </summary> private XmlElement VivoxDeleteChannel(string parent, string channelid) { string requrl = String.Format(m_vivoxChannelDel, m_vivoxServer, "delete", channelid, m_authToken); if (!string.IsNullOrEmpty(parent)) { requrl = String.Format("{0}&chan_parent={1}", requrl, parent); } return VivoxCall(requrl, true); } private static readonly string m_vivoxChannelSearch = "http://{0}/api2/viv_chan_search.php?&cond_chanparent={1}&auth_token={2}"; /// <summary> /// Return information on channels in the given directory /// </summary> private XmlElement VivoxListChildren(string channelid) { string requrl = String.Format(m_vivoxChannelSearch, m_vivoxServer, channelid, m_authToken); return VivoxCall(requrl, true); } // private XmlElement VivoxGetChild(string parent, string child) // { // XmlElement children = VivoxListChildren(parent); // string count; // if (XmlFind(children, "response.level0.channel-search.count", out count)) // { // int cnum = Convert.ToInt32(count); // for (int i = 0; i < cnum; i++) // { // string name; // string id; // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.name", i, out name)) // { // if (name == child) // { // if (XmlFind(children, "response.level0.channel-search.channels.channels.level4.id", i, out id)) // { // return VivoxGetChannelById(null, id); // } // } // } // } // } // // One we *know* does not exist. // return VivoxGetChannel(null, Guid.NewGuid().ToString()); // } /// <summary> /// This method handles the WEB side of making a request over the /// Vivox interface. The returned values are tansferred to a has /// table which is returned as the result. /// The outcome of the call can be determined by examining the /// status value in the hash table. /// </summary> private XmlElement VivoxCall(string requrl, bool admin) { XmlDocument doc = null; // If this is an admin call, and admin is not connected, // and the admin id cannot be connected, then fail. if (admin && !m_adminConnected && !DoAdminLogin()) return null; doc = new XmlDocument(); // Let's serialize all calls to Vivox. Most of these are driven by // the clients (CAPs), when the user arrives at the region. We don't // want to issue many simultaneous http requests to Vivox, because mono // doesn't like that lock (m_Lock) { try { // Otherwise prepare the request m_log.DebugFormat("[VivoxVoice] Sending request <{0}>", requrl); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(requrl); // We are sending just parameters, no content req.ContentLength = 0; // Send request and retrieve the response using (HttpWebResponse rsp = (HttpWebResponse)req.GetResponse()) using (Stream s = rsp.GetResponseStream()) using (XmlTextReader rdr = new XmlTextReader(s)) doc.Load(rdr); } catch (Exception e) { m_log.ErrorFormat("[VivoxVoice] Error in admin call : {0}", e.Message); } } // If we're debugging server responses, dump the whole // load now if (m_dumpXml) XmlScanl(doc.DocumentElement, 0); return doc.DocumentElement; } /// <summary> /// Just say if it worked. /// </summary> private bool IsOK(XmlElement resp) { string status; XmlFind(resp, "response.level0.status", out status); return (status == "OK"); } /// <summary> /// Login has been factored in this way because it gets called /// from several places in the module, and we want it to work /// the same way each time. /// </summary> private bool DoAdminLogin() { m_log.Debug("[VivoxVoice] Establishing admin connection"); lock (vlock) { if (!m_adminConnected) { string status = "Unknown"; XmlElement resp = null; resp = VivoxLogin(m_vivoxAdminUser, m_vivoxAdminPassword); if (XmlFind(resp, "response.level0.body.status", out status)) { if (status == "Ok") { m_log.Info("[VivoxVoice] Admin connection established"); if (XmlFind(resp, "response.level0.body.auth_token", out m_authToken)) { if (m_dumpXml) m_log.DebugFormat("[VivoxVoice] Auth Token <{0}>", m_authToken); m_adminConnected = true; } } else { m_log.WarnFormat("[VivoxVoice] Admin connection failed, status = {0}", status); } } } } return m_adminConnected; } /// <summary> /// The XmlScan routine is provided to aid in the /// reverse engineering of incompletely /// documented packets returned by the Vivox /// voice server. It is only called if the /// m_dumpXml switch is set. /// </summary> private void XmlScanl(XmlElement e, int index) { if (e.HasChildNodes) { m_log.DebugFormat("<{0}>".PadLeft(index + 5), e.Name); XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) switch (node.NodeType) { case XmlNodeType.Element: XmlScanl((XmlElement)node, index + 1); break; case XmlNodeType.Text: m_log.DebugFormat("\"{0}\"".PadLeft(index + 5), node.Value); break; default: break; } m_log.DebugFormat("</{0}>".PadLeft(index + 6), e.Name); } else { m_log.DebugFormat("<{0}/>".PadLeft(index + 6), e.Name); } } private static readonly char[] C_POINT = { '.' }; /// <summary> /// The Find method is passed an element whose /// inner text is scanned in an attempt to match /// the name hierarchy passed in the 'tag' parameter. /// If the whole hierarchy is resolved, the InnerText /// value at that point is returned. Note that this /// may itself be a subhierarchy of the entire /// document. The function returns a boolean indicator /// of the search's success. The search is performed /// by the recursive Search method. /// </summary> private bool XmlFind(XmlElement root, string tag, int nth, out string result) { if (root == null || tag == null || tag == String.Empty) { result = String.Empty; return false; } return XmlSearch(root, tag.Split(C_POINT), 0, ref nth, out result); } private bool XmlFind(XmlElement root, string tag, out string result) { int nth = 0; if (root == null || tag == null || tag == String.Empty) { result = String.Empty; return false; } return XmlSearch(root, tag.Split(C_POINT), 0, ref nth, out result); } /// <summary> /// XmlSearch is initially called by XmlFind, and then /// recursively called by itself until the document /// supplied to XmlFind is either exhausted or the name hierarchy /// is matched. /// /// If the hierarchy is matched, the value is returned in /// result, and true returned as the function's /// value. Otherwise the result is set to the empty string and /// false is returned. /// </summary> private bool XmlSearch(XmlElement e, string[] tags, int index, ref int nth, out string result) { if (index == tags.Length || e.Name != tags[index]) { result = String.Empty; return false; } if (tags.Length - index == 1) { if (nth == 0) { result = e.InnerText; return true; } else { nth--; result = String.Empty; return false; } } if (e.HasChildNodes) { XmlNodeList children = e.ChildNodes; foreach (XmlNode node in children) { switch (node.NodeType) { case XmlNodeType.Element: if (XmlSearch((XmlElement)node, tags, index + 1, ref nth, out result)) return true; break; default: break; } } } result = String.Empty; return false; } } }
// Lucene version compatibility level 4.8.1 using YAF.Lucene.Net.Analysis.TokenAttributes; using YAF.Lucene.Net.Util; namespace YAF.Lucene.Net.Analysis.Miscellaneous { /* * 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> /// Joins two token streams and leaves the last token of the first stream available /// to be used when updating the token values in the second stream based on that token. /// /// The default implementation adds last prefix token end offset to the suffix token start and end offsets. /// <para/> /// <b>NOTE:</b> This filter might not behave correctly if used with custom /// <see cref="Lucene.Net.Util.IAttribute"/>s, i.e. <see cref="Lucene.Net.Util.IAttribute"/>s other than /// the ones located in Lucene.Net.Analysis.TokenAttributes. /// </summary> public class PrefixAwareTokenFilter : TokenStream { private TokenStream prefix; private TokenStream suffix; private readonly ICharTermAttribute termAtt; private readonly IPositionIncrementAttribute posIncrAtt; private readonly IPayloadAttribute payloadAtt; private readonly IOffsetAttribute offsetAtt; private readonly ITypeAttribute typeAtt; private readonly IFlagsAttribute flagsAtt; private readonly ICharTermAttribute p_termAtt; private readonly IPositionIncrementAttribute p_posIncrAtt; private readonly IPayloadAttribute p_payloadAtt; private readonly IOffsetAttribute p_offsetAtt; private readonly ITypeAttribute p_typeAtt; private readonly IFlagsAttribute p_flagsAtt; public PrefixAwareTokenFilter(TokenStream prefix, TokenStream suffix) : base(suffix) { this.suffix = suffix; this.prefix = prefix; prefixExhausted = false; termAtt = AddAttribute<ICharTermAttribute>(); posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); payloadAtt = AddAttribute<IPayloadAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); typeAtt = AddAttribute<ITypeAttribute>(); flagsAtt = AddAttribute<IFlagsAttribute>(); p_termAtt = prefix.AddAttribute<ICharTermAttribute>(); p_posIncrAtt = prefix.AddAttribute<IPositionIncrementAttribute>(); p_payloadAtt = prefix.AddAttribute<IPayloadAttribute>(); p_offsetAtt = prefix.AddAttribute<IOffsetAttribute>(); p_typeAtt = prefix.AddAttribute<ITypeAttribute>(); p_flagsAtt = prefix.AddAttribute<IFlagsAttribute>(); } private readonly Token previousPrefixToken = new Token(); private readonly Token reusableToken = new Token(); private bool prefixExhausted; public override sealed bool IncrementToken() { Token nextToken; // LUCENENET: IDE0059: Remove unnecessary value assignment if (!prefixExhausted) { nextToken = GetNextPrefixInputToken(reusableToken); if (nextToken is null) { prefixExhausted = true; } else { previousPrefixToken.Reinit(nextToken); // Make it a deep copy BytesRef p = previousPrefixToken.Payload; if (p != null) { previousPrefixToken.Payload = (BytesRef)p.Clone(); } SetCurrentToken(nextToken); return true; } } nextToken = GetNextSuffixInputToken(reusableToken); if (nextToken is null) { return false; } nextToken = UpdateSuffixToken(nextToken, previousPrefixToken); SetCurrentToken(nextToken); return true; } private void SetCurrentToken(Token token) { if (token is null) { return; } ClearAttributes(); termAtt.CopyBuffer(token.Buffer, 0, token.Length); posIncrAtt.PositionIncrement = token.PositionIncrement; flagsAtt.Flags = token.Flags; offsetAtt.SetOffset(token.StartOffset, token.EndOffset); typeAtt.Type = token.Type; payloadAtt.Payload = token.Payload; } private Token GetNextPrefixInputToken(Token token) { if (!prefix.IncrementToken()) { return null; } token.CopyBuffer(p_termAtt.Buffer, 0, p_termAtt.Length); token.PositionIncrement = p_posIncrAtt.PositionIncrement; token.Flags = p_flagsAtt.Flags; token.SetOffset(p_offsetAtt.StartOffset, p_offsetAtt.EndOffset); token.Type = p_typeAtt.Type; token.Payload = p_payloadAtt.Payload; return token; } private Token GetNextSuffixInputToken(Token token) { if (!suffix.IncrementToken()) { return null; } token.CopyBuffer(termAtt.Buffer, 0, termAtt.Length); token.PositionIncrement = posIncrAtt.PositionIncrement; token.Flags = flagsAtt.Flags; token.SetOffset(offsetAtt.StartOffset, offsetAtt.EndOffset); token.Type = typeAtt.Type; token.Payload = payloadAtt.Payload; return token; } /// <summary> /// The default implementation adds last prefix token end offset to the suffix token start and end offsets. /// </summary> /// <param name="suffixToken"> a token from the suffix stream </param> /// <param name="lastPrefixToken"> the last token from the prefix stream </param> /// <returns> consumer token </returns> public virtual Token UpdateSuffixToken(Token suffixToken, Token lastPrefixToken) { suffixToken.SetOffset(lastPrefixToken.EndOffset + suffixToken.StartOffset, lastPrefixToken.EndOffset + suffixToken.EndOffset); return suffixToken; } public override void End() { prefix.End(); suffix.End(); } protected override void Dispose(bool disposing) { if (disposing) { prefix.Dispose(); suffix.Dispose(); } } public override void Reset() { base.Reset(); if (prefix != null) { prefixExhausted = false; prefix.Reset(); } if (suffix != null) { suffix.Reset(); } } public virtual TokenStream Prefix { get => prefix; set => this.prefix = value; } public virtual TokenStream Suffix { get => suffix; set => this.suffix = value; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Xml.Serialization; using System.Xml; using System.Xml.Schema; using System.Diagnostics.CodeAnalysis; using System.Diagnostics; namespace System.ServiceModel.Syndication { internal delegate InlineCategoriesDocument CreateInlineCategoriesDelegate(); internal delegate ReferencedCategoriesDocument CreateReferencedCategoriesDelegate(); [XmlRoot(ElementName = App10Constants.Service, Namespace = App10Constants.Namespace)] public class AtomPub10ServiceDocumentFormatter : ServiceDocumentFormatter, IXmlSerializable { private readonly Type _documentType; private readonly int _maxExtensionSize; public AtomPub10ServiceDocumentFormatter() : this(typeof(ServiceDocument)) { } public AtomPub10ServiceDocumentFormatter(Type documentTypeToCreate) : base() { if (documentTypeToCreate == null) { throw new ArgumentNullException(nameof(documentTypeToCreate)); } if (!typeof(ServiceDocument).IsAssignableFrom(documentTypeToCreate)) { throw new ArgumentException(SR.Format(SR.InvalidObjectTypePassed, nameof(documentTypeToCreate), nameof(ServiceDocument)), nameof(documentTypeToCreate)); } _maxExtensionSize = int.MaxValue; _documentType = documentTypeToCreate; } public AtomPub10ServiceDocumentFormatter(ServiceDocument documentToWrite) : base(documentToWrite) { _maxExtensionSize = int.MaxValue; _documentType = documentToWrite.GetType(); } public override string Version => App10Constants.Namespace; public override bool CanRead(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } return reader.IsStartElement(App10Constants.Service, App10Constants.Namespace); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] XmlSchema IXmlSerializable.GetSchema() => null; [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.ReadXml(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } ReadDocument(reader); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "The IXmlSerializable implementation is only for exposing under WCF DataContractSerializer. The funcionality is exposed to derived class through the ReadFrom\\WriteTo methods")] void IXmlSerializable.WriteXml(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } WriteDocument(writer); } public override void ReadFrom(XmlReader reader) { if (reader == null) { throw new ArgumentNullException(nameof(reader)); } reader.MoveToContent(); if (!CanRead(reader)) { throw new XmlException(SR.Format(SR.UnknownDocumentXml, reader.LocalName, reader.NamespaceURI)); } ReadDocument(reader); } public override void WriteTo(XmlWriter writer) { if (writer == null) { throw new ArgumentNullException(nameof(writer)); } if (Document == null) { throw new InvalidOperationException(SR.DocumentFormatterDoesNotHaveDocument); } writer.WriteStartElement(App10Constants.Prefix, App10Constants.Service, App10Constants.Namespace); WriteDocument(writer); writer.WriteEndElement(); } internal static CategoriesDocument ReadCategories(XmlReader reader, Uri baseUri, CreateInlineCategoriesDelegate inlineCategoriesFactory, CreateReferencedCategoriesDelegate referencedCategoriesFactory, string version, int maxExtensionSize) { string link = reader.GetAttribute(App10Constants.Href, string.Empty); if (string.IsNullOrEmpty(link)) { InlineCategoriesDocument inlineCategories = inlineCategoriesFactory(); ReadInlineCategories(reader, inlineCategories, baseUri, version, maxExtensionSize); return inlineCategories; } else { ReferencedCategoriesDocument referencedCategories = referencedCategoriesFactory(); ReadReferencedCategories(reader, referencedCategories, baseUri, new Uri(link, UriKind.RelativeOrAbsolute), version, maxExtensionSize); return referencedCategories; } } internal static void WriteCategoriesInnerXml(XmlWriter writer, CategoriesDocument categories, Uri baseUri, string version) { Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, categories.BaseUri); if (baseUriToWrite != null) { WriteXmlBase(writer, baseUriToWrite); } if (!string.IsNullOrEmpty(categories.Language)) { WriteXmlLang(writer, categories.Language); } if (categories.IsInline) { WriteInlineCategoriesContent(writer, (InlineCategoriesDocument)categories, version); } else { WriteReferencedCategoriesContent(writer, (ReferencedCategoriesDocument)categories, version); } } protected override ServiceDocument CreateDocumentInstance() { if (_documentType == typeof(ServiceDocument)) { return new ServiceDocument(); } else { return (ServiceDocument)Activator.CreateInstance(_documentType); } } private static void ReadInlineCategories(XmlReader reader, InlineCategoriesDocument inlineCategories, Uri baseUri, string version, int maxExtensionSize) { inlineCategories.BaseUri = baseUri; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { inlineCategories.BaseUri = FeedUtils.CombineXmlBase(inlineCategories.BaseUri, reader.Value); } else if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { inlineCategories.Language = reader.Value; } else if (reader.LocalName == App10Constants.Fixed && reader.NamespaceURI == string.Empty) { inlineCategories.IsFixed = (reader.Value == "yes"); } else if (reader.LocalName == Atom10Constants.SchemeTag && reader.NamespaceURI == string.Empty) { inlineCategories.Scheme = reader.Value; } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, inlineCategories, version)) { inlineCategories.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } SyndicationFeedFormatter.MoveToStartElement(reader); bool isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement(); if (!isEmptyElement) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (reader.IsStartElement(Atom10Constants.CategoryTag, Atom10Constants.Atom10Namespace)) { SyndicationCategory category = CreateCategory(inlineCategories); Atom10FeedFormatter.ReadCategory(reader, category, version, preserveAttributeExtensions: true, preserveElementExtensions: true, maxExtensionSize); if (category.Scheme == null) { category.Scheme = inlineCategories.Scheme; } inlineCategories.Categories.Add(category); } else if (!TryParseElement(reader, inlineCategories, version)) { SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, inlineCategories); } finally { extWriter?.Close(); } reader.ReadEndElement(); } } private static void ReadReferencedCategories(XmlReader reader, ReferencedCategoriesDocument referencedCategories, Uri baseUri, Uri link, string version, int maxExtensionSize) { referencedCategories.BaseUri = baseUri; referencedCategories.Link = link; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { referencedCategories.BaseUri = FeedUtils.CombineXmlBase(referencedCategories.BaseUri, reader.Value); } else if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { referencedCategories.Language = reader.Value; } else if (reader.LocalName == App10Constants.Href && reader.NamespaceURI == string.Empty) { continue; } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, referencedCategories, version)) { referencedCategories.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } reader.MoveToElement(); bool isEmptyElement = reader.IsEmptyElement; reader.ReadStartElement(); if (!isEmptyElement) { XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; try { while (reader.IsStartElement()) { if (!TryParseElement(reader, referencedCategories, version)) { SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, referencedCategories); } finally { extWriter?.Close(); } reader.ReadEndElement(); } } private static void WriteCategories(XmlWriter writer, CategoriesDocument categories, Uri baseUri, string version) { writer.WriteStartElement(App10Constants.Prefix, App10Constants.Categories, App10Constants.Namespace); WriteCategoriesInnerXml(writer, categories, baseUri, version); writer.WriteEndElement(); } private static void WriteInlineCategoriesContent(XmlWriter writer, InlineCategoriesDocument categories, string version) { if (!string.IsNullOrEmpty(categories.Scheme)) { writer.WriteAttributeString(Atom10Constants.SchemeTag, categories.Scheme); } // by default, categories are not fixed if (categories.IsFixed) { writer.WriteAttributeString(App10Constants.Fixed, "yes"); } WriteAttributeExtensions(writer, categories, version); for (int i = 0; i < categories.Categories.Count; ++i) { Atom10FeedFormatter.WriteCategory(writer, categories.Categories[i], version); } WriteElementExtensions(writer, categories, version); } private static void WriteReferencedCategoriesContent(XmlWriter writer, ReferencedCategoriesDocument categories, string version) { if (categories.Link != null) { writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(categories.Link)); } WriteAttributeExtensions(writer, categories, version); WriteElementExtensions(writer, categories, version); } private static void WriteXmlBase(XmlWriter writer, Uri baseUri) { writer.WriteAttributeString("xml", "base", Atom10FeedFormatter.XmlNs, FeedUtils.GetUriString(baseUri)); } private static void WriteXmlLang(XmlWriter writer, string lang) { writer.WriteAttributeString("xml", nameof(lang), Atom10FeedFormatter.XmlNs, lang); } private ResourceCollectionInfo ReadCollection(XmlReader reader, Workspace workspace) { ResourceCollectionInfo result = CreateCollection(workspace); result.BaseUri = workspace.BaseUri; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value); } else if (reader.LocalName == App10Constants.Href && reader.NamespaceURI == string.Empty) { result.Link = new Uri(reader.Value, UriKind.RelativeOrAbsolute); } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; reader.ReadStartElement(); try { while (reader.IsStartElement()) { if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace)) { result.Title = Atom10FeedFormatter.ReadTextContentFrom(reader, "//app:service/app:workspace/app:collection/atom:title[@type]", preserveAttributeExtensions: true); } else if (reader.IsStartElement(App10Constants.Categories, App10Constants.Namespace)) { result.Categories.Add(ReadCategories(reader, result.BaseUri, () => CreateInlineCategories(result), () => CreateReferencedCategories(result), Version, _maxExtensionSize)); } else if (reader.IsStartElement(App10Constants.Accept, App10Constants.Namespace)) { result.Accepts.Add(reader.ReadElementString()); } else if (!TryParseElement(reader, result, Version)) { SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, result); } finally { extWriter?.Close(); } reader.ReadEndElement(); return result; } private void ReadDocument(XmlReader reader) { ServiceDocument result = CreateDocumentInstance(); try { SyndicationFeedFormatter.MoveToStartElement(reader); bool elementIsEmpty = reader.IsEmptyElement; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "lang" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { result.Language = reader.Value; } else if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { result.BaseUri = new Uri(reader.Value, UriKind.RelativeOrAbsolute); } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; reader.ReadStartElement(); if (!elementIsEmpty) { try { while (reader.IsStartElement()) { if (reader.IsStartElement(App10Constants.Workspace, App10Constants.Namespace)) { result.Workspaces.Add(ReadWorkspace(reader, result)); } else if (!TryParseElement(reader, result, Version)) { SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, result); } finally { extWriter?.Close(); } } reader.ReadEndElement(); } catch (FormatException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e); } catch (ArgumentException e) { throw new XmlException(FeedUtils.AddLineInfo(reader, SR.ErrorParsingDocument), e); } SetDocument(result); } private Workspace ReadWorkspace(XmlReader reader, ServiceDocument document) { Workspace result = CreateWorkspace(document); result.BaseUri = document.BaseUri; if (reader.HasAttributes) { while (reader.MoveToNextAttribute()) { if (reader.LocalName == "base" && reader.NamespaceURI == Atom10FeedFormatter.XmlNs) { result.BaseUri = FeedUtils.CombineXmlBase(result.BaseUri, reader.Value); } else { string ns = reader.NamespaceURI; string name = reader.LocalName; if (FeedUtils.IsXmlns(name, ns) || FeedUtils.IsXmlSchemaType(name, ns)) { continue; } string val = reader.Value; if (!TryParseAttribute(name, ns, val, result, Version)) { result.AttributeExtensions.Add(new XmlQualifiedName(reader.LocalName, reader.NamespaceURI), reader.Value); } } } } XmlBuffer buffer = null; XmlDictionaryWriter extWriter = null; reader.ReadStartElement(); try { while (reader.IsStartElement()) { if (reader.IsStartElement(Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace)) { result.Title = Atom10FeedFormatter.ReadTextContentFrom(reader, "//app:service/app:workspace/atom:title[@type]", preserveAttributeExtensions: true); } else if (reader.IsStartElement(App10Constants.Collection, App10Constants.Namespace)) { result.Collections.Add(ReadCollection(reader, result)); } else if (!TryParseElement(reader, result, Version)) { SyndicationFeedFormatter.CreateBufferIfRequiredAndWriteNode(ref buffer, ref extWriter, reader, _maxExtensionSize); } } LoadElementExtensions(buffer, extWriter, result); } finally { extWriter?.Close(); } reader.ReadEndElement(); return result; } private void WriteCollection(XmlWriter writer, ResourceCollectionInfo collection, Uri baseUri) { writer.WriteStartElement(App10Constants.Prefix, App10Constants.Collection, App10Constants.Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, collection.BaseUri); if (baseUriToWrite != null) { baseUri = collection.BaseUri; WriteXmlBase(writer, baseUriToWrite); } if (collection.Link != null) { writer.WriteAttributeString(App10Constants.Href, FeedUtils.GetUriString(collection.Link)); } WriteAttributeExtensions(writer, collection, Version); if (collection.Title != null) { collection.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); } for (int i = 0; i < collection.Accepts.Count; ++i) { writer.WriteElementString(App10Constants.Prefix, App10Constants.Accept, App10Constants.Namespace, collection.Accepts[i]); } for (int i = 0; i < collection.Categories.Count; ++i) { WriteCategories(writer, collection.Categories[i], baseUri, Version); } WriteElementExtensions(writer, collection, Version); writer.WriteEndElement(); } private void WriteDocument(XmlWriter writer) { // declare the atom10 namespace upfront for compactness writer.WriteAttributeString(Atom10Constants.Atom10Prefix, Atom10FeedFormatter.XmlNsNs, Atom10Constants.Atom10Namespace); if (!string.IsNullOrEmpty(Document.Language)) { WriteXmlLang(writer, Document.Language); } Uri baseUri = Document.BaseUri; if (baseUri != null) { WriteXmlBase(writer, baseUri); } WriteAttributeExtensions(writer, Document, Version); for (int i = 0; i < Document.Workspaces.Count; ++i) { WriteWorkspace(writer, Document.Workspaces[i], baseUri); } WriteElementExtensions(writer, Document, Version); } private void WriteWorkspace(XmlWriter writer, Workspace workspace, Uri baseUri) { writer.WriteStartElement(App10Constants.Prefix, App10Constants.Workspace, App10Constants.Namespace); Uri baseUriToWrite = FeedUtils.GetBaseUriToWrite(baseUri, workspace.BaseUri); if (baseUriToWrite != null) { baseUri = workspace.BaseUri; WriteXmlBase(writer, baseUriToWrite); } WriteAttributeExtensions(writer, workspace, Version); if (workspace.Title != null) { workspace.Title.WriteTo(writer, Atom10Constants.TitleTag, Atom10Constants.Atom10Namespace); } for (int i = 0; i < workspace.Collections.Count; ++i) { WriteCollection(writer, workspace.Collections[i], baseUri); } WriteElementExtensions(writer, workspace, Version); writer.WriteEndElement(); } } [XmlRoot(ElementName = App10Constants.Service, Namespace = App10Constants.Namespace)] public class AtomPub10ServiceDocumentFormatter<TServiceDocument> : AtomPub10ServiceDocumentFormatter where TServiceDocument : ServiceDocument, new() { public AtomPub10ServiceDocumentFormatter() : base(typeof(TServiceDocument)) { } public AtomPub10ServiceDocumentFormatter(TServiceDocument documentToWrite) : base(documentToWrite) { } protected override ServiceDocument CreateDocumentInstance() => new TServiceDocument(); } }
/* ==================================================================== 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.UserModel { using NPOI.DDF; using NPOI.SS; using NPOI.SS.UserModel; using System; /// <summary> /// A client anchor Is attached to an excel worksheet. It anchors against a /// top-left and buttom-right cell. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> public class HSSFClientAnchor : HSSFAnchor, IClientAnchor { public static int MAX_COL = SpreadsheetVersion.EXCEL97.LastColumnIndex; public static int MAX_ROW = SpreadsheetVersion.EXCEL97.LastRowIndex; private EscherClientAnchorRecord _escherClientAnchor; public HSSFClientAnchor(EscherClientAnchorRecord escherClientAnchorRecord) { this._escherClientAnchor = escherClientAnchorRecord; } /// <summary> /// Creates a new client anchor and defaults all the anchor positions to 0. /// </summary> public HSSFClientAnchor() { //Is this necessary? this._escherClientAnchor = new EscherClientAnchorRecord(); } /// <summary> /// Creates a new client anchor and Sets the top-left and bottom-right /// coordinates of the anchor. /// /// Note: Microsoft Excel seems to sometimes disallow /// higher y1 than y2 or higher x1 than x2 in the anchor, you might need to /// reverse them and draw shapes vertically or horizontally flipped! /// </summary> /// <param name="dx1">the x coordinate within the first cell.</param> /// <param name="dy1">the y coordinate within the first cell.</param> /// <param name="dx2">the x coordinate within the second cell.</param> /// <param name="dy2">the y coordinate within the second cell.</param> /// <param name="col1">the column (0 based) of the first cell.</param> /// <param name="row1">the row (0 based) of the first cell.</param> /// <param name="col2">the column (0 based) of the second cell.</param> /// <param name="row2">the row (0 based) of the second cell.</param> public HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) : base(dx1, dy1, dx2, dy2) { CheckRange(dx1, 0, 1023, "dx1"); CheckRange(dx2, 0, 1023, "dx2"); CheckRange(dy1, 0, 255, "dy1"); CheckRange(dy2, 0, 255, "dy2"); CheckRange(col1, 0, MAX_COL, "col1"); CheckRange(col2, 0, MAX_COL, "col2"); CheckRange(row1, 0, MAX_ROW, "row1"); CheckRange(row2, 0, MAX_ROW, "row2"); Col1 = ((short)Math.Min(col1, col2)); Col2 = ((short)Math.Max(col1, col2)); Row1 = Math.Min(row1, row2); Row2 = Math.Max(row1, row2); if (col1 > col2) { _isHorizontallyFlipped = true; } if (row1 > row2) { _isVerticallyFlipped = true; } } /// <summary> /// Calculates the height of a client anchor in points. /// </summary> /// <param name="sheet">the sheet the anchor will be attached to</param> /// <returns>the shape height.</returns> public float GetAnchorHeightInPoints(NPOI.SS.UserModel.ISheet sheet) { int y1 = Dy1; int y2 = Dy2; int row1 = Math.Min(Row1, Row2); int row2 = Math.Max(Row1, Row2); float points = 0; if (row1 == row2) { points = ((y2 - y1) / 256.0f) * GetRowHeightInPoints(sheet, row2); } else { points += ((256.0f - y1) / 256.0f) * GetRowHeightInPoints(sheet, row1); for (int i = row1 + 1; i < row2; i++) { points += GetRowHeightInPoints(sheet, i); } points += (y2 / 256.0f) * GetRowHeightInPoints(sheet, row2); } return points; } /// <summary> /// Gets the row height in points. /// </summary> /// <param name="sheet">The sheet.</param> /// <param name="rowNum">The row num.</param> /// <returns></returns> private float GetRowHeightInPoints(NPOI.SS.UserModel.ISheet sheet, int rowNum) { NPOI.SS.UserModel.IRow row = sheet.GetRow(rowNum); if (row == null) return sheet.DefaultRowHeightInPoints; else return row.HeightInPoints; } /// <summary> /// Gets or sets the col1. /// </summary> /// <value>The col1.</value> public int Col1 { get { return _escherClientAnchor.Col1; } set { CheckRange(value, 0, MAX_COL, "col1"); _escherClientAnchor.Col1 = (short)value; } } /// <summary> /// Gets or sets the col2. /// </summary> /// <value>The col2.</value> public int Col2 { get { return _escherClientAnchor.Col2; } set { CheckRange(value, 0, MAX_COL, "col2"); _escherClientAnchor.Col2 = (short)value; } } /// <summary> /// Gets or sets the row1. /// </summary> /// <value>The row1.</value> public int Row1 { get { return unsignedValue(_escherClientAnchor.Row1); } set { CheckRange(value, 0, MAX_ROW, "row1"); _escherClientAnchor.Row1 = (short)value; } } /// <summary> /// Gets or sets the row2. /// </summary> /// <value>The row2.</value> public int Row2 { get { return unsignedValue(_escherClientAnchor.Row2); } set { CheckRange(value, 0, MAX_ROW, "row2"); _escherClientAnchor.Row2 = (short)value; } } /// <summary> /// Sets the top-left and bottom-right /// coordinates of the anchor /// /// Note: Microsoft Excel seems to sometimes disallow /// higher y1 than y2 or higher x1 than x2 in the anchor, you might need to /// reverse them and draw shapes vertically or horizontally flipped! /// </summary> /// <param name="col1">the column (0 based) of the first cell.</param> /// <param name="row1"> the row (0 based) of the first cell.</param> /// <param name="x1">the x coordinate within the first cell.</param> /// <param name="y1">the y coordinate within the first cell.</param> /// <param name="col2">the column (0 based) of the second cell.</param> /// <param name="row2">the row (0 based) of the second cell.</param> /// <param name="x2">the x coordinate within the second cell.</param> /// <param name="y2">the y coordinate within the second cell.</param> public void SetAnchor(short col1, int row1, int x1, int y1, short col2, int row2, int x2, int y2) { CheckRange(x1, 0, 1023, "dx1"); CheckRange(x2, 0, 1023, "dx2"); CheckRange(y1, 0, 255, "dy1"); CheckRange(y2, 0, 255, "dy2"); CheckRange(col1, 0, MAX_COL, "col1"); CheckRange(col2, 0, MAX_COL, "col2"); CheckRange(row1, 0, MAX_ROW, "row1"); CheckRange(row2, 0, MAX_ROW, "row2"); this.Col1 = col1; this.Row1 = row1; this.Dx1 = x1; this.Dy1 = y1; this.Col2 = col2; this.Row2 = row2; this.Dx2 = x2; this.Dy2 = y2; } /// <summary> /// Gets a value indicating whether this instance is horizontally flipped. /// </summary> /// <value> /// <c>true</c> if the anchor goes from right to left; otherwise, <c>false</c>. /// </value> public override bool IsHorizontallyFlipped { get { return _isHorizontallyFlipped; } } /// <summary> /// Gets a value indicating whether this instance is vertically flipped. /// </summary> /// <value> /// <c>true</c> if the anchor goes from bottom to top.; otherwise, <c>false</c>. /// </value> public override bool IsVerticallyFlipped { get { return _isVerticallyFlipped; } } /// <summary> /// Gets the anchor type /// 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells. /// </summary> /// <value>The type of the anchor.</value> public AnchorType AnchorType { get { return (AnchorType)_escherClientAnchor.Flag; } set { this._escherClientAnchor.Flag = (short)value; } } /// <summary> /// Checks the range. /// </summary> /// <param name="value">The value.</param> /// <param name="minRange">The min range.</param> /// <param name="maxRange">The max range.</param> /// <param name="varName">Name of the variable.</param> private void CheckRange(int value, int minRange, int maxRange, String varName) { if (value < minRange || value > maxRange) throw new ArgumentOutOfRangeException(varName + " must be between " + minRange + " and " + maxRange + ", but was: " + value); } internal override EscherRecord GetEscherAnchor() { return _escherClientAnchor; } protected override void CreateEscherAnchor() { _escherClientAnchor = new EscherClientAnchorRecord(); } /** * Given a 16-bit unsigned integer stored in a short, return the unsigned value. * * @param s A 16-bit value intended to be interpreted as an unsigned integer. * @return The value represented by <code>s</code>. */ private static int unsignedValue(short s) { return (s < 0 ? 0x10000 + s : s); } public override bool Equals(Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.GetType() != GetType()) return false; HSSFClientAnchor anchor = (HSSFClientAnchor)obj; return anchor.Col1 == Col1 && anchor.Col2 == Col2 && anchor.Dx1 == Dx1 && anchor.Dx2 == Dx2 && anchor.Dy1 == Dy1 && anchor.Dy2 == Dy2 && anchor.Row1 == Row1 && anchor.Row2 == Row2 && anchor.AnchorType == AnchorType; } public override int GetHashCode() { return Col1.GetHashCode() ^ Col2.GetHashCode() ^ Dx1.GetHashCode() ^ Dx2.GetHashCode() ^ Dy1.GetHashCode() ^ Dy2.GetHashCode() ^Row1.GetHashCode() ^ Row2.GetHashCode() ^ AnchorType.GetHashCode(); } public override int Dx1 { get { return _escherClientAnchor.Dx1; } set { _escherClientAnchor.Dx1 = (short)value; } } public override int Dx2 { get { return _escherClientAnchor.Dx2; } set { _escherClientAnchor.Dx2 = (short)value; } } public override int Dy1 { get { return _escherClientAnchor.Dy1; } set { _escherClientAnchor.Dy1 = (short)value; } } public override int Dy2 { get { return _escherClientAnchor.Dy2; } set { _escherClientAnchor.Dy2 = (short)value; } } } }
using UnityEngine; using UnityEngine.Events; using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; using System; namespace JordiBisbal.EventManager { /// <summary> /// Dispatch messages to subcribers, by broadcasting to the subscribers o by delivering just to one of them /// For targeted events "@", the name, and the instance id of the target is add to the event name /// </summary> public class EventManager : EventManagerInterface { /// <summary> /// Messages that EventManager sends by itself /// </summary> public const string update = "EventManager.update"; public const string allwaysUpdate = "EventManager.allwaysUpdate"; public const string log = "EventManager.log"; /// <summary> /// Should debug all events ? /// </summary> public bool myDebugEvents = false; /// <summary> /// Should debug all events ? /// </summary> public bool debugEvents { get { return myDebugEvents; } set { myDebugEvents = value; } } /// <summary> /// Stored the subcribers lists /// </summary> Dictionary<string, ParametrizedEvents> eventDictionary = new Dictionary<string, ParametrizedEvents>(); /// <summary> /// Subscribers list /// </summary> Dictionary<string, ArrayList> subscribers = new Dictionary<string, ArrayList>(); /// <summary> /// Delayed events /// </summary> ArrayList delayedEvents = new ArrayList(); /// <summary> /// Return the current time (based on game start) /// </summary> Func<float> timeProviderDelegate; public EventManager(Func<float> timeProviderDelegate = null) { this.timeProviderDelegate = timeProviderDelegate; } /// <summary> /// Subscribe a given object to an event, either for targeted or not events, the even if subscribed as subscriber so all /// event subscribed this way, can be freed by just calling to StopListering(subscriber) /// </summary> /// <param name="subscriber">Object the event system will use the instance Id to subscribe, this will be used when unsubscribing</param> /// <param name="eventName">Name of the event the listener will respond to</param> /// <param name="listener">Listener Action to catch the event</param> /// <param name="target">If </param> public void StartListening(UnityEngine.Object subscriber, string eventName, UnityAction<object> listener, UnityEngine.Object target = null) { string key = "" + subscriber.GetInstanceID(); if (! subscribers.ContainsKey(key)) { subscribers.Add(key, new ArrayList()); } ArrayList namedEvents; subscribers.TryGetValue(key, out namedEvents); namedEvents.Add(new OwnedListener(subscriber, listener, eventName, target)); StartListening(eventName, listener, target); } /// <summary> /// Attaches a callback to eventName, ei. starts listening for eventName. /// If a target is specified, then just targeted events will be received, if no target is specified, targeted events will not be attached (received) /// To free the event registration, StopListering(eventName, listener) must be called, ie. the unsubcription needs booth the event name and the callback to be done /// </summary> /// <param name="eventName">The event name</param> /// <param name="listener">The callback to be called</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void StartListening(string eventName, UnityAction<object> listener, UnityEngine.Object target = null) { ParametrizedEvents thisEvent = null; assertEventNameIsValid(eventName); eventName = targetedEventName(eventName, target); if (! eventDictionary.TryGetValue(eventName, out thisEvent)) { thisEvent = new ParametrizedEvents(); eventDictionary.Add(eventName, thisEvent); } thisEvent.AddListener(listener); DebugEvent("Event listener added : " + eventName); } /// <summary> /// Logs the event /// </summary> /// <param name="eventName">Message to log</param> private void DebugEvent(string message) { if (myDebugEvents) { Debug.Log(message); } } /// <summary> /// Unsubstibe to all events that where subscribed as subscriber /// </summary> /// <param name="subscriber"></param> public void StopListening(UnityEngine.Object subscriber) { // On stop listening it is ok to ignore if no singleton is already created as we could disable an object before the singleton is instantiated string key = "" + subscriber.GetInstanceID(); if (!subscribers.ContainsKey(key)) { return; } ArrayList ownedEvents; subscribers.TryGetValue(key, out ownedEvents); foreach (OwnedListener ownedListener in ownedEvents) { StopListening(ownedListener.eventName, ownedListener.listener, ownedListener.target); } subscribers.Remove(key); } /// <summary> /// Deataches the given listener to eventName event. /// If a target is specified, then just targeted events will be dettached, if no target is specified, targeted events will not be dettached. /// </summary> /// <param name="eventName">The event name</param> /// <param name="listener">The callback to be called</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void StopListening(string eventName, UnityAction<object> listener, UnityEngine.Object target = null) { assertEventNameIsValid(eventName); eventName = targetedEventName(eventName, target); ParametrizedEvents thisEvent = null; if (eventDictionary.TryGetValue(eventName, out thisEvent)) { thisEvent.RemoveListener(listener); } } /// <summary> /// Deattaches all events (targeted or not) at wich listener is attached /// </summary> /// <param name="listener"></param> public void StopListening(UnityAction<object> listener) { foreach (KeyValuePair<string, ParametrizedEvents> thisEvent in eventDictionary) { thisEvent.Value.RemoveListener(listener); } } /// <summary> /// Sends the message to all attached listeners /// </summary> /// <param name="eventName">The event name</param> /// <param name="message">The message to be passed</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void TriggerEvent(string eventName, object message = null, UnityEngine.Object target = null) { assertEventNameIsValid(eventName); eventName = targetedEventName(eventName, target); DebugEvent("Event triggered : " + eventName); ParametrizedEvents thisEvent = null; if (eventDictionary.TryGetValue(eventName, out thisEvent)) { thisEvent.Invoke(message); } } /// <summary> /// Counts attached listeners /// </summary> /// <param name="eventName">The event name</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public int ListenerCount(string eventName, UnityEngine.Object target = null) { assertEventNameIsValid(eventName); eventName = targetedEventName(eventName, target); DebugEvent("Event triggered : " + eventName); ParametrizedEvents thisEvent = null; if (eventDictionary.TryGetValue(eventName, out thisEvent)) { return thisEvent.Count(); } return 0; } /// <summary> /// Counts all attached listeners /// </summary> public int ListenerCount() { int total = 0; foreach (ParametrizedEvents paremitrizedEvents in eventDictionary.Values) { total = total + paremitrizedEvents.Count(); } return total; } /// <summary> /// Sends a message after some amount of time, that is done on allwaysUpdate loop, so the precision is the one of that. /// </summary> /// <param name="time">Sends the message after time seconds</param> /// <param name="eventName">The event name</param> /// <param name="listener">The callback to be called</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void TriggerEventAfter(float time, string eventName, object message, UnityEngine.Object target = null) { delayedEvents.Add(new DelayedEvent(eventName, message, target, GetTime() + time)); } /// <summary> /// Calculates the targeted event name for an event /// </summary> /// <param name="eventName">The event name</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> /// <returns></returns> private string targetedEventName(string eventName, UnityEngine.Object target) { if (target == null) { return eventName; } return eventName + "@" + target.name + "(" + target.GetInstanceID() + ")"; } /// <summary> /// Checks if the eventName is valid or nor /// </summary> /// <param name="eventName">Event name</param> private static void assertEventNameIsValid(string eventName) { // Fucked bastards !!! Another regex dialect ? Really ??? :( if (!(new Regex(@"^[\w./:+]+$").IsMatch(eventName))) { throw new InvalidEventNameException("Invalid event name \"" + eventName + "\""); }; } /// <summary> /// Sends a tick messatge to listners subscribed to EventManager.update /// </summary> public void Update() { TriggerEvent(update, null); } /// <summary> /// Sends a tick messatge to listners subscribed to EventManager.allwaysUpdate and delivers delayed events /// </summary> public void AllwaysUpdate() { TriggerEvent(allwaysUpdate, null); float now = GetTime(); for (int i = delayedEvents.Count - 1; i >= 0; i--) { DelayedEvent theEvent = (DelayedEvent)delayedEvents[i]; if (theEvent.when <= now) { TriggerEvent(theEvent.eventName, theEvent.message, theEvent.target); delayedEvents.Remove(theEvent); } } } /// <summary> /// Return the current time /// </summary> /// <returns></returns> private float GetTime() { if (timeProviderDelegate == null) { throw new MissConfiguredException("No time delegate has been provided for this eventManager"); } float now = timeProviderDelegate(); return now; } /// <summary> /// Remove delayed events matching eventName and target /// </summary> /// <param name="eventName">Event name</param> /// <param name="target">Event Target</param> public void FlushDelayedEvents(string eventName, GameObject target = null) { for (int i = delayedEvents.Count - 1; i > 0; i--) { DelayedEvent theEvent = (DelayedEvent)delayedEvents[i]; if ((theEvent.eventName == eventName) && (theEvent.target == target)) { delayedEvents.Remove(theEvent); } } } /// <summary> /// Translates an enum value to be used as event name /// </summary> /// <param name="value">Enum value to translate</param> /// <returns>The enum translated value</returns> private static string EnumToString(Enum value) { return value.GetType().FullName + ":" + (Enum.GetName(value.GetType(), value)); } /// <summary> /// Subscribe a given object to an event, either for targeted or not events, the even if subscribed as subscriber so all /// event subscribed this way, can be freed by just calling to StopListering(subscriber) /// </summary> /// <param name="subscriber">Object the event system will use the instance Id to subscribe, this will be used when unsubscribing</param> /// <param name="eventName">Enum to use as event name</param> /// <param name="listener">Listener Action to catch the event</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event </param> public void StartListening(UnityEngine.Object subscriber, Enum eventName, UnityAction<object> listener, UnityEngine.Object target = null) { StartListening(subscriber, EnumToString(eventName), listener, target); } /// <summary> /// Attaches a callback to eventName, ei. starts listening for eventName. /// If a target is specified, then just targeted events will be received, if no target is specified, targeted events will not be attached (received) /// To free the event registration, StopListering(eventName, listener) must be called, ie. the unsubcription needs booth the event name and the callback to be done /// </summary> /// <param name="eventName">The event name</param> /// <param name="listener">The callback to be called</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void StartListening(Enum eventName, UnityAction<object> listener, UnityEngine.Object target = null) { StartListening(EnumToString(eventName), listener, target); } /// <summary> /// Sends the message to all attached listeners /// </summary> /// <param name="eventName">The enum to use as event name</param> /// <param name="message">The message to be passed</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void TriggerEvent(Enum eventName, object message = null, UnityEngine.Object target = null) { TriggerEvent(EnumToString(eventName), message, target); } /// <summary> /// Counts attached listeners /// </summary> /// <param name="eventName">The enum to use as event name</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public int ListenerCount(Enum eventName, UnityEngine.Object target = null) { return ListenerCount(EnumToString(eventName), target); } /// <summary> /// Sends a message after some amount of time, that is done on allwaysUpdate loop, so the precision is the one of that. /// </summary> /// <param name="time">Sends the message after time seconds</param> /// <param name="eventName">The enum to use as event name</param> /// <param name="listener">The callback to be called</param> /// <param name="target">If set, the listener will reveice the event only when target is specified on triggering the event</param> public void TriggerEventAfter(float time, Enum eventName, object message, UnityEngine.Object target = null) { TriggerEventAfter(time, EnumToString(eventName), message, target); } /// <summary> /// Remove delayed events matching eventName and target /// </summary> /// <param name="eventName">Enum to use as event name</param> /// <param name="target">Event Target</param> public void FlushDelayedEvents(Enum eventName, GameObject target = null) { FlushDelayedEvents(EnumToString(eventName), target); } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Net.Configuration; using EventStore.Common.Log; using EventStore.Core.Bus; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public class CoreProjectionQueue { private readonly ILogger _logger = LogManager.GetLoggerFor<CoreProjectionQueue>(); private readonly StagedProcessingQueue _queuePendingEvents; private readonly IPublisher _publisher; private readonly Guid _projectionCorrelationId; private readonly int _pendingEventsThreshold; private readonly Action _updateStatistics; private CheckpointTag _lastEnqueuedEventTag; private bool _justInitialized; private bool _subscriptionPaused; public event Action EnsureTickPending { add { _queuePendingEvents.EnsureTickPending += value; } remove { _queuePendingEvents.EnsureTickPending -= value; } } public CoreProjectionQueue( Guid projectionCorrelationId, IPublisher publisher, int pendingEventsThreshold, bool orderedPartitionProcessing, Action updateStatistics = null) { _queuePendingEvents = new StagedProcessingQueue( new[] { true /* record event order - async with ordered output*/, true /* get state partition - ordered as it may change correlation id - sync */, false /* load foreach state - async- unordered completion*/, orderedPartitionProcessing /* process Js - unordered/ordered - inherently unordered/ordered completion*/, true /* write emits - ordered - async ordered completion*/, false /* complete item */ }); _publisher = publisher; _projectionCorrelationId = projectionCorrelationId; _pendingEventsThreshold = pendingEventsThreshold; _updateStatistics = updateStatistics; } public bool IsRunning { get { return _isRunning; } } public bool ProcessEvent() { var processed = false; if (_queuePendingEvents.Count > 0) processed = ProcessOneEventBatch(); return processed; } public int GetBufferedEventCount() { return _queuePendingEvents.Count; } public void EnqueueTask(WorkItem workItem, CheckpointTag workItemCheckpointTag, bool allowCurrentPosition = false) { ValidateQueueingOrder(workItemCheckpointTag, allowCurrentPosition); workItem.SetProjectionQueue(this); workItem.SetCheckpointTag(workItemCheckpointTag); _queuePendingEvents.Enqueue(workItem); } public void EnqueueOutOfOrderTask(WorkItem workItem) { if (_lastEnqueuedEventTag == null) throw new InvalidOperationException( "Cannot enqueue an out-of-order task. The projection position is currently unknown."); workItem.SetProjectionQueue(this); workItem.SetCheckpointTag(_lastEnqueuedEventTag); _queuePendingEvents.Enqueue(workItem); } public void InitializeQueue(CheckpointTag startingPosition) { _subscriptionPaused = false; _unsubscribed = false; _lastReportedStatisticsTimeStamp = default(DateTime); _unsubscribed = false; _subscriptionId = Guid.Empty; _queuePendingEvents.Initialize(); _lastEnqueuedEventTag = startingPosition; _justInitialized = true; } public string GetStatus() { return (_subscriptionPaused ? "/Paused" : ""); } private void ValidateQueueingOrder(CheckpointTag eventTag, bool allowCurrentPosition = false) { if (eventTag < _lastEnqueuedEventTag || (!(allowCurrentPosition || _justInitialized) && eventTag <= _lastEnqueuedEventTag)) throw new InvalidOperationException( string.Format( "Invalid order. Last known tag is: '{0}'. Current tag is: '{1}'", _lastEnqueuedEventTag, eventTag)); _justInitialized = _justInitialized && (eventTag == _lastEnqueuedEventTag); _lastEnqueuedEventTag = eventTag; } private void PauseSubscription() { if (_subscriptionId == Guid.Empty) throw new InvalidOperationException("Not subscribed"); if (!_subscriptionPaused && !_unsubscribed) { _subscriptionPaused = true; _publisher.Publish( new ReaderSubscriptionManagement.Pause(_subscriptionId)); } } private void ResumeSubscription() { if (_subscriptionId == Guid.Empty) throw new InvalidOperationException("Not subscribed"); if (_subscriptionPaused && !_unsubscribed) { _subscriptionPaused = false; _publisher.Publish( new ReaderSubscriptionManagement.Resume(_subscriptionId)); } } private DateTime _lastReportedStatisticsTimeStamp = default(DateTime); private bool _unsubscribed; private Guid _subscriptionId; private bool _isRunning; private bool ProcessOneEventBatch() { if (_queuePendingEvents.Count > _pendingEventsThreshold) PauseSubscription(); var processed = _queuePendingEvents.Process(max: 30); if (_subscriptionPaused && _queuePendingEvents.Count < _pendingEventsThreshold / 2) ResumeSubscription(); if (_updateStatistics != null && ((_queuePendingEvents.Count == 0) || (DateTime.UtcNow - _lastReportedStatisticsTimeStamp).TotalMilliseconds > 500)) _updateStatistics(); _lastReportedStatisticsTimeStamp = DateTime.UtcNow; return processed; } public void Unsubscribed() { _unsubscribed = true; } public void Subscribed(Guid currentSubscriptionId) { if (_unsubscribed) throw new InvalidOperationException("Unsubscribed"); if (_subscriptionId != Guid.Empty) throw new InvalidOperationException("Already subscribed"); _subscriptionId = currentSubscriptionId; } public void SetIsRunning(bool isRunning) { _isRunning = isRunning; } } }
using System; using System.Reflection; using System.Web; using System.Web.UI; namespace umbraco.BusinessLogic { /// <summary> /// The StateHelper class provides general helper methods for handling sessions, context, viewstate and cookies. /// </summary> public class StateHelper { private static HttpContextBase _customHttpContext; /// <summary> /// Gets/sets the HttpContext object, this is generally used for unit testing. By default this will /// use the HttpContext.Current /// </summary> internal static HttpContextBase HttpContext { get { if (_customHttpContext == null && System.Web.HttpContext.Current != null) { //return the current HttpContxt, do NOT store this in the _customHttpContext field //as it will persist across reqeusts! return new HttpContextWrapper(System.Web.HttpContext.Current); } if (_customHttpContext == null && System.Web.HttpContext.Current == null) { throw new NullReferenceException("The HttpContext property has not been set or the object execution is not running inside of an HttpContext"); } return _customHttpContext; } set { _customHttpContext = value; } } #region Session Helpers /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(string key) { return GetSessionValue<T>(HttpContext, key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetSessionValue accepting an HttpContextBase instead")] public static T GetSessionValue<T>(HttpContext context, string key) { return GetSessionValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the session value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetSessionValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Session[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets a session value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(string key, object value) { SetSessionValue(HttpContext, key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetSessionValue accepting an HttpContextBase instead")] public static void SetSessionValue(HttpContext context, string key, object value) { SetSessionValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the session value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetSessionValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Session[key] = value; } #endregion #region Context Helpers /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(string key) { return GetContextValue<T>(HttpContext, key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> [Obsolete("Use the GetContextValue accepting an HttpContextBase instead")] public static T GetContextValue<T>(HttpContext context, string key) { return GetContextValue<T>(new HttpContextWrapper(context), key); } /// <summary> /// Gets the context value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetContextValue<T>(HttpContextBase context, string key) { if (context == null) return default(T); object o = context.Items[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the context value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(string key, object value) { SetContextValue(HttpContext, key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> [Obsolete("Use the SetContextValue accepting an HttpContextBase instead")] public static void SetContextValue(HttpContext context, string key, object value) { SetContextValue(new HttpContextWrapper(context), key, value); } /// <summary> /// Sets the context value. /// </summary> /// <param name="context">The context.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetContextValue(HttpContextBase context, string key, object value) { if (context == null) return; context.Items[key] = value; } #endregion #region ViewState Helpers /// <summary> /// Gets the state bag. /// </summary> /// <returns></returns> private static StateBag GetStateBag() { //if (HttpContext.Current == null) // return null; var page = HttpContext.CurrentHandler as Page; if (page == null) return null; var pageType = typeof(Page); var viewState = pageType.GetProperty("ViewState", BindingFlags.GetProperty | BindingFlags.Instance); if (viewState == null) return null; return viewState.GetValue(page, null) as StateBag; } /// <summary> /// Gets the view state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(string key) { return GetViewStateValue<T>(GetStateBag(), key); } /// <summary> /// Gets a view-state value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <returns></returns> public static T GetViewStateValue<T>(StateBag bag, string key) { if (bag == null) return default(T); object o = bag[key]; if (o == null) return default(T); return (T)o; } /// <summary> /// Sets the view state value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(string key, object value) { SetViewStateValue(GetStateBag(), key, value); } /// <summary> /// Sets the view state value. /// </summary> /// <param name="bag">The bag.</param> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetViewStateValue(StateBag bag, string key, object value) { if (bag != null) bag[key] = value; } #endregion #region Cookie Helpers /// <summary> /// Determines whether a cookie has a value with a specified key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the cookie has a value with the specified key; otherwise, <c>false</c>. /// </returns> [Obsolete("Use !string.IsNullOrEmpty(GetCookieValue(key))", false)] public static bool HasCookieValue(string key) { return !string.IsNullOrEmpty(GetCookieValue(key)); } /// <summary> /// Gets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <returns></returns> public static string GetCookieValue(string key) { if (!Cookies.HasCookies) return null; var cookie = HttpContext.Request.Cookies[key]; return cookie == null ? null : cookie.Value; } /// <summary> /// Sets the cookie value. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public static void SetCookieValue(string key, string value) { SetCookieValue(key, value, 30d); // default Umbraco expires is 30 days } /// <summary> /// Sets the cookie value including the number of days to persist the cookie /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="daysToPersist">How long the cookie should be present in the browser</param> public static void SetCookieValue(string key, string value, double daysToPersist) { if (!Cookies.HasCookies) return; var context = HttpContext; HttpCookie cookie = new HttpCookie(key, value); cookie.Expires = DateTime.Now.AddDays(daysToPersist); context.Response.Cookies.Set(cookie); cookie = context.Request.Cookies[key]; if (cookie != null) cookie.Value = value; } // zb-00004 #29956 : refactor cookies names & handling public static class Cookies { /* * helper class to manage cookies * * beware! SetValue(string value) does _not_ set expires, unless the cookie has been * configured to have one. This allows us to have cookies w/out an expires timespan. * However, default behavior in Umbraco was to set expires to 30days by default. This * must now be managed in the Cookie constructor or by using an overriden SetValue(...). * * we currently reproduce this by configuring each cookie with a 30d expires, but does * that actually make sense? shouldn't some cookie have _no_ expires? */ static readonly Cookie _preview = new Cookie("UMB_PREVIEW", 30d); // was "PreviewSet" static readonly Cookie _userContext = new Cookie("UMB_UCONTEXT", 30d); // was "UserContext" static readonly Cookie _member = new Cookie("UMB_MEMBER", 30d); // was "umbracoMember" public static Cookie Preview { get { return _preview; } } public static Cookie UserContext { get { return _userContext; } } public static Cookie Member { get { return _member; } } public static bool HasCookies { get { var context = HttpContext; // although just checking context should be enough?! // but in some (replaced) umbraco code, everything is checked... return context != null && context.Request != null & context.Request.Cookies != null && context.Response != null && context.Response.Cookies != null; } } public static void ClearAll() { HttpContext.Response.Cookies.Clear(); } public class Cookie { const string cookiesExtensionConfigKey = "umbracoCookiesExtension"; static readonly string _ext; TimeSpan _expires; string _key; static Cookie() { var appSettings = System.Configuration.ConfigurationManager.AppSettings; _ext = appSettings[cookiesExtensionConfigKey] == null ? "" : "_" + (string)appSettings[cookiesExtensionConfigKey]; } public Cookie(string key) : this(key, TimeSpan.Zero, true) { } public Cookie(string key, double days) : this(key, TimeSpan.FromDays(days), true) { } public Cookie(string key, TimeSpan expires) : this(key, expires, true) { } public Cookie(string key, bool appendExtension) : this(key, TimeSpan.Zero, appendExtension) { } public Cookie(string key, double days, bool appendExtension) : this(key, TimeSpan.FromDays(days), appendExtension) { } public Cookie(string key, TimeSpan expires, bool appendExtension) { _key = appendExtension ? key + _ext : key; _expires = expires; } public string Key { get { return _key; } } public bool HasValue { get { return RequestCookie != null; } } public string GetValue() { return RequestCookie == null ? null : RequestCookie.Value; } public void SetValue(string value) { SetValueWithDate(value, DateTime.Now + _expires); } public void SetValue(string value, double days) { SetValue(value, DateTime.Now.AddDays(days)); } public void SetValue(string value, TimeSpan expires) { SetValue(value, DateTime.Now + expires); } public void SetValue(string value, DateTime expires) { SetValueWithDate(value, expires); } private void SetValueWithDate(string value, DateTime expires) { HttpCookie cookie = new HttpCookie(_key, value); if (GlobalSettings.UseSSL) cookie.Secure = true; //ensure http only, this should only be able to be accessed via the server cookie.HttpOnly = true; cookie.Expires = expires; ResponseCookie = cookie; // original Umbraco code also does this // so we can GetValue() back what we previously set cookie = RequestCookie; if (cookie != null) cookie.Value = value; } public void Clear() { if (RequestCookie != null || ResponseCookie != null) { HttpCookie cookie = new HttpCookie(_key); cookie.Expires = DateTime.Now.AddDays(-1); ResponseCookie = cookie; } } public void Remove() { // beware! will not clear browser's cookie // you probably want to use .Clear() HttpContext.Response.Cookies.Remove(_key); } public HttpCookie RequestCookie { get { return HttpContext.Request.Cookies[_key]; } } public HttpCookie ResponseCookie { get { return HttpContext.Response.Cookies[_key]; } set { // .Set() ensures the uniqueness of cookies in the cookie collection // ie it is the same as .Remove() + .Add() -- .Add() allows duplicates HttpContext.Response.Cookies.Set(value); } } } } #endregion } }
namespace Microsoft.Azure.Management.PowerBIEmbedded { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Client to manage your Power BI embedded workspace collections and /// retrieve workspaces. /// </summary> public partial class PowerBIEmbeddedManagementClient : ServiceClient<PowerBIEmbeddedManagementClient>, IPowerBIEmbeddedManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IWorkspaceCollectionsOperations. /// </summary> public virtual IWorkspaceCollectionsOperations WorkspaceCollections { get; private set; } /// <summary> /// Gets the IWorkspacesOperations. /// </summary> public virtual IWorkspacesOperations Workspaces { get; private set; } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PowerBIEmbeddedManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PowerBIEmbeddedManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected PowerBIEmbeddedManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected PowerBIEmbeddedManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PowerBIEmbeddedManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PowerBIEmbeddedManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PowerBIEmbeddedManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PowerBIEmbeddedManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public PowerBIEmbeddedManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.WorkspaceCollections = new WorkspaceCollectionsOperations(this); this.Workspaces = new WorkspacesOperations(this); this.BaseUri = new Uri("http://management.azure.com"); this.ApiVersion = "2016-01-29"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Indicates which operations can be performed by the Power BI Resource /// Provider. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationList>> GetAvailableOperationsWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.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, "GetAvailableOperations", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.PowerBI/operations").ToString(); List<string> _queryParameters = new List<string>(); if (this.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<OperationList>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<OperationList>(_responseContent, this.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// 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.IO; using System.Linq; using System.ServiceModel; using System.ServiceModel.Channels; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; public static class ServiceContractTests { [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_Buffered() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Buffered; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_StreamedRequest() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var result = serviceProxy.GetStringFromStream(stream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_StreamedResponse() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_Streamed() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStream(stream); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_Streamed_Async() { string testString = "Hello"; StringBuilder errorBuilder = new StringBuilder(); BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var returnStream = serviceProxy.EchoStreamAsync(stream).Result; var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.DefaultSettings_Echo_RoundTrips_String_Streamed(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: DefaultSettings_Echo_RoundTrips_String_Streamed_WithSingleThreadedSyncContext timed-out."); } [Fact] [OuterLoop] public static void DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext() { bool success = Task.Run(() => { TestTypes.SingleThreadSynchronizationContext.Run(() => { Task.Factory.StartNew(() => ServiceContractTests.DefaultSettings_Echo_RoundTrips_String_Streamed_Async(), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()).Wait(); }); }).Wait(ScenarioTestHelpers.TestTimeout); Assert.True(success, "Test Scenario: DefaultSettings_Echo_RoundTrips_String_Streamed_Async_WithSingleThreadedSyncContext timed-out."); } [Fact] [OuterLoop] public static void ServiceContract_Call_Operation_With_MessageParameterAttribute() { // This test verifies the scenario where MessageParameter attribute is used in the contract StringBuilder errorBuilder = new StringBuilder(); ChannelFactory<IWcfServiceGenerated> factory = null; IWcfServiceGenerated serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); // Note the service interface used. It was manually generated with svcutil. factory = new ChannelFactory<IWcfServiceGenerated>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string echoString = "you"; string result = serviceProxy.EchoMessageParameter(echoString); // *** VALIDATE *** \\ Assert.True(string.Equals(result, "Hello " + echoString), String.Format("Expected response from Service: {0} Actual was: {1}", "Hello " + echoString, result)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // End operation includes keyword "out" on an Int as an arg. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncEndOperation_IntOutArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractIntOutService> factory = null; IServiceContractIntOutService serviceProxy = null; int number = 0; try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractIntOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntOut_Address)); serviceProxy = factory.CreateChannel(); ManualResetEvent waitEvent = new ManualResetEvent(false); // *** EXECUTE *** \\ // This delegate will execute when the call has completed, which is how we get the result of the call. AsyncCallback callback = (iar) => { serviceProxy.EndRequest(out number, iar); waitEvent.Set(); }; IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null); // *** VALIDATE *** \\ Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called."); Assert.True((number == message.Count<char>()), String.Format("The local int variable was not correctly set, expected {0} but got {1}", message.Count<char>(), number)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // End operation includes keyword "out" on a unique type as an arg. // The unique type used must not appear anywhere else in any contracts in order // test the static analysis logic of the Net Native toolchain. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeOutArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractUniqueTypeOutService> factory = null; IServiceContractUniqueTypeOutService serviceProxy = null; UniqueType uniqueType = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractUniqueTypeOutService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeOut_Address)); serviceProxy = factory.CreateChannel(); ManualResetEvent waitEvent = new ManualResetEvent(false); // *** EXECUTE *** \\ // This delegate will execute when the call has completed, which is how we get the result of the call. AsyncCallback callback = (iar) => { serviceProxy.EndRequest(out uniqueType, iar); waitEvent.Set(); }; IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null); // *** VALIDATE *** \\ Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called."); Assert.True((uniqueType.stringValue == message), String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // End & Begin operations include keyword "ref" on an Int as an arg. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncEndOperation_IntRefArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractIntRefService> factory = null; IServiceContractIntRefService serviceProxy = null; int number = 0; try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractIntRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncIntRef_Address)); serviceProxy = factory.CreateChannel(); ManualResetEvent waitEvent = new ManualResetEvent(false); // *** EXECUTE *** \\ // This delegate will execute when the call has completed, which is how we get the result of the call. AsyncCallback callback = (iar) => { serviceProxy.EndRequest(ref number, iar); waitEvent.Set(); }; IAsyncResult ar = serviceProxy.BeginRequest(message, ref number, callback, null); // *** VALIDATE *** \\ Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called."); Assert.True((number == message.Count<char>()), String.Format("The value of the integer sent by reference was not the expected value. expected {0} but got {1}", message.Count<char>(), number)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // End & Begin operations include keyword "ref" on a unique type as an arg. // The unique type used must not appear anywhere else in any contracts in order // test the static analysis logic of the Net Native toolchain. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_AsyncEndOperation_UniqueTypeRefArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractUniqueTypeRefService> factory = null; IServiceContractUniqueTypeRefService serviceProxy = null; UniqueType uniqueType = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractUniqueTypeRefService>(binding, new EndpointAddress(Endpoints.ServiceContractAsyncUniqueTypeRef_Address)); serviceProxy = factory.CreateChannel(); ManualResetEvent waitEvent = new ManualResetEvent(false); // *** EXECUTE *** \\ // This delegate will execute when the call has completed, which is how we get the result of the call. AsyncCallback callback = (iar) => { serviceProxy.EndRequest(ref uniqueType, iar); waitEvent.Set(); }; IAsyncResult ar = serviceProxy.BeginRequest(message, ref uniqueType, callback, null); // *** VALIDATE *** \\ Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called."); Assert.True((uniqueType.stringValue == message), String.Format("The 'stringValue' field in the instance of 'UniqueType' was not as expected. expected {0} but got {1}", message, uniqueType.stringValue)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // Synchronous operation using the keyword "out" on a unique type as an arg. // The unique type used must not appear anywhere else in any contracts in order // test the static analysis logic of the Net Native toolchain. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeOutArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractUniqueTypeOutSyncService> factory = null; IServiceContractUniqueTypeOutSyncService serviceProxy = null; UniqueType uniqueType = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractUniqueTypeOutSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeOut_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ serviceProxy.Request(message, out uniqueType); // *** VALIDATE *** \\ Assert.True((uniqueType.stringValue == message), String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } // Synchronous operation using the keyword "ref" on a unique type as an arg. // The unique type used must not appear anywhere else in any contracts in order // test the static analysis logic of the Net Native toolchain. [Fact] [OuterLoop] public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeRefArg() { string message = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IServiceContractUniqueTypeRefSyncService> factory = null; IServiceContractUniqueTypeRefSyncService serviceProxy = null; UniqueType uniqueType = new UniqueType(); try { // *** SETUP *** \\ binding = new BasicHttpBinding(); factory = new ChannelFactory<IServiceContractUniqueTypeRefSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeRef_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ serviceProxy.Request(message, ref uniqueType); // *** VALIDATE *** \\ Assert.True((uniqueType.stringValue == message), String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } } private static void PrintInnerExceptionsHresult(Exception e, StringBuilder errorBuilder) { if (e.InnerException != null) { errorBuilder.AppendLine(string.Format("\r\n InnerException type: '{0}', Hresult:'{1}'", e.InnerException, e.InnerException.HResult)); PrintInnerExceptionsHresult(e.InnerException, errorBuilder); } } private static string StreamToString(Stream stream) { var reader = new StreamReader(stream, Encoding.UTF8); return reader.ReadToEnd(); } private static Stream StringToStream(string str) { var ms = new MemoryStream(); var sw = new StreamWriter(ms, Encoding.UTF8); sw.Write(str); sw.Flush(); ms.Position = 0; return ms; } }
using UnityEngine; using System.Collections.Generic; namespace UMA { /// <summary> /// Slot data contains mesh information and overlay references. /// </summary> [System.Serializable] public class SlotData : System.IEquatable<SlotData>, ISerializationCallbackReceiver { /// <summary> /// The asset contains the immutable portions of the slot. /// </summary> public SlotDataAsset asset; /// <summary> /// Adjusts the resolution of slot overlays. /// </summary> public float overlayScale = 1.0f; /// <summary> /// When serializing this recipe should this slot be skipped, useful for scene specific "additional slots" /// </summary> public bool dontSerialize; public string slotName { get { return asset.slotName; } } /// <summary> /// list of overlays used to texture the slot. /// </summary> private List<OverlayData> overlayList = new List<OverlayData>(); /// <summary> /// Constructor for slot using the given asset. /// </summary> /// <param name="asset">Asset.</param> public SlotData(SlotDataAsset asset) { this.asset = asset; overlayScale = asset.overlayScale; } /// <summary> /// Deep copy of the SlotData. /// </summary> public SlotData Copy() { var res = new SlotData(asset); int overlayCount = overlayList.Count; res.overlayList = new List<OverlayData>(overlayCount); for (int i = 0; i < overlayCount; i++) { OverlayData overlay = overlayList[i]; if (overlay != null) { res.overlayList.Add(overlay.Duplicate()); } } return res; } public int GetTextureChannelCount(UMAGeneratorBase generator) { return asset.GetTextureChannelCount(generator); } public bool RemoveOverlay(params string[] names) { bool changed = false; foreach (var name in names) { for (int i = 0; i < overlayList.Count; i++) { if (overlayList[i].overlayName == name) { overlayList.RemoveAt(i); changed = true; break; } } } return changed; } public bool SetOverlayColor(Color32 color, params string[] names) { bool changed = false; foreach (var name in names) { foreach (var overlay in overlayList) { if (overlay.overlayName == name) { overlay.colorData.color = color; changed = true; } } } return changed; } public OverlayData GetOverlay(params string[] names) { foreach (var name in names) { foreach (var overlay in overlayList) { if (overlay.overlayName == name) { return overlay; } } } return null; } public void SetOverlay(int index, OverlayData overlay) { if (index >= overlayList.Count) { overlayList.Capacity = index + 1; while (index >= overlayList.Count) { overlayList.Add(null); } } overlayList[index] = overlay; } public OverlayData GetOverlay(int index) { if (index < 0 || index >= overlayList.Count) return null; return overlayList[index]; } /// <summary> /// Attempts to find an equivalent overlay in the slot. /// </summary> /// <returns>The equivalent overlay (or null, if no equivalent).</returns> /// <param name="overlay">Overlay.</param> public OverlayData GetEquivalentOverlay(OverlayData overlay) { foreach (OverlayData overlay2 in overlayList) { if (OverlayData.Equivalent(overlay, overlay2)) { return overlay2; } } return null; } /// <summary> /// Attempts to find an equivalent overlay in the slot, based on the overlay rect and its assets properties. /// </summary> /// <param name="overlay"></param> /// <returns></returns> public OverlayData GetEquivalentUsedOverlay(OverlayData overlay) { foreach (OverlayData overlay2 in overlayList) { if (OverlayData.EquivalentAssetAndUse(overlay, overlay2)) { return overlay2; } } return null; } public int OverlayCount { get { return overlayList.Count; } } /// <summary> /// Sets the complete list of overlays. /// </summary> /// <param name="newOverlayList">The overlay list.</param> public void SetOverlayList(List<OverlayData> newOverlayList) { if (this.overlayList.Count == newOverlayList.Count) { // keep the list, and just set the overlays so that merging continues to work. for (int i = 0; i < this.overlayList.Count; i++) { this.overlayList[i] = newOverlayList[i]; } } else { this.overlayList = newOverlayList; } } /// <summary> /// Add an overlay to the slot. /// </summary> /// <param name="overlayData">Overlay.</param> public void AddOverlay(OverlayData overlayData) { if (overlayData) overlayList.Add(overlayData); } /// <summary> /// Gets the complete list of overlays. /// </summary> /// <returns>The overlay list.</returns> public List<OverlayData> GetOverlayList() { return overlayList; } internal bool Validate() { bool valid = true; if (asset.meshData != null) { if (asset.material == null) { Debug.LogError(string.Format("Slot '{0}' has a mesh but no material.", asset.slotName), asset); valid = false; } else { if (asset.material.material == null) { Debug.LogError(string.Format("Slot '{0}' has an umaMaterial without a material assigned.", asset.slotName), asset); valid = false; } else { for (int i = 0; i < asset.material.channels.Length; i++) { var channel = asset.material.channels[i]; if (!asset.material.material.HasProperty(channel.materialPropertyName)) { Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset); valid = false; } } } } for (int i = 0; i < overlayList.Count; i++) { var overlayData = overlayList[i]; if (overlayData != null) { if (!overlayData.Validate(asset.material, (i == 0))) { valid = false; Debug.LogError(string.Format("Invalid Overlay '{0}' on Slot '{1}'.", overlayData.overlayName, asset.slotName)); } } } } else { if (asset.material != null) { for (int i = 0; i < asset.material.channels.Length; i++) { var channel = asset.material.channels[i]; if (!asset.material.material.HasProperty(channel.materialPropertyName)) { Debug.LogError(string.Format("Slot '{0}' Material Channel {1} refers to material property '{2}' but no such property exists.", asset.slotName, i, channel.materialPropertyName), asset); valid = false; } } } } return valid; } public override string ToString() { return "SlotData: " + asset.slotName; } #region operator ==, != and similar HACKS, seriously..... public static implicit operator bool(SlotData obj) { return ((System.Object)obj) != null && obj.asset != null; } public bool Equals(SlotData other) { return (this == other); } public override bool Equals(object other) { return Equals(other as SlotData); } public static bool operator ==(SlotData slot, SlotData obj) { if (slot) { if (obj) { return System.Object.ReferenceEquals(slot, obj); } return false; } return !((bool)obj); } public static bool operator !=(SlotData slot, SlotData obj) { if (slot) { if (obj) { return !System.Object.ReferenceEquals(slot, obj); } return true; } return ((bool)obj); } public override int GetHashCode() { return base.GetHashCode(); } #endregion #region ISerializationCallbackReceiver Members public void OnAfterDeserialize() { if (overlayList == null) overlayList = new List<OverlayData>(); } public void OnBeforeSerialize() { } #endregion } }
//Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.WindowsAPI.Resources; using Microsoft.WindowsAPI.Internal; namespace Microsoft.WindowsAPI.Dialogs { /// <summary> /// Encapsulates a new-to-Vista Win32 TaskDialog window /// - a powerful successor to the MessageBox available /// in previous versions of Windows. /// </summary> public sealed class TaskDialog : IDialogControlHost, IDisposable { // Global instance of TaskDialog, to be used by static Show() method. // As most parameters of a dialog created via static Show() will have // identical parameters, we'll create one TaskDialog and treat it // as a NativeTaskDialog generator for all static Show() calls. private static TaskDialog staticDialog; // Main current native dialog. private NativeTaskDialog nativeDialog; private List<TaskDialogButtonBase> buttons = new List<TaskDialogButtonBase>(); private List<TaskDialogButtonBase> radioButtons = new List<TaskDialogButtonBase>(); private List<TaskDialogButtonBase> commandLinks = new List<TaskDialogButtonBase>(); private IntPtr ownerWindow; #region Public Properties /// <summary> /// Occurs when a progress bar changes. /// </summary> public event EventHandler<TaskDialogTickEventArgs> Tick; /// <summary> /// Occurs when a user clicks a hyperlink. /// </summary> public event EventHandler<TaskDialogHyperlinkClickedEventArgs> HyperlinkClick; /// <summary> /// Occurs when the TaskDialog is closing. /// </summary> public event EventHandler<TaskDialogClosingEventArgs> Closing; /// <summary> /// Occurs when a user clicks on Help. /// </summary> public event EventHandler HelpInvoked; /// <summary> /// Occurs when the TaskDialog is opened. /// </summary> public event EventHandler Opened; /// <summary> /// Gets or sets a value that contains the owner window's handle. /// </summary> public IntPtr OwnerWindowHandle { get { return ownerWindow; } set { ThrowIfDialogShowing(LocalizedMessages.OwnerCannotBeChanged); ownerWindow = value; } } // Main content (maps to MessageBox's "message"). private string text; /// <summary> /// Gets or sets a value that contains the message text. /// </summary> public string Text { get { return text; } set { // Set local value, then update native dialog if showing. text = value; if (NativeDialogShowing) { nativeDialog.UpdateText(text); } } } private string instructionText; /// <summary> /// Gets or sets a value that contains the instruction text. /// </summary> public string InstructionText { get { return instructionText; } set { // Set local value, then update native dialog if showing. instructionText = value; if (NativeDialogShowing) { nativeDialog.UpdateInstruction(instructionText); } } } private string caption; /// <summary> /// Gets or sets a value that contains the caption text. /// </summary> public string Caption { get { return caption; } set { ThrowIfDialogShowing(LocalizedMessages.CaptionCannotBeChanged); caption = value; } } private string footerText; /// <summary> /// Gets or sets a value that contains the footer text. /// </summary> public string FooterText { get { return footerText; } set { // Set local value, then update native dialog if showing. footerText = value; if (NativeDialogShowing) { nativeDialog.UpdateFooterText(footerText); } } } private string checkBoxText; /// <summary> /// Gets or sets a value that contains the footer check box text. /// </summary> public string FooterCheckBoxText { get { return checkBoxText; } set { ThrowIfDialogShowing(LocalizedMessages.CheckBoxCannotBeChanged); checkBoxText = value; } } private string detailsExpandedText; /// <summary> /// Gets or sets a value that contains the expanded text in the details section. /// </summary> public string DetailsExpandedText { get { return detailsExpandedText; } set { // Set local value, then update native dialog if showing. detailsExpandedText = value; if (NativeDialogShowing) { nativeDialog.UpdateExpandedText(detailsExpandedText); } } } private bool detailsExpanded; /// <summary> /// Gets or sets a value that determines if the details section is expanded. /// </summary> public bool DetailsExpanded { get { return detailsExpanded; } set { ThrowIfDialogShowing(LocalizedMessages.ExpandingStateCannotBeChanged); detailsExpanded = value; } } private string detailsExpandedLabel; /// <summary> /// Gets or sets a value that contains the expanded control text. /// </summary> public string DetailsExpandedLabel { get { return detailsExpandedLabel; } set { ThrowIfDialogShowing(LocalizedMessages.ExpandedLabelCannotBeChanged); detailsExpandedLabel = value; } } private string detailsCollapsedLabel; /// <summary> /// Gets or sets a value that contains the collapsed control text. /// </summary> public string DetailsCollapsedLabel { get { return detailsCollapsedLabel; } set { ThrowIfDialogShowing(LocalizedMessages.CollapsedTextCannotBeChanged); detailsCollapsedLabel = value; } } private bool cancelable; /// <summary> /// Gets or sets a value that determines if Cancelable is set. /// </summary> public bool Cancelable { get { return cancelable; } set { ThrowIfDialogShowing(LocalizedMessages.CancelableCannotBeChanged); cancelable = value; } } private TaskDialogStandardIcon icon; /// <summary> /// Gets or sets a value that contains the TaskDialog main icon. /// </summary> public TaskDialogStandardIcon Icon { get { return icon; } set { // Set local value, then update native dialog if showing. icon = value; if (NativeDialogShowing) { nativeDialog.UpdateMainIcon(icon); } } } private TaskDialogStandardIcon footerIcon; /// <summary> /// Gets or sets a value that contains the footer icon. /// </summary> public TaskDialogStandardIcon FooterIcon { get { return footerIcon; } set { // Set local value, then update native dialog if showing. footerIcon = value; if (NativeDialogShowing) { nativeDialog.UpdateFooterIcon(footerIcon); } } } private TaskDialogStandardButtons standardButtons = TaskDialogStandardButtons.None; /// <summary> /// Gets or sets a value that contains the standard buttons. /// </summary> public TaskDialogStandardButtons StandardButtons { get { return standardButtons; } set { ThrowIfDialogShowing(LocalizedMessages.StandardButtonsCannotBeChanged); standardButtons = value; } } private DialogControlCollection<TaskDialogControl> controls; /// <summary> /// Gets a value that contains the TaskDialog controls. /// </summary> public DialogControlCollection<TaskDialogControl> Controls { // "Show protection" provided by collection itself, // as well as individual controls. get { return controls; } } private bool hyperlinksEnabled; /// <summary> /// Gets or sets a value that determines if hyperlinks are enabled. /// </summary> public bool HyperlinksEnabled { get { return hyperlinksEnabled; } set { ThrowIfDialogShowing(LocalizedMessages.HyperlinksCannotBetSet); hyperlinksEnabled = value; } } private bool? footerCheckBoxChecked = null; /// <summary> /// Gets or sets a value that indicates if the footer checkbox is checked. /// </summary> public bool? FooterCheckBoxChecked { get { return footerCheckBoxChecked.GetValueOrDefault(false); } set { // Set local value, then update native dialog if showing. footerCheckBoxChecked = value; if (NativeDialogShowing) { nativeDialog.UpdateCheckBoxChecked(footerCheckBoxChecked.Value); } } } private TaskDialogExpandedDetailsLocation expansionMode; /// <summary> /// Gets or sets a value that contains the expansion mode for this dialog. /// </summary> public TaskDialogExpandedDetailsLocation ExpansionMode { get { return expansionMode; } set { ThrowIfDialogShowing(LocalizedMessages.ExpandedDetailsCannotBeChanged); expansionMode = value; } } private TaskDialogStartupLocation startupLocation; /// <summary> /// Gets or sets a value that contains the startup location. /// </summary> public TaskDialogStartupLocation StartupLocation { get { return startupLocation; } set { ThrowIfDialogShowing(LocalizedMessages.StartupLocationCannotBeChanged); startupLocation = value; } } private TaskDialogProgressBar progressBar; /// <summary> /// Gets or sets the progress bar on the taskdialog. ProgressBar a visual representation /// of the progress of a long running operation. /// </summary> public TaskDialogProgressBar ProgressBar { get { return progressBar; } set { ThrowIfDialogShowing(LocalizedMessages.ProgressBarCannotBeChanged); if (value != null) { if (value.HostingDialog != null) { throw new InvalidOperationException(LocalizedMessages.ProgressBarCannotBeHostedInMultipleDialogs); } value.HostingDialog = this; } progressBar = value; } } #endregion #region Constructors /// <summary> /// Creates a basic TaskDialog window /// </summary> public TaskDialog() { CoreHelpers.ThrowIfNotVista(); // Initialize various data structs. controls = new DialogControlCollection<TaskDialogControl>(this); } #endregion #region Static Show Methods /// <summary> /// Creates and shows a task dialog with the specified message text. /// </summary> /// <param name="text">The text to display.</param> /// <returns>The dialog result.</returns> public static TaskDialogResult Show(string text) { return ShowCoreStatic( text, TaskDialogDefaults.MainInstruction, TaskDialogDefaults.Caption); } /// <summary> /// Creates and shows a task dialog with the specified supporting text and main instruction. /// </summary> /// <param name="text">The supporting text to display.</param> /// <param name="instructionText">The main instruction text to display.</param> /// <returns>The dialog result.</returns> public static TaskDialogResult Show(string text, string instructionText) { return ShowCoreStatic( text, instructionText, TaskDialogDefaults.Caption); } /// <summary> /// Creates and shows a task dialog with the specified supporting text, main instruction, and dialog caption. /// </summary> /// <param name="text">The supporting text to display.</param> /// <param name="instructionText">The main instruction text to display.</param> /// <param name="caption">The caption for the dialog.</param> /// <returns>The dialog result.</returns> public static TaskDialogResult Show(string text, string instructionText, string caption) { return ShowCoreStatic(text, instructionText, caption); } #endregion #region Instance Show Methods /// <summary> /// Creates and shows a task dialog. /// </summary> /// <returns>The dialog result.</returns> public TaskDialogResult Show() { return ShowCore(); } #endregion #region Core Show Logic // CORE SHOW METHODS: // All static Show() calls forward here - // it is responsible for retrieving // or creating our cached TaskDialog instance, getting it configured, // and in turn calling the appropriate instance Show. private static TaskDialogResult ShowCoreStatic( string text, string instructionText, string caption) { CoreHelpers.ThrowIfNotVista(); // If no instance cached yet, create it. if (staticDialog == null) { // New TaskDialog will automatically pick up defaults when // a new config structure is created as part of ShowCore(). staticDialog = new TaskDialog(); } // Set the few relevant properties, // and go with the defaults for the others. staticDialog.text = text; staticDialog.instructionText = instructionText; staticDialog.caption = caption; return staticDialog.Show(); } private TaskDialogResult ShowCore() { TaskDialogResult result; try { // Populate control lists, based on current // contents - note we are somewhat late-bound // on our control lists, to support XAML scenarios. SortDialogControls(); // First, let's make sure it even makes // sense to try a show. ValidateCurrentDialogSettings(); // Create settings object for new dialog, // based on current state. NativeTaskDialogSettings settings = new NativeTaskDialogSettings(); ApplyCoreSettings(settings); ApplySupplementalSettings(settings); // Show the dialog. // NOTE: this is a BLOCKING call; the dialog proc callbacks // will be executed by the same thread as the // Show() call before the thread of execution // contines to the end of this method. nativeDialog = new NativeTaskDialog(settings, this); nativeDialog.NativeShow(); // Build and return dialog result to public API - leaving it // null after an exception is thrown is fine in this case result = ConstructDialogResult(nativeDialog); footerCheckBoxChecked = nativeDialog.CheckBoxChecked; } finally { CleanUp(); nativeDialog = null; } return result; } // Helper that looks at the current state of the TaskDialog and verifies // that there aren't any abberant combinations of properties. // NOTE that this method is designed to throw // rather than return a bool. private void ValidateCurrentDialogSettings() { if (footerCheckBoxChecked.HasValue && footerCheckBoxChecked.Value == true && string.IsNullOrEmpty(checkBoxText)) { throw new InvalidOperationException(LocalizedMessages.TaskDialogCheckBoxTextRequiredToEnableCheckBox); } // Progress bar validation. // Make sure the progress bar values are valid. // the Win32 API will valiantly try to rationalize // bizarre min/max/value combinations, but we'll save // it the trouble by validating. if (progressBar != null && !progressBar.HasValidValues) { throw new InvalidOperationException(LocalizedMessages.TaskDialogProgressBarValueInRange); } // Validate Buttons collection. // Make sure we don't have buttons AND // command-links - the Win32 API treats them as different // flavors of a single button struct. if (buttons.Count > 0 && commandLinks.Count > 0) { throw new NotSupportedException(LocalizedMessages.TaskDialogSupportedButtonsAndLinks); } if (buttons.Count > 0 && standardButtons != TaskDialogStandardButtons.None) { throw new NotSupportedException(LocalizedMessages.TaskDialogSupportedButtonsAndButtons); } } // Analyzes the final state of the NativeTaskDialog instance and creates the // final TaskDialogResult that will be returned from the public API private static TaskDialogResult ConstructDialogResult(NativeTaskDialog native) { Debug.Assert(native.ShowState == DialogShowState.Closed, "dialog result being constructed for unshown dialog."); TaskDialogResult result = TaskDialogResult.Cancel; TaskDialogStandardButtons standardButton = MapButtonIdToStandardButton(native.SelectedButtonId); // If returned ID isn't a standard button, let's fetch if (standardButton == TaskDialogStandardButtons.None) { result = TaskDialogResult.CustomButtonClicked; } else { result = (TaskDialogResult)standardButton; } return result; } /// <summary> /// Close TaskDialog /// </summary> /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception> public void Close() { if (!NativeDialogShowing) { throw new InvalidOperationException(LocalizedMessages.TaskDialogCloseNonShowing); } nativeDialog.NativeClose(TaskDialogResult.Cancel); // TaskDialog's own cleanup code - // which runs post show - will handle disposal of native dialog. } /// <summary> /// Close TaskDialog with a given TaskDialogResult /// </summary> /// <param name="closingResult">TaskDialogResult to return from the TaskDialog.Show() method</param> /// <exception cref="InvalidOperationException">if TaskDialog is not showing.</exception> public void Close(TaskDialogResult closingResult) { if (!NativeDialogShowing) { throw new InvalidOperationException(LocalizedMessages.TaskDialogCloseNonShowing); } nativeDialog.NativeClose(closingResult); // TaskDialog's own cleanup code - // which runs post show - will handle disposal of native dialog. } #endregion #region Configuration Construction private void ApplyCoreSettings(NativeTaskDialogSettings settings) { ApplyGeneralNativeConfiguration(settings.NativeConfiguration); ApplyTextConfiguration(settings.NativeConfiguration); ApplyOptionConfiguration(settings.NativeConfiguration); ApplyControlConfiguration(settings); } private void ApplyGeneralNativeConfiguration(TaskDialogNativeMethods.TaskDialogConfiguration dialogConfig) { // If an owner wasn't specifically specified, // we'll use the app's main window. if (ownerWindow != IntPtr.Zero) { dialogConfig.parentHandle = ownerWindow; } // Other miscellaneous sets. dialogConfig.mainIcon = new TaskDialogNativeMethods.IconUnion((int)icon); dialogConfig.footerIcon = new TaskDialogNativeMethods.IconUnion((int)footerIcon); dialogConfig.commonButtons = (TaskDialogNativeMethods.TaskDialogCommonButtons)standardButtons; } /// <summary> /// Sets important text properties. /// </summary> /// <param name="dialogConfig">An instance of a <see cref="TaskDialogNativeMethods.TaskDialogConfiguration"/> object.</param> private void ApplyTextConfiguration(TaskDialogNativeMethods.TaskDialogConfiguration dialogConfig) { // note that nulls or empty strings are fine here. dialogConfig.content = text; dialogConfig.windowTitle = caption; dialogConfig.mainInstruction = instructionText; dialogConfig.expandedInformation = detailsExpandedText; dialogConfig.expandedControlText = detailsExpandedLabel; dialogConfig.collapsedControlText = detailsCollapsedLabel; dialogConfig.footerText = footerText; dialogConfig.verificationText = checkBoxText; } private void ApplyOptionConfiguration(TaskDialogNativeMethods.TaskDialogConfiguration dialogConfig) { // Handle options - start with no options set. TaskDialogNativeMethods.TaskDialogOptions options = TaskDialogNativeMethods.TaskDialogOptions.None; if (cancelable) { options |= TaskDialogNativeMethods.TaskDialogOptions.AllowCancel; } if (footerCheckBoxChecked.HasValue && footerCheckBoxChecked.Value) { options |= TaskDialogNativeMethods.TaskDialogOptions.CheckVerificationFlag; } if (hyperlinksEnabled) { options |= TaskDialogNativeMethods.TaskDialogOptions.EnableHyperlinks; } if (detailsExpanded) { options |= TaskDialogNativeMethods.TaskDialogOptions.ExpandedByDefault; } if (Tick != null) { options |= TaskDialogNativeMethods.TaskDialogOptions.UseCallbackTimer; } if (startupLocation == TaskDialogStartupLocation.CenterOwner) { options |= TaskDialogNativeMethods.TaskDialogOptions.PositionRelativeToWindow; } // Note: no validation required, as we allow this to // be set even if there is no expanded information // text because that could be added later. // Default for Win32 API is to expand into (and after) // the content area. if (expansionMode == TaskDialogExpandedDetailsLocation.ExpandFooter) { options |= TaskDialogNativeMethods.TaskDialogOptions.ExpandFooterArea; } // Finally, apply options to config. dialogConfig.taskDialogFlags = options; } // Builds the actual configuration // that the NativeTaskDialog (and underlying Win32 API) // expects, by parsing the various control // lists, marshalling to the unmanaged heap, etc. private void ApplyControlConfiguration(NativeTaskDialogSettings settings) { // Deal with progress bars/marquees. if (progressBar != null) { if (progressBar.State == TaskDialogProgressBarState.Marquee) { settings.NativeConfiguration.taskDialogFlags |= TaskDialogNativeMethods.TaskDialogOptions.ShowMarqueeProgressBar; } else { settings.NativeConfiguration.taskDialogFlags |= TaskDialogNativeMethods.TaskDialogOptions.ShowProgressBar; } } // Build the native struct arrays that NativeTaskDialog // needs - though NTD will handle // the heavy lifting marshalling to make sure // all the cleanup is centralized there. if (buttons.Count > 0 || commandLinks.Count > 0) { // These are the actual arrays/lists of // the structs that we'll copy to the // unmanaged heap. List<TaskDialogButtonBase> sourceList = (buttons.Count > 0 ? buttons : commandLinks); settings.Buttons = BuildButtonStructArray(sourceList); // Apply option flag that forces all // custom buttons to render as command links. if (commandLinks.Count > 0) { settings.NativeConfiguration.taskDialogFlags |= TaskDialogNativeMethods.TaskDialogOptions.UseCommandLinks; } // Set default button and add elevation icons // to appropriate buttons. settings.NativeConfiguration.defaultButtonIndex = FindDefaultButtonId(sourceList); ApplyElevatedIcons(settings, sourceList); } if (radioButtons.Count > 0) { settings.RadioButtons = BuildButtonStructArray(radioButtons); // Set default radio button - radio buttons don't support. int defaultRadioButton = FindDefaultButtonId(radioButtons); settings.NativeConfiguration.defaultRadioButtonIndex = defaultRadioButton; if (defaultRadioButton == TaskDialogNativeMethods.NoDefaultButtonSpecified) { settings.NativeConfiguration.taskDialogFlags |= TaskDialogNativeMethods.TaskDialogOptions.NoDefaultRadioButton; } } } private static TaskDialogNativeMethods.TaskDialogButton[] BuildButtonStructArray(List<TaskDialogButtonBase> controls) { TaskDialogNativeMethods.TaskDialogButton[] buttonStructs; TaskDialogButtonBase button; int totalButtons = controls.Count; buttonStructs = new TaskDialogNativeMethods.TaskDialogButton[totalButtons]; for (int i = 0; i < totalButtons; i++) { button = controls[i]; buttonStructs[i] = new TaskDialogNativeMethods.TaskDialogButton(button.Id, button.ToString()); } return buttonStructs; } // Searches list of controls and returns the ID of // the default control, or 0 if no default was specified. private static int FindDefaultButtonId(List<TaskDialogButtonBase> controls) { var defaults = controls.FindAll(control => control.Default); if (defaults.Count == 1) { return defaults[0].Id; } else if (defaults.Count > 1) { throw new InvalidOperationException(LocalizedMessages.TaskDialogOnlyOneDefaultControl); } return TaskDialogNativeMethods.NoDefaultButtonSpecified; } private static void ApplyElevatedIcons(NativeTaskDialogSettings settings, List<TaskDialogButtonBase> controls) { foreach (TaskDialogButton control in controls) { if (control.UseElevationIcon) { if (settings.ElevatedButtons == null) { settings.ElevatedButtons = new List<int>(); } settings.ElevatedButtons.Add(control.Id); } } } private void ApplySupplementalSettings(NativeTaskDialogSettings settings) { if (progressBar != null) { if (progressBar.State != TaskDialogProgressBarState.Marquee) { settings.ProgressBarMinimum = progressBar.Minimum; settings.ProgressBarMaximum = progressBar.Maximum; settings.ProgressBarValue = progressBar.Value; settings.ProgressBarState = progressBar.State; } } if (HelpInvoked != null) { settings.InvokeHelp = true; } } // Here we walk our controls collection and // sort the various controls by type. private void SortDialogControls() { foreach (TaskDialogControl control in controls) { TaskDialogButtonBase buttonBase = control as TaskDialogButtonBase; TaskDialogCommandLink commandLink = control as TaskDialogCommandLink; if (buttonBase != null && string.IsNullOrEmpty(buttonBase.Text) && commandLink != null && string.IsNullOrEmpty(commandLink.Instruction)) { throw new InvalidOperationException(LocalizedMessages.TaskDialogButtonTextEmpty); } TaskDialogRadioButton radButton; TaskDialogProgressBar progBar; // Loop through child controls // and sort the controls based on type. if (commandLink != null) { commandLinks.Add(commandLink); } else if ((radButton = control as TaskDialogRadioButton) != null) { if (radioButtons == null) { radioButtons = new List<TaskDialogButtonBase>(); } radioButtons.Add(radButton); } else if (buttonBase != null) { if (buttons == null) { buttons = new List<TaskDialogButtonBase>(); } buttons.Add(buttonBase); } else if ((progBar = control as TaskDialogProgressBar) != null) { progressBar = progBar; } else { throw new InvalidOperationException(LocalizedMessages.TaskDialogUnkownControl); } } } #endregion #region Helpers // Helper to map the standard button IDs returned by // TaskDialogIndirect to the standard button ID enum - // note that we can't just cast, as the Win32 // typedefs differ incoming and outgoing. private static TaskDialogStandardButtons MapButtonIdToStandardButton(int id) { switch ((TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds)id) { case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ok: return TaskDialogStandardButtons.Ok; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Cancel: return TaskDialogStandardButtons.Cancel; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Abort: // Included for completeness in API - // we can't pass in an Abort standard button. return TaskDialogStandardButtons.None; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Retry: return TaskDialogStandardButtons.Retry; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ignore: // Included for completeness in API - // we can't pass in an Ignore standard button. return TaskDialogStandardButtons.None; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Yes: return TaskDialogStandardButtons.Yes; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.No: return TaskDialogStandardButtons.No; case TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close: return TaskDialogStandardButtons.Close; default: return TaskDialogStandardButtons.None; } } private void ThrowIfDialogShowing(string message) { if (NativeDialogShowing) { throw new NotSupportedException(message); } } private bool NativeDialogShowing { get { return (nativeDialog != null) && (nativeDialog.ShowState == DialogShowState.Showing || nativeDialog.ShowState == DialogShowState.Closing); } } // NOTE: we are going to require names be unique // across both buttons and radio buttons, // even though the Win32 API allows them to be separate. private TaskDialogButtonBase GetButtonForId(int id) { return (TaskDialogButtonBase)controls.GetControlbyId(id); } #endregion #region IDialogControlHost Members // We're explicitly implementing this interface // as the user will never need to know about it // or use it directly - it is only for the internal // implementation of "pseudo controls" within // the dialogs. // Called whenever controls are being added // to or removed from the dialog control collection. bool IDialogControlHost.IsCollectionChangeAllowed() { // Only allow additions to collection if dialog is NOT showing. return !NativeDialogShowing; } // Called whenever controls have been added or removed. void IDialogControlHost.ApplyCollectionChanged() { // If we're showing, we should never get here - // the changing notification would have thrown and the // property would not have been changed. Debug.Assert(!NativeDialogShowing, "Collection changed notification received despite show state of dialog"); } // Called when a control currently in the collection // has a property changing - this is // basically to screen out property changes that // cannot occur while the dialog is showing // because the Win32 API has no way for us to // propagate the changes until we re-invoke the Win32 call. bool IDialogControlHost.IsControlPropertyChangeAllowed(string propertyName, DialogControl control) { Debug.Assert(control is TaskDialogControl, "Property changing for a control that is not a TaskDialogControl-derived type"); Debug.Assert(propertyName != "Name", "Name changes at any time are not supported - public API should have blocked this"); bool canChange = false; if (!NativeDialogShowing) { // Certain properties can't be changed if the dialog is not showing // we need a handle created before we can set these... switch (propertyName) { case "Enabled": canChange = false; break; default: canChange = true; break; } } else { // If the dialog is showing, we can only // allow some properties to change. switch (propertyName) { // Properties that CAN'T be changed while dialog is showing. case "Text": case "Default": canChange = false; break; // Properties that CAN be changed while dialog is showing. case "ShowElevationIcon": case "Enabled": canChange = true; break; default: Debug.Assert(true, "Unknown property name coming through property changing handler"); break; } } return canChange; } // Called when a control currently in the collection // has a property changed - this handles propagating // the new property values to the Win32 API. // If there isn't a way to change the Win32 value, then we // should have already screened out the property set // in NotifyControlPropertyChanging. void IDialogControlHost.ApplyControlPropertyChange(string propertyName, DialogControl control) { // We only need to apply changes to the // native dialog when it actually exists. if (NativeDialogShowing) { TaskDialogButton button; TaskDialogRadioButton radioButton; if (control is TaskDialogProgressBar) { if (!progressBar.HasValidValues) { throw new ArgumentException(LocalizedMessages.TaskDialogProgressBarValueInRange); } switch (propertyName) { case "State": nativeDialog.UpdateProgressBarState(progressBar.State); break; case "Value": nativeDialog.UpdateProgressBarValue(progressBar.Value); break; case "Minimum": case "Maximum": nativeDialog.UpdateProgressBarRange(); break; default: Debug.Assert(true, "Unknown property being set"); break; } } else if ((button = control as TaskDialogButton) != null) { switch (propertyName) { case "ShowElevationIcon": nativeDialog.UpdateElevationIcon(button.Id, button.UseElevationIcon); break; case "Enabled": nativeDialog.UpdateButtonEnabled(button.Id, button.Enabled); break; default: Debug.Assert(true, "Unknown property being set"); break; } } else if ((radioButton = control as TaskDialogRadioButton) != null) { switch (propertyName) { case "Enabled": nativeDialog.UpdateRadioButtonEnabled(radioButton.Id, radioButton.Enabled); break; default: Debug.Assert(true, "Unknown property being set"); break; } } else { // Do nothing with property change - // note that this shouldn't ever happen, we should have // either thrown on the changing event, or we handle above. Debug.Assert(true, "Control property changed notification not handled properly - being ignored"); } } } #endregion #region Event Percolation Methods // All Raise*() methods are called by the // NativeTaskDialog when various pseudo-controls // are triggered. internal void RaiseButtonClickEvent(int id) { // First check to see if the ID matches a custom button. TaskDialogButtonBase button = GetButtonForId(id); // If a custom button was found, // raise the event - if not, it's a standard button, and // we don't support custom event handling for the standard buttons if (button != null) { button.RaiseClickEvent(); } } internal void RaiseHyperlinkClickEvent(string link) { EventHandler<TaskDialogHyperlinkClickedEventArgs> handler = HyperlinkClick; if (handler != null) { handler(this, new TaskDialogHyperlinkClickedEventArgs(link)); } } // Gives event subscriber a chance to prevent // the dialog from closing, based on // the current state of the app and the button // used to commit. Note that we don't // have full access at this stage to // the full dialog state. internal int RaiseClosingEvent(int id) { EventHandler<TaskDialogClosingEventArgs> handler = Closing; if (handler != null) { TaskDialogButtonBase customButton = null; TaskDialogClosingEventArgs e = new TaskDialogClosingEventArgs(); // Try to identify the button - is it a standard one? TaskDialogStandardButtons buttonClicked = MapButtonIdToStandardButton(id); // If not, it had better be a custom button... if (buttonClicked == TaskDialogStandardButtons.None) { customButton = GetButtonForId(id); // ... or we have a problem. if (customButton == null) { throw new InvalidOperationException(LocalizedMessages.TaskDialogBadButtonId); } e.CustomButton = customButton.Name; e.TaskDialogResult = TaskDialogResult.CustomButtonClicked; } else { e.TaskDialogResult = (TaskDialogResult)buttonClicked; } // Raise the event and determine how to proceed. handler(this, e); if (e.Cancel) { return (int)HResult.False; } } // It's okay to let the dialog close. return (int)HResult.Ok; } internal void RaiseHelpInvokedEvent() { if (HelpInvoked != null) { HelpInvoked(this, EventArgs.Empty); } } internal void RaiseOpenedEvent() { if (Opened != null) { Opened(this, EventArgs.Empty); } } internal void RaiseTickEvent(int ticks) { if (Tick != null) { Tick(this, new TaskDialogTickEventArgs(ticks)); } } #endregion #region Cleanup Code // Cleans up data and structs from a single // native dialog Show() invocation. private void CleanUp() { // Reset values that would be considered // 'volatile' in a given instance. if (progressBar != null) { progressBar.Reset(); } // Clean out sorted control lists - // though we don't of course clear the main controls collection, // so the controls are still around; we'll // resort on next show, since the collection may have changed. if (buttons != null) { buttons.Clear(); } if (commandLinks != null) { commandLinks.Clear(); } if (radioButtons != null) { radioButtons.Clear(); } progressBar = null; // Have the native dialog clean up the rest. if (nativeDialog != null) { nativeDialog.Dispose(); } } // Dispose pattern - cleans up data and structs for // a) any native dialog currently showing, and // b) anything else that the outer TaskDialog has. private bool disposed; /// <summary> /// Dispose TaskDialog Resources /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// TaskDialog Finalizer /// </summary> ~TaskDialog() { Dispose(false); } /// <summary> /// Dispose TaskDialog Resources /// </summary> /// <param name="disposing">If true, indicates that this is being called via Dispose rather than via the finalizer.</param> public void Dispose(bool disposing) { if (!disposed) { disposed = true; if (disposing) { // Clean up managed resources. if (nativeDialog != null && nativeDialog.ShowState == DialogShowState.Showing) { nativeDialog.NativeClose(TaskDialogResult.Cancel); } buttons = null; radioButtons = null; commandLinks = null; } // Clean up unmanaged resources SECOND, NTD counts on // being closed before being disposed. if (nativeDialog != null) { nativeDialog.Dispose(); nativeDialog = null; } if (staticDialog != null) { staticDialog.Dispose(); staticDialog = null; } } } #endregion /// <summary> /// Indicates whether this feature is supported on the current platform. /// </summary> public static bool IsPlatformSupported { get { // We need Windows Vista onwards ... return CoreHelpers.RunningOnVista; } } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal { using System; using System.Text; /// <summary> /// URL Encoding helper. /// </summary> internal static class UrlHelper { [Flags] public enum EscapeEncodingOptions { None = 0, /// <summary>Allow UnreservedMarks instead of ReservedMarks, as specified by chosen RFC</summary> UriString = 1, /// <summary>Use RFC2396 standard (instead of RFC3986)</summary> LegacyRfc2396 = 2, /// <summary>Should use lowercase when doing HEX escaping of special characters</summary> LowerCaseHex = 4, /// <summary>Replace space ' ' with '+' instead of '%20'</summary> SpaceAsPlus = 8, /// <summary>Skip UTF8 encoding, and prefix special characters with '%u'</summary> NLogLegacy = 16 | LegacyRfc2396 | LowerCaseHex | UriString, }; /// <summary> /// Escape unicode string data for use in http-requests /// </summary> /// <param name="source">unicode string-data to be encoded</param> /// <param name="target">target for the encoded result</param> /// <param name="options"><see cref="EscapeEncodingOptions"/>s for how to perform the encoding</param> public static void EscapeDataEncode(string source, StringBuilder target, EscapeEncodingOptions options) { if (string.IsNullOrEmpty(source)) return; bool isLowerCaseHex = Contains(options, EscapeEncodingOptions.LowerCaseHex); bool isSpaceAsPlus = Contains(options, EscapeEncodingOptions.SpaceAsPlus); bool isNLogLegacy = Contains(options, EscapeEncodingOptions.NLogLegacy); char[] charArray = null; byte[] byteArray = null; char[] hexChars = isLowerCaseHex ? hexLowerChars : hexUpperChars; for (int i = 0; i < source.Length; ++i) { char ch = source[i]; target.Append(ch); if (IsSimpleCharOrNumber(ch)) continue; if (isSpaceAsPlus && ch == ' ') { target[target.Length - 1] = '+'; continue; } if (IsAllowedChar(options, ch)) { continue; } if (isNLogLegacy) { HandleLegacyEncoding(target, ch, hexChars); continue; } if (charArray == null) charArray = new char[1]; charArray[0] = ch; if (byteArray == null) byteArray = new byte[8]; WriteWideChars(target, charArray, byteArray, hexChars); } } private static bool Contains(EscapeEncodingOptions options, EscapeEncodingOptions option) { return (options & option) == option; } /// <summary> /// Convert the wide-char into utf8-bytes, and then escape /// </summary> /// <param name="target"></param> /// <param name="charArray"></param> /// <param name="byteArray"></param> /// <param name="hexChars"></param> private static void WriteWideChars(StringBuilder target, char[] charArray, byte[] byteArray, char[] hexChars) { int byteCount = Encoding.UTF8.GetBytes(charArray, 0, 1, byteArray, 0); for (int j = 0; j < byteCount; ++j) { byte byteCh = byteArray[j]; if (j == 0) target[target.Length - 1] = '%'; else target.Append('%'); target.Append(hexChars[(byteCh & 0xf0) >> 4]); target.Append(hexChars[byteCh & 0xf]); } } private static void HandleLegacyEncoding(StringBuilder target, char ch, char[] hexChars) { if (ch < 256) { target[target.Length - 1] = '%'; target.Append(hexChars[(ch >> 4) & 0xF]); target.Append(hexChars[(ch >> 0) & 0xF]); } else { target[target.Length - 1] = '%'; target.Append('u'); target.Append(hexChars[(ch >> 12) & 0xF]); target.Append(hexChars[(ch >> 8) & 0xF]); target.Append(hexChars[(ch >> 4) & 0xF]); target.Append(hexChars[(ch >> 0) & 0xF]); } } /// <summary> /// Is allowed? /// </summary> /// <param name="options"></param> /// <param name="ch"></param> /// <returns></returns> private static bool IsAllowedChar(EscapeEncodingOptions options, char ch) { bool isUriString = (options & EscapeEncodingOptions.UriString) == EscapeEncodingOptions.UriString; bool isLegacyRfc2396 = (options & EscapeEncodingOptions.LegacyRfc2396) == EscapeEncodingOptions.LegacyRfc2396; if (isUriString) { if (!isLegacyRfc2396 && RFC3986UnreservedMarks.IndexOf(ch) >= 0) return true; if (isLegacyRfc2396 && RFC2396UnreservedMarks.IndexOf(ch) >= 0) return true; } else { if (!isLegacyRfc2396 && RFC3986ReservedMarks.IndexOf(ch) >= 0) return true; if (isLegacyRfc2396 && RFC2396ReservedMarks.IndexOf(ch) >= 0) return true; } return false; } /// <summary> /// Is a-z / A-Z / 0-9 /// </summary> /// <param name="ch"></param> /// <returns></returns> private static bool IsSimpleCharOrNumber(char ch) { return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9'; } private const string RFC2396ReservedMarks = @";/?:@&=+$,"; private const string RFC3986ReservedMarks = @":/?#[]@!$&'()*+,;="; private const string RFC2396UnreservedMarks = @"-_.!~*'()"; private const string RFC3986UnreservedMarks = @"-._~"; private static readonly char[] hexUpperChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static readonly char[] hexLowerChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static EscapeEncodingOptions GetUriStringEncodingFlags(bool escapeDataNLogLegacy, bool spaceAsPlus, bool escapeDataRfc3986) { EscapeEncodingOptions encodingOptions = EscapeEncodingOptions.UriString; if (escapeDataNLogLegacy) encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.NLogLegacy; else if (!escapeDataRfc3986) encodingOptions |= EscapeEncodingOptions.LowerCaseHex | EscapeEncodingOptions.LegacyRfc2396; if (spaceAsPlus) encodingOptions |= EscapeEncodingOptions.SpaceAsPlus; return encodingOptions; } } }
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 AspNetIdentityWebAPIDemo.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) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Runtime.Serialization; using System.Diagnostics; namespace DocumentFormat.OpenXml { /// <summary> /// Represents the mc:AlternateContent element of markup /// compatibility. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class AlternateContent : OpenXmlCompositeElement { private static string _mcNamespace = @"http://schemas.openxmlformats.org/markup-compatibility/2006"; private static byte _mcNamespaceId = byte.MaxValue; private static string tagName = "AlternateContent"; /// <summary> /// Initializes a new instance of the AlternateContent /// class. /// </summary> public AlternateContent() : base() { } /// <summary> /// Initializes a new instance of the AlternateContent /// class by using the supplied IEnumerable elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContent(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AlternateContent /// class by using the supplied OpenXmlElement elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContent(params OpenXmlElement[] childElements) : base(childElements) { } /// <param name="outerXml">The outer XML of the element. /// </param> /// <summary> /// Initializes a new instance of the AlternateContent /// class by using the supplied string. /// </summary> public AlternateContent(string outerXml) : base(outerXml) { } /// <summary> /// Gets a value that represents the markup compatibility /// namespace. /// </summary> public static string MarkupCompatibilityNamespace { get { return _mcNamespace; } } /// <summary> /// Gets a value that represents the markup compatibility /// namespace ID. /// </summary> public static byte MarkupCompatibilityNamespaceId { get { if (_mcNamespaceId == byte.MaxValue) { _mcNamespaceId = NamespaceIdMap.GetNamespaceId(_mcNamespace); } return _mcNamespaceId; } } /// <summary> /// Gets a value that represents the tag name of the /// AlternateContent element. /// </summary> public static string TagName { get { return tagName; } } /// <summary> /// Gets a value that represents the local name of the /// AlternateContent element. /// </summary> public override string LocalName { get { return tagName; } } internal override byte NamespaceId { get { return MarkupCompatibilityNamespaceId; } } private static string[] attributeTagNames = { }; private static byte[] attributeNamespaceIds = { }; internal override string[] AttributeTagNames { get { return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get { return attributeNamespaceIds; } } internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { if (MarkupCompatibilityNamespaceId == namespaceId && AlternateContentChoice.TagName == name) return new AlternateContentChoice(); if (MarkupCompatibilityNamespaceId == namespaceId && AlternateContentFallback.TagName == name) return new AlternateContentFallback(); return null; } /// <summary> /// Appends a new child of type T:DocumentFormat.OpenXml.AlternateContentChoice /// to the current element. /// </summary> /// <returns> /// </returns> public AlternateContentChoice AppendNewAlternateContentChoice() { AlternateContentChoice child = new AlternateContentChoice(); this.AppendChild(child); return child; } /// <summary> /// Appends a new child of type T:DocumentFormat.OpenXml.AlternateContentFallback /// to the current element. /// </summary> /// <returns> /// </returns> public AlternateContentFallback AppendNewAlternateContentFallback() { AlternateContentFallback child = new AlternateContentFallback(); this.AppendChild(child); return child; } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { return null; } /// <returns>The cloned node. </returns> /// <summary> /// When a node is overridden in a derived class, /// CloneNode creates a duplicate of the node. /// </summary> /// <param name="deep"> /// True to recursively clone the subtree under /// the specified node; False to clone only the node /// itself. /// </param> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<AlternateContent>(deep); } /// <summary> /// The type ID of the element. /// </summary> internal override int ElementTypeId { get { return ReservedElementTypeIds.AlternateContentId; } } /// <summary> /// Indicates whether this element is available in a specific version of an Office Application. /// Always returns true since AlternateContent is allowed /// in every version. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { return true; } } /// <summary> /// Defines an mc:Choice element in mc:AlternateContent. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class AlternateContentChoice : OpenXmlCompositeElement { private static string tagName = "Choice"; /// <summary> /// Initializes a new instance of the /// AlternateContentChoice class. /// </summary> public AlternateContentChoice() : base() { } /// <summary> /// Initializes a new instance of the /// AlternateContentChoice class by using the supplied /// IEnumerable elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContentChoice(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the /// AlternateContentChoice class by using the supplied /// OpenXmlElement elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContentChoice(params OpenXmlElement[] childElements) : base(childElements) { } /// <param name="outerXml"> /// The outer XML of the element. /// </param> /// <summary> /// Initializes a new instance of the /// AlternateContentChoice class by using the supplied /// string. /// </summary> public AlternateContentChoice(string outerXml) : base(outerXml) { } /// <summary> /// Gets a value that represents the tag name of the /// Choice element. /// </summary> public static string TagName { get { return tagName; } } /// <summary> /// Gets the local name of the Choice element. /// </summary> public override string LocalName { get { return tagName; } } internal override byte NamespaceId { get { return AlternateContent.MarkupCompatibilityNamespaceId; } } private static string[] attributeTagNames = { "Requires" }; private static byte[] attributeNamespaceIds = { 0 }; internal override string[] AttributeTagNames { get { return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get { return attributeNamespaceIds; } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { if (0 == namespaceId && "Requires" == name) return new StringValue(); return null; } /// <summary> /// <para>Gets or sets a whitespace-delimited list of namespace prefixes that identify the /// namespaces a markup consumer needs in order to understand and select that /// Choice and process the content.</para> /// <para> Represents the attribute in a schema. </para> /// </summary> public StringValue Requires { get { return (StringValue)Attributes[0]; } set { Attributes[0] = value; } } internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { OpenXmlElement newElement = null; if (this.Parent != null && this.Parent is AlternateContent) { OpenXmlElement parentsParentElemnt = this.Parent.Parent; if (parentsParentElemnt != null) { newElement = parentsParentElemnt.ElementFactory(namespaceId, name); if (newElement == null) { newElement = parentsParentElemnt.AlternateContentElementFactory(namespaceId, name); } } } return newElement; } /// <returns>The cloned node. </returns> /// <summary> /// When a node is overridden in a derived class, CloneNode creates a duplicate /// of the node. /// </summary> /// <param name="deep"> /// True to recursively clone the subtree under the specified node; False /// to clone only the node itself. /// </param> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<AlternateContentChoice>(deep); } /// <summary> /// The type ID of the element. /// </summary> internal override int ElementTypeId { get { return ReservedElementTypeIds.AlternateContentChoiceId; } } /// <summary> /// Indicates whether this element is available in a specific version of an Office Application. /// This method always returns true since AlternateContentFallback is available in every version. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { return true; } } /// <summary> /// Defines a mc:Fallback element in mc:AlternateContent. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] public class AlternateContentFallback : OpenXmlCompositeElement { private static string tagName = "Fallback"; /// <summary> /// Initializes a new instance of the AlternateContentFallback class. /// </summary> public AlternateContentFallback() : base() { } /// <summary> /// Initializes a new instance of the AlternateContentFallback class /// by using the supplied IEnumerable elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContentFallback(IEnumerable<OpenXmlElement> childElements) : base(childElements) { } /// <summary> /// Initializes a new instance of the AlternateContentFallback class /// by using the supplied OpenXmlElement elements. /// </summary> /// <param name="childElements"> /// Represents all child elements. /// </param> public AlternateContentFallback(params OpenXmlElement[] childElements) : base(childElements) { } /// <param name="outerXml">The outer XML of the element.</param> /// <summary> /// Initializes a new instance of the AlternateContentFallback class /// by using the supplied string. /// </summary> public AlternateContentFallback(string outerXml) : base(outerXml) { } /// <summary> /// Gets a value that represents the tag name of the AlternateContentFallback element. /// </summary> public static string TagName { get { return tagName; } } /// <summary> /// Gets the local name of the element. /// </summary> public override string LocalName { get { return tagName; } } internal override byte NamespaceId { get { return AlternateContent.MarkupCompatibilityNamespaceId; } } private static string[] attributeTagNames = { }; private static byte[] attributeNamespaceIds = { }; internal override string[] AttributeTagNames { get { return attributeTagNames; } } internal override byte[] AttributeNamespaceIds { get { return attributeNamespaceIds; } } internal override OpenXmlSimpleType AttributeFactory(byte namespaceId, string name) { return null; } internal override OpenXmlElement ElementFactory(byte namespaceId, string name) { OpenXmlElement newElement = null; if (this.Parent != null && this.Parent is AlternateContent) { OpenXmlElement parentsParentElemnt = this.Parent.Parent; if (parentsParentElemnt != null) { newElement = parentsParentElemnt.ElementFactory(namespaceId, name); } } return newElement; } /// <returns>The cloned node. </returns> /// <summary> /// When a node is overridden in a derived class, CloneNode creates a /// duplicate of the node. /// </summary> /// <param name="deep"> /// True to recursively clone the subtree under the specified node; False /// to clone only the node itself. /// </param> public override OpenXmlElement CloneNode(bool deep) { return CloneImp<AlternateContentFallback>(deep); } /// <summary> /// The type ID of the element. /// </summary> internal override int ElementTypeId { get { return ReservedElementTypeIds.AlternateContentFallbackId; } } /// <summary> /// Indicates whether this element is available in a specific version of an Office Application. /// This method always return true since AlternateContentFallback is available in every version. /// </summary> /// <param name="version">The Office file format version.</param> /// <returns>Returns true if the element is defined in the specified version.</returns> internal override bool IsInVersion(FileFormatVersions version) { return true; } } internal enum ElementAction { Normal, Ignore, ProcessContent, ACBlock, } internal enum AttributeAction { Normal, Ignore, } /// <summary> /// Defines the Markup Compatibility Attributes. /// </summary> public class MarkupCompatibilityAttributes { internal static string MCPrefix = NamespaceIdMap.GetNamespacePrefix(NamespaceIdMap.GetNamespaceId(AlternateContent.MarkupCompatibilityNamespace)); /// <summary> /// Gets or sets a whitespace-delimited list of prefixes, where each /// prefix identifies an ignorable namespace. /// </summary> public StringValue Ignorable { get; set; } /// <summary> /// Gets or sets a whitespace-delimited list of element-qualified names /// that identify the expanded names of elements. The content of the /// elements shall be processed, even if the elements themselves are /// ignored. /// </summary> public StringValue ProcessContent { get; set; } /// <summary> /// Gets or sets a whitespace-delimited list of element qualified names /// that identify the expanded names of elements. The elements are suggested /// by a markup producer for preservation by markup editors, even if /// the elements themselves are ignored. /// </summary> public StringValue PreserveElements { get; set; } /// <summary> /// Gets or sets a whitespace-delimited list of attribute qualified names /// that identify expanded names of attributes. The attributes were /// suggested by a markup producer for preservation by markup editors. /// </summary> public StringValue PreserveAttributes { get; set; } /// <summary> /// Gets or sets a whitespace-delimited list of prefixes that identify /// a set of namespace names. /// </summary> public StringValue MustUnderstand { get; set; } } internal class MCConsts { internal const string Ignorable = "Ignorable"; internal const string ProcessContent = "ProcessContent"; internal const string PreserveElements = "PreserveElements"; internal const string PreserveAttributes = "PreserveAttributes"; internal const string MustUnderstand = "MustUnderstand"; } internal class MCContext { internal delegate string LookupNamespace(string prefix); Stack<string> _currentIgnorable; Stack<XmlQualifiedName> _currentPreserveAttr; Stack<XmlQualifiedName> _currentPreserveEle; Stack<XmlQualifiedName> _currentProcessContent; Stack<int> _pushedIgnor; Stack<int> _pushedPA; Stack<int> _pushedPE; Stack<int> _pushedPC; bool _noExceptionOnError; internal MCContext() { _currentIgnorable = new Stack<string>(); _currentPreserveAttr = new Stack<XmlQualifiedName>(); _currentPreserveEle = new Stack<XmlQualifiedName>(); _currentProcessContent = new Stack<XmlQualifiedName>(); _pushedIgnor = new Stack<int>(); _pushedPA = new Stack<int>(); _pushedPC = new Stack<int>(); _pushedPE = new Stack<int>(); } internal MCContext(bool exceptionOnError) : this() { this._noExceptionOnError = ! exceptionOnError; } internal LookupNamespace LookupNamespaceDelegate { get; set; } #region methods to maintain the MC Context internal void PushMCAttributes(MarkupCompatibilityAttributes attr) { _pushedIgnor.Push(PushIgnorable(attr)); _pushedPA.Push(PushPreserveAttribute(attr)); _pushedPE.Push(PushPreserveElement(attr)); _pushedPC.Push(PushProcessContent(attr)); } internal void PopMCAttributes() { PopIgnorable(_pushedIgnor.Pop()); PopPreserveAttribute(_pushedPA.Pop()); PopPreserveElement(_pushedPE.Pop()); PopProcessContent(_pushedPC.Pop()); } /// <summary> /// This method is for MC validation use. Only push Ignorable and ProcessContent. /// </summary> /// <param name="attr"></param> /// <param name="lookupNamespaceDelegate"></param> internal void PushMCAttributes2(MarkupCompatibilityAttributes attr, LookupNamespace lookupNamespaceDelegate) { this.LookupNamespaceDelegate = lookupNamespaceDelegate; _pushedIgnor.Push(PushIgnorable(attr)); _pushedPC.Push(PushProcessContent(attr)); } /// <summary> /// This method is for MC validation use only. /// </summary> internal void PopMCAttributes2() { PopIgnorable(_pushedIgnor.Pop()); PopProcessContent(_pushedPC.Pop()); } /// <summary> /// This method is called by ParseQNameList() and ParsePrefixList(). /// </summary> /// <param name="value">The value of the attribute.</param> /// <returns>True to stop parsing; False to continue.</returns> internal delegate bool OnInvalidValue(string value); internal IEnumerable<string> ParsePrefixList(string ignorable, OnInvalidValue onInvalidPrefix) { Debug.Assert(!string.IsNullOrEmpty(ignorable)); var prefixes = ignorable.Trim().Split(new char[] { ' ' }); foreach (var prefix in prefixes) { var ns = LookupNamespaceDelegate(prefix); if (string.IsNullOrEmpty(ns)) { if (onInvalidPrefix(ignorable)) { yield break; } else { continue; } } yield return ns; } } internal IEnumerable<XmlQualifiedName> ParseQNameList(string qnameList, OnInvalidValue onInvalidQName) { Debug.Assert(!string.IsNullOrEmpty(qnameList)); var qnames = qnameList.Trim().Split(new char[] { ' ' }); foreach (var qname in qnames) { var items = qname.Split(':'); if (items.Length != 2) { if (onInvalidQName(qnameList)) { yield break; } else { continue; } } var ns = LookupNamespaceDelegate(items[0]); if (string.IsNullOrEmpty(ns)) { if (onInvalidQName(qnameList)) { yield break; } else { continue; } } yield return (new XmlQualifiedName(items[1], ns)); } } #endregion #region Exposed functions internal bool HasIgnorable() { return _currentIgnorable.Count > 0; } internal bool IsIgnorableNs(byte namespaceId) { if (_currentIgnorable.Count == 0) { return false; } if (_currentIgnorable.Contains(NamespaceIdMap.GetNamespaceUri(namespaceId))) { return true; } else { return false; } } internal bool IsIgnorableNs(string ns) { if (_currentIgnorable.Count == 0) { return false; } if (string.IsNullOrEmpty(ns)) { return false; } if (_currentIgnorable.Contains(ns)) { return true; } else { return false; } } internal bool IsPreservedAttribute(string ns, string localName) { return ContainsQName(localName, ns, _currentPreserveAttr); } internal bool IsPreservedElement(string ns, string localName) { return ContainsQName(localName, ns, _currentPreserveEle); } internal bool IsProcessContent(string ns, string localName) { return ContainsQName(localName, ns, _currentProcessContent); } internal bool IsProcessContent(OpenXmlElement element) { // TODO: performance tuning return ContainsQName(element.LocalName, element.NamespaceUri, _currentProcessContent); } internal AttributeAction GetAttributeAction(string ns, string localName, FileFormatVersions format) { if (format == (FileFormatVersions.Office2010|FileFormatVersions.Office2007) || format == (FileFormatVersions.Office2010|FileFormatVersions.Office2007|FileFormatVersions.Office2013)) { return AttributeAction.Normal; } if (string.IsNullOrEmpty(ns)) { return AttributeAction.Normal; } if (NamespaceIdMap.IsInFileFormat(ns, format)) { return AttributeAction.Normal; } if (!IsIgnorableNs(ns)) { return AttributeAction.Normal; } if (IsPreservedAttribute(ns, localName)) { return AttributeAction.Normal; } return AttributeAction.Ignore; } internal ElementAction GetElementAction(OpenXmlElement element, FileFormatVersions format) { if (format == (FileFormatVersions.Office2010 | FileFormatVersions.Office2007) || format == (FileFormatVersions.Office2010 | FileFormatVersions.Office2007 | FileFormatVersions.Office2013)) { return ElementAction.Normal; } if (element is AlternateContent) { return ElementAction.ACBlock; } if (element.IsInVersion(format)) { return ElementAction.Normal; } if (IsIgnorableNs(element.NamespaceUri)) { if (IsPreservedElement(element.NamespaceUri, element.LocalName)) { return ElementAction.Normal; } if (IsProcessContent(element.NamespaceUri, element.LocalName)) { return ElementAction.ProcessContent; } return ElementAction.Ignore; } return ElementAction.Normal; } #endregion #region private methods private static bool ContainsQName(string localName, string ns, Stack<XmlQualifiedName> stack) { XmlQualifiedName qname = new XmlQualifiedName(localName, ns); foreach (var qn in stack) { if (qn == qname || qn.Name == "*" && qn.Namespace == ns) { return true; } } return false; } /// <summary> /// This method is called by ParseIgnorable() and ParseProcessContent(). /// </summary> /// <param name="value">The value of the attribute.</param> /// <returns>True to stop parsing; False to continue.</returns> private bool OnMcContextError(string value) { if (this._noExceptionOnError) { return false; } else { var msg = String.Format(System.Globalization.CultureInfo.CurrentUICulture, ExceptionMessages.UnknowMCContent, value); throw new InvalidMCContentException(msg); } } private int PushIgnorable(MarkupCompatibilityAttributes attr) { int ret = 0; if (attr != null && attr.Ignorable != null && !string.IsNullOrEmpty(attr.Ignorable.Value)) { foreach (var ns in ParsePrefixList(attr.Ignorable, OnMcContextError)) { _currentIgnorable.Push(ns); ret++; } } return ret; } private int PushQName(Stack<XmlQualifiedName>stack, string value) { int ret = 0; foreach (var qn in ParseQNameList(value, OnMcContextError)) { stack.Push(qn); ret++; } return ret; } private int PushPreserveAttribute(MarkupCompatibilityAttributes attr) { int ret = 0; if (attr != null && attr.PreserveAttributes != null && !string.IsNullOrEmpty(attr.PreserveAttributes.Value)) { ret = PushQName(_currentPreserveAttr,attr.PreserveAttributes.Value); } return ret; } private int PushPreserveElement(MarkupCompatibilityAttributes attr) { int ret = 0; if (attr != null && attr.PreserveElements != null && !string.IsNullOrEmpty(attr.PreserveElements.Value)) { ret = PushQName(_currentPreserveEle, attr.PreserveElements.Value); } return ret; } private int PushProcessContent(MarkupCompatibilityAttributes attr) { int ret = 0; if (attr != null && attr.ProcessContent != null && !string.IsNullOrEmpty(attr.ProcessContent.Value)) { ret = PushQName(_currentProcessContent, attr.ProcessContent.Value); } return ret; } private void PopIgnorable(int count) { for (int i = 0; i < count; i++) { _currentIgnorable.Pop(); } } private void PopPreserveAttribute(int count) { for (int i = 0; i < count; i++) { _currentPreserveAttr.Pop(); } } private void PopPreserveElement(int count) { for (int i = 0; i < count; i++) { _currentPreserveEle.Pop(); } } private void PopProcessContent(int count) { for (int i = 0; i < count; i++) { _currentProcessContent.Pop(); } } #endregion #region Helper functions internal OpenXmlCompositeElement GetContentFromACBlock(AlternateContent acblk, FileFormatVersions format) { Debug.Assert(format != (FileFormatVersions.Office2007 | FileFormatVersions.Office2010 | FileFormatVersions.Office2013)); foreach (var choice in acblk.ChildElements.OfType<AlternateContentChoice>()) { if(choice.Requires == null) { //should we throw exception here? continue; } string reqs = choice.Requires.InnerText.Trim(); if (string.IsNullOrEmpty(reqs)) { //should we throw exception here? continue; } bool chooce = true; foreach (var req in reqs.Split(new char[] { ' ' })) { //fix bug 537858 //the LookupNamespaceDeleget is from xmlReader //bug when we try to GetContentFromACBlock, the reader has already moved to the next element of ACB //so we should use the element's LookupNamespace function to find it //string ns = LookupNamespaceDelegate(req); string ns = choice.LookupNamespace(req); if (ns == null) { if (this._noExceptionOnError) { chooce = false; break; } else { var msg = String.Format(System.Globalization.CultureInfo.CurrentUICulture, ExceptionMessages.UnknowMCContent, req); throw new InvalidMCContentException(msg); } } if (!NamespaceIdMap.IsInFileFormat(ns, format)) { chooce = false; break; } } if (chooce) { return choice; } } var fallback = acblk.GetFirstChild<AlternateContentFallback>(); if (fallback != null) { return fallback; } return null; } #endregion } /// <summary> /// The exception that is thrown for Markup Compatibility content errors. /// </summary> [SerializableAttribute] public sealed class InvalidMCContentException : Exception { /// <summary> /// Initializes a new instance of the InvalidMCContentException class. /// </summary> public InvalidMCContentException() : base() { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with a specified error message. /// </summary> /// <param name="message">The message that describes the error. </param> public InvalidMCContentException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> private InvalidMCContentException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public InvalidMCContentException(string message, Exception innerException) : base(message, innerException) { } } /// <summary> /// The exception that is thrown for Markup Compatibility content errors. /// </summary> [SerializableAttribute] public sealed class NamespaceNotUnderstandException : Exception { /// <summary> /// Initializes a new instance of the InvalidMCContentException class. /// </summary> public NamespaceNotUnderstandException() : base() { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with a specified error message. /// </summary> /// <param name="message">The message that describes the error. </param> public NamespaceNotUnderstandException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with serialized data. /// </summary> /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> private NamespaceNotUnderstandException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of the InvalidMCContentException class with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public NamespaceNotUnderstandException(string message, Exception innerException) : base(message, innerException) { } } }
using System; using System.Diagnostics; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Math.EC.Multiplier; namespace Org.BouncyCastle.Math.EC { /** * base class for points on elliptic curves. */ public abstract class ECPoint { private readonly ECCurve _curve; private readonly ECFieldElement _x, _y; private readonly bool _withCompression; protected internal ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) { if (curve == null) throw new ArgumentNullException("curve"); _curve = curve; _x = x; _y = y; _withCompression = withCompression; } public ECCurve Curve { get { return _curve; } } public ECFieldElement X { get { return _x; } } public ECFieldElement Y { get { return _y; } } public bool IsInfinity { get { return _x == null && _y == null; } } public bool IsCompressed { get { return _withCompression; } } public IECMultiplier Multiplier { get; set; } public IPreCompInfo PreCompInfo { get; set; } public override bool Equals(object obj) { if (obj == this) return true; var o = obj as ECPoint; if (o == null) return false; if (this.IsInfinity) return o.IsInfinity; return _x.Equals(o._x) && _y.Equals(o._y); } public override int GetHashCode() { if (this.IsInfinity) return 0; return _x.GetHashCode() ^ _y.GetHashCode(); } // /** // * Mainly for testing. Explicitly set the <code>ECMultiplier</code>. // * @param multiplier The <code>ECMultiplier</code> to be used to multiply // * this <code>ECPoint</code>. // */ // internal void SetECMultiplier( // ECMultiplier multiplier) // { // this.multiplier = multiplier; // } public abstract byte[] GetEncoded(); public abstract ECPoint Add(ECPoint b); public abstract ECPoint Subtract(ECPoint b); public abstract ECPoint Negate(); public abstract ECPoint Twice(); public abstract ECPoint Multiply(IBigInteger b); /** * Sets the appropriate <code>ECMultiplier</code>, unless already set. */ internal virtual void AssertECMultiplier() { if (Multiplier != null) return; lock (this) { if (Multiplier == null) { Multiplier = new FpNafMultiplier(); } } } } public abstract class ECPointBase : ECPoint { protected internal ECPointBase(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { } protected internal abstract bool YTilde { get; } /** * return the field element encoded with point compression. (S 4.3.6) */ public override byte[] GetEncoded() { if (this.IsInfinity) return new byte[1]; // Note: some of the tests rely on calculating byte length from the field element // (since the test cases use mismatching fields for curve/elements) var byteLength = X9IntegerConverter.GetByteLength(this.X); var x = X9IntegerConverter.IntegerToBytes(this.X.ToBigInteger(), byteLength); byte[] po; if (this.IsCompressed) { po = new byte[1 + x.Length]; po[0] = (byte)(YTilde ? 0x03 : 0x02); } else { var y = X9IntegerConverter.IntegerToBytes(this.Y.ToBigInteger(), byteLength); po = new byte[1 + x.Length + y.Length]; po[0] = 0x04; y.CopyTo(po, 1 + x.Length); } x.CopyTo(po, 1); return po; } /** * Multiplies this <code>ECPoint</code> by the given number. * @param k The multiplicator. * @return <code>k * this</code>. */ public override ECPoint Multiply(IBigInteger k) { if (k.SignValue < 0) throw new ArgumentException(@"The multiplicator cannot be negative", "k"); if (this.IsInfinity) return this; if (k.SignValue == 0) return this.Curve.Infinity; AssertECMultiplier(); return this.Multiplier.Multiply(this, k, this.PreCompInfo); } } /** * Elliptic curve points over Fp */ public class FPPoint : ECPointBase { /** * Create a point which encodes with point compression. * * @param curve the curve to use * @param x affine x co-ordinate * @param y affine y co-ordinate */ public FPPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * Create a point that encodes with or without point compresion. * * @param curve the curve to use * @param x affine x co-ordinate * @param y affine y co-ordinate * @param withCompression if true encode with point compression */ public FPPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x != null && y == null) || (x == null && y != null)) throw new ArgumentException("Exactly one of the field elements is null"); } protected internal override bool YTilde { get { return this.Y.ToBigInteger().TestBit(0); } } // B.3 pg 62 public override ECPoint Add(ECPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; // Check if b = this or b = -this if (this.X.Equals(b.X)) { if (this.Y.Equals(b.Y)) { // this = b, i.e. this must be doubled return this.Twice(); } Debug.Assert(this.Y.Equals(b.Y.Negate())); // this = -b, i.e. the result is the point at infinity return this.Curve.Infinity; } var gamma = b.Y.Subtract(this.Y).Divide(b.X.Subtract(this.X)); var x3 = gamma.Square().Subtract(this.X).Subtract(b.X); var y3 = gamma.Multiply(this.X.Subtract(x3)).Subtract(this.Y); return new FPPoint(this.Curve, x3, y3); } // B.3 pg 62 public override ECPoint Twice() { // Twice identity element (point at infinity) is identity if (this.IsInfinity) return this; // if y1 == 0, then (x1, y1) == (x1, -y1) // and hence this = -this and thus 2(x1, y1) == infinity if (this.Y.ToBigInteger().SignValue == 0) return this.Curve.Infinity; var two = this.Curve.FromBigInteger(BigInteger.Two); var three = this.Curve.FromBigInteger(BigInteger.Three); var gamma = this.X.Square().Multiply(three).Add(this.Curve.A).Divide(Y.Multiply(two)); var x3 = gamma.Square().Subtract(this.X.Multiply(two)); var y3 = gamma.Multiply(this.X.Subtract(x3)).Subtract(this.Y); return new FPPoint(this.Curve, x3, y3, this.IsCompressed); } // D.3.2 pg 102 (see Note:) public override ECPoint Subtract(ECPoint b) { return b.IsInfinity ? this : Add(b.Negate()); } public override ECPoint Negate() { return new FPPoint(this.Curve, this.X, this.Y.Negate(), this.IsCompressed); } /** * Sets the default <code>ECMultiplier</code>, unless already set. */ internal override void AssertECMultiplier() { if (this.Multiplier == null) { lock (this) { if (this.Multiplier == null) { this.Multiplier = new WNafMultiplier(); } } } } } /** * Elliptic curve points over F2m */ public class F2MPoint : ECPointBase { /** * @param curve base curve * @param x x point * @param y y point */ public F2MPoint(ECCurve curve, ECFieldElement x, ECFieldElement y) : this(curve, x, y, false) { } /** * @param curve base curve * @param x x point * @param y y point * @param withCompression true if encode with point compression. */ public F2MPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, bool withCompression) : base(curve, x, y, withCompression) { if ((x != null && y == null) || (x == null && y != null)) { throw new ArgumentException("Exactly one of the field elements is null"); } if (x == null) return; // Check if x and y are elements of the same field F2MFieldElement.CheckFieldElements(this.X, this.Y); // Check if x and a are elements of the same field F2MFieldElement.CheckFieldElements(this.X, this.Curve.A); } /** * Constructor for point at infinity */ [Obsolete("Use ECCurve.Infinity property")] public F2MPoint( ECCurve curve) : this(curve, null, null) { } protected internal override bool YTilde { get { // X9.62 4.2.2 and 4.3.6: // if x = 0 then ypTilde := 0, else ypTilde is the rightmost // bit of y * x^(-1) return this.X.ToBigInteger().SignValue != 0 && this.Y.Multiply(this.X.Invert()).ToBigInteger().TestBit(0); } } /** * Check, if two <code>ECPoint</code>s can be added or subtracted. * @param a The first <code>ECPoint</code> to check. * @param b The second <code>ECPoint</code> to check. * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * cannot be added. */ private static void CheckPoints(ECPoint a, ECPoint b) { // Check, if points are on the same curve if (!a.Curve.Equals(b.Curve)) throw new ArgumentException("Only points on the same curve can be added or subtracted"); // F2mFieldElement.CheckFieldElements(a.x, b.x); } /* (non-Javadoc) * @see org.bouncycastle.math.ec.ECPoint#add(org.bouncycastle.math.ec.ECPoint) */ public override ECPoint Add(ECPoint b) { CheckPoints(this, b); return AddSimple((F2MPoint)b); } /** * Adds another <code>ECPoints.F2m</code> to <code>this</code> without * checking if both points are on the same curve. Used by multiplication * algorithms, because there all points are a multiple of the same point * and hence the checks can be omitted. * @param b The other <code>ECPoints.F2m</code> to add to * <code>this</code>. * @return <code>this + b</code> */ internal F2MPoint AddSimple(F2MPoint b) { if (this.IsInfinity) return b; if (b.IsInfinity) return this; var x2 = (F2MFieldElement)b.X; var y2 = (F2MFieldElement)b.Y; // Check if b == this or b == -this if (this.X.Equals(x2)) { // this == b, i.e. this must be doubled if (this.Y.Equals(y2)) return (F2MPoint)this.Twice(); // this = -other, i.e. the result is the point at infinity return (F2MPoint)this.Curve.Infinity; } var xSum = this.X.Add(x2); var lambda = (F2MFieldElement)(this.Y.Add(y2)).Divide(xSum); var x3 = (F2MFieldElement)lambda.Square().Add(lambda).Add(xSum).Add(this.Curve.A); var y3 = (F2MFieldElement)lambda.Multiply(this.X.Add(x3)).Add(x3).Add(this.Y); return new F2MPoint(this.Curve, x3, y3, this.IsCompressed); } /* (non-Javadoc) * @see org.bouncycastle.math.ec.ECPoint#subtract(org.bouncycastle.math.ec.ECPoint) */ public override ECPoint Subtract( ECPoint b) { CheckPoints(this, b); return SubtractSimple((F2MPoint)b); } /** * Subtracts another <code>ECPoints.F2m</code> from <code>this</code> * without checking if both points are on the same curve. Used by * multiplication algorithms, because there all points are a multiple * of the same point and hence the checks can be omitted. * @param b The other <code>ECPoints.F2m</code> to subtract from * <code>this</code>. * @return <code>this - b</code> */ internal F2MPoint SubtractSimple( F2MPoint b) { if (b.IsInfinity) return this; // Add -b return AddSimple((F2MPoint)b.Negate()); } /* (non-Javadoc) * @see Org.BouncyCastle.Math.EC.ECPoint#twice() */ public override ECPoint Twice() { // Twice identity element (point at infinity) is identity if (this.IsInfinity) return this; // if x1 == 0, then (x1, y1) == (x1, x1 + y1) // and hence this = -this and thus 2(x1, y1) == infinity if (this.X.ToBigInteger().SignValue == 0) return this.Curve.Infinity; var lambda = (F2MFieldElement)this.X.Add(this.Y.Divide(this.X)); var x2 = (F2MFieldElement)lambda.Square().Add(lambda).Add(this.Curve.A); var one = this.Curve.FromBigInteger(BigInteger.One); var y2 = (F2MFieldElement)this.X.Square().Add(x2.Multiply(lambda.Add(one))); return new F2MPoint(this.Curve, x2, y2, this.IsCompressed); } public override ECPoint Negate() { return new F2MPoint(this.Curve, this.X, this.X.Add(this.Y), this.IsCompressed); } /** * Sets the appropriate <code>ECMultiplier</code>, unless already set. */ internal override void AssertECMultiplier() { if (this.Multiplier == null) { lock (this) { if (this.Multiplier == null) { if (((F2MCurve)this.Curve).IsKoblitz) { this.Multiplier = new WTauNafMultiplier(); } else { this.Multiplier = new WNafMultiplier(); } } } } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Management.SiteRecovery; using Microsoft.WindowsAzure.Management.SiteRecovery.Models; namespace Microsoft.WindowsAzure.Management.SiteRecovery { public static partial class ProtectionEntityOperationsExtensions { /// <summary> /// Commit failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse CommitFailover(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).CommitFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Commit failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Commit failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> CommitFailoverAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CommitFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.CommitFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Disable Protection for the given protection enity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse DisableProtection(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).DisableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disable Protection for the given protection enity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> DisableProtectionAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, DisableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return operations.DisableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse EnableProtection(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enable Protection for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='input'> /// Optional. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> EnableProtectionAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, EnableProtectionInput input, CustomRequestHeaders customRequestHeaders) { return operations.EnableProtectionAsync(protectionContainerId, protectionEntityId, input, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the protection entity object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Vm object. /// </returns> public static ProtectionEntityResponse Get(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).GetAsync(protectionContainerId, protectionEntityId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the protection entity object by Id. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Vm object. /// </returns> public static Task<ProtectionEntityResponse> GetAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(protectionContainerId, protectionEntityId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the list of all protection entities. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Vm operation. /// </returns> public static ProtectionEntityListResponse List(this IProtectionEntityOperations operations, string protectionContainerId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).ListAsync(protectionContainerId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all protection entities. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Vm operation. /// </returns> public static Task<ProtectionEntityListResponse> ListAsync(this IProtectionEntityOperations operations, string protectionContainerId, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(protectionContainerId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Planned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse PlannedFailover(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).PlannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Planned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> PlannedFailoverAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, PlannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.PlannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Reprotect operation for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse Reprotect(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).ReprotectAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Reprotect operation for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Reprotect request after failover. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> ReprotectAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, ReprotectRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.ReprotectAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Synchronise Owner Information for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse SyncOwnerInformation(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).SyncOwnerInformationAsync(protectionContainerId, protectionEntityId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Synchronise Owner Information for the given protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> SyncOwnerInformationAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, CustomRequestHeaders customRequestHeaders) { return operations.SyncOwnerInformationAsync(protectionContainerId, protectionEntityId, customRequestHeaders, CancellationToken.None); } /// <summary> /// Test failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse TestFailover(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).TestFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Test failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> TestFailoverAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, TestFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.TestFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Unplanned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse UnplannedFailover(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IProtectionEntityOperations)s).UnplannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Unplanned failover of a protection entity. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.SiteRecovery.IProtectionEntityOperations. /// </param> /// <param name='protectionContainerId'> /// Required. Parent Protection Container ID. /// </param> /// <param name='protectionEntityId'> /// Required. Protection entity ID. /// </param> /// <param name='parameters'> /// Required. Planned failover request. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> UnplannedFailoverAsync(this IProtectionEntityOperations operations, string protectionContainerId, string protectionEntityId, UnplannedFailoverRequest parameters, CustomRequestHeaders customRequestHeaders) { return operations.UnplannedFailoverAsync(protectionContainerId, protectionEntityId, parameters, customRequestHeaders, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using bv.common; using bv.common.Core; using bv.common.db; using bv.common.db.Core; using bv.common.Enums; using bv.model.Model.Core; namespace eidss.avr.db.DBService.QueryBuilder { public class QuerySearchObject_DB : BaseDbService { #region Constants public const string TasQuerySearchObject = "tasQuerySearchObject"; public const string TasQuerySearchField = "tasQuerySearchField"; public const string TasQueryConditionGroup = "tasQueryConditionGroup"; public const string TasSubquery = "tasSubquery"; public const string TasSubquerySearchField = "tasSubquerySearchFields"; #endregion private IDbCommand m_CmdPostFieldCondition; #region ID Properties private long m_QuerySearchObjectID = -1L; public long QuerySearchObjectID { get { return m_QuerySearchObjectID; } set { m_QuerySearchObjectID = value; } } private long m_QueryID = -1L; public long QueryID { get { return m_QueryID; } set { m_QueryID = value; } } #endregion public QuerySearchObject_DB() { ObjectName = "QuerySearchObject"; UseDatasetCopyInPost = false; } public override DataSet GetDetail(object id) { var ds = new DataSet(); try { IDbCommand cmd = CreateSPCommand("spAsQuerySearchObject_SelectDetail"); AddParam(cmd, "@ID", id, ref m_Error); if (m_Error != null) { return (null); } AddParam(cmd, "@LangID", ModelUserContext.CurrentLanguage, ref m_Error); if (m_Error != null) { return (null); } DbDataAdapter querySearchObjectAdapter = CreateAdapter(cmd, true); querySearchObjectAdapter.Fill(ds, TasQuerySearchObject); ds.EnforceConstraints = false; CorrectTable(ds.Tables[0], TasQuerySearchObject, "idfQuerySearchObject"); CorrectTable(ds.Tables[1], TasQuerySearchField, "idfQuerySearchField"); CorrectTable(ds.Tables[2], TasQueryConditionGroup, "idfCondition"); CorrectTable(ds.Tables[3], TasSubquery, "idfQuerySearchObject"); CorrectTable(ds.Tables[4], TasSubquerySearchField, "idfQuerySearchField"); ClearColumnsAttibutes(ds); ds.Tables[TasQueryConditionGroup].Columns["SearchFieldConditionText"].MaxLength = int.MaxValue; ds.Tables[TasQueryConditionGroup].Columns["idfCondition"].AutoIncrementStep = 1; ds.Tables[TasQueryConditionGroup].Columns["idfCondition"].AutoIncrement = true; ds.Tables[TasQueryConditionGroup].Columns["idfCondition"].AutoIncrementSeed = 0; ds.Tables[TasQuerySearchField].Columns["TypeImageIndex"].ReadOnly = false; ds.Tables[TasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrementStep = -1; ds.Tables[TasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrement = true; ds.Tables[TasSubquerySearchField].Columns["idfQuerySearchField"].AutoIncrementSeed = -100000; if (ds.Tables[TasQuerySearchObject].Rows.Count == 0) { if (Utils.IsEmpty(id) || (!(id is long)) || ((long) id >= 0)) { id = m_QuerySearchObjectID; } else { m_QuerySearchObjectID = (long) id; } m_IsNewObject = true; DataRow rQso = ds.Tables[TasQuerySearchObject].NewRow(); rQso["idfQuerySearchObject"] = id; rQso["idflQuery"] = m_QueryID; rQso["intOrder"] = 0; ds.EnforceConstraints = false; ds.Tables[TasQuerySearchObject].Rows.Add(rQso); } else { m_IsNewObject = false; m_QuerySearchObjectID = (long) ds.Tables[TasQuerySearchObject].Rows[0]["idfQuerySearchObject"]; m_QueryID = (long) ds.Tables[TasQuerySearchObject].Rows[0]["idflQuery"]; } InitRootGroupCondition(ds.Tables[TasQueryConditionGroup], id); ds.EnforceConstraints = false; m_ID = id; return (ds); } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.FillDatasetError, ex); } return null; } public static DataRow InitRootGroupCondition(DataTable dt, object searchObjectID) { if (dt.Rows.Count == 0) { DataRow row = dt.NewRow(); row["idfCondition"] = 0L; row["idfQueryConditionGroup"] = -1L; row["idfQuerySearchObject"] = searchObjectID; row["intOrder"] = 0; row["idfParentQueryConditionGroup"] = DBNull.Value; row["blnJoinByOr"] = false; row["blnUseNot"] = false; row["idfQuerySearchFieldCondition"] = DBNull.Value; row["SearchFieldConditionText"] = "()"; dt.Rows.Add(row); } return dt.Rows[0]; } public static DataRow InitFilterRow (DataTable dt, object groupID, object parentGroupID, object searchObjectID, object useOr, int order = 0) { DataRow row = dt.NewRow(); row["idfQueryConditionGroup"] = groupID; row["idfParentQueryConditionGroup"] = parentGroupID; row["blnJoinByOr"] = useOr; row["blnUseNot"] = false; row["intOrder"] = order; row["idfQuerySearchObject"] = searchObjectID; row["idfSubQuerySearchObject"] = DBNull.Value; dt.Rows.Add(row); return row; } public override void AcceptChanges(DataSet ds) { // this method shoul duplicate base method bu WITHOUT line m_IsNewObject = false foreach (DataTable table in ds.Tables) { if (!SkipAcceptChanges(table)) { table.AcceptChanges(); } } RaiseAcceptChangesEvent(ds); } private void PostSubQueryWithRootObject (IDbCommand cmdSubQuery, DataRow rSubQuery, DataTable fieldTable, DataTable conditionGroupTable) { if ((cmdSubQuery == null) || (rSubQuery == null)) { return; } object strFunctionName = DBNull.Value; object idflSubQueryDescription = DBNull.Value; if (rSubQuery.RowState != DataRowState.Deleted) { object subQueryID = rSubQuery["idflQuery"]; object subQueryRootObjectID = rSubQuery["idfQuerySearchObject"]; SetParam(cmdSubQuery, "@idflSubQuery", subQueryID, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idfSubQuerySearchObject", subQueryRootObjectID, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idfsSearchObject", rSubQuery["idfsSearchObject"]); SetParam(cmdSubQuery, "@strFunctionName", strFunctionName, ParameterDirection.InputOutput); SetParam(cmdSubQuery, "@idflSubQueryDescription", idflSubQueryDescription, ParameterDirection.InputOutput); ExecCommand(cmdSubQuery, cmdSubQuery.Connection, cmdSubQuery.Transaction, true); var newSubQueryID = (long)((IDataParameter)cmdSubQuery.Parameters["@idflSubQuery"]).Value; var newSubQueryRootObjectID = (long)((IDataParameter)cmdSubQuery.Parameters["@idfSubQuerySearchObject"]).Value; if (newSubQueryRootObjectID != (long)subQueryRootObjectID) { rSubQuery["idflQuery"] = newSubQueryID; rSubQuery["idfQuerySearchObject"] = newSubQueryRootObjectID; DataRow[] fieldRows = fieldTable.Select(string.Format("idfQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow fieldRow in fieldRows) { if ((fieldRow.RowState != DataRowState.Deleted) && (Utils.Str(fieldRow["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(subQueryRootObjectID).ToLowerInvariant())) { fieldRow["idfQuerySearchObject"] = newSubQueryRootObjectID; } } DataRow[] groupRows = conditionGroupTable.Select(string.Format("idfQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow groupRow in groupRows) { if (groupRow.RowState != DataRowState.Deleted) { groupRow["idfQuerySearchObject"] = newSubQueryRootObjectID; } } groupRows = conditionGroupTable.Select(string.Format("idfSubQuerySearchObject = {0} ", subQueryRootObjectID)); foreach (DataRow groupRow in groupRows) { if (groupRow.RowState != DataRowState.Deleted) { groupRow["idfSubQuerySearchObject"] = newSubQueryRootObjectID; } } } } } private void PostField(IDbCommand cmdField, DataRow rField, DataTable fieldConditionTable) { if ((cmdField == null) || (rField == null)) { return; } object fieldID; if (rField.RowState == DataRowState.Deleted) { fieldID = rField["idfQuerySearchField", DataRowVersion.Original]; SetParam(cmdField, "@idfQuerySearchField", fieldID, ParameterDirection.InputOutput); SetParam(cmdField, "@idfQuerySearchObject", -1L); SetParam(cmdField, "@idfsSearchField", DBNull.Value); SetParam(cmdField, "@blnShow", 0); SetParam(cmdField, "@idfsParameter", DBNull.Value); ExecCommand(cmdField, cmdField.Connection, cmdField.Transaction, true); } else { fieldID = rField["idfQuerySearchField"]; SetParam(cmdField, "@idfQuerySearchField", fieldID, ParameterDirection.InputOutput); SetParam(cmdField, "@idfQuerySearchObject", rField["idfQuerySearchObject"]); SetParam(cmdField, "@idfsSearchField", rField["idfsSearchField"]); SetParam(cmdField, "@blnShow", rField["blnShow"]); SetParam(cmdField, "@idfsParameter", rField["idfsParameter"]); ExecCommand(cmdField, cmdField.Connection, cmdField.Transaction, true); long newFieldID = (long)((IDataParameter)cmdField.Parameters["@idfQuerySearchField"]).Value; if (newFieldID != (long)fieldID) { rField["idfQuerySearchField"] = newFieldID; DataRow[] rows = fieldConditionTable.Select(string.Format("idfQuerySearchField = {0} ", fieldID)); foreach (DataRow row in rows) { if (row.RowState != DataRowState.Deleted) { row["idfQuerySearchField"] = newFieldID; } } } } } private void PostFieldCondition(IDbCommand cmdFieldCondition, DataRow rFieldCondition) { if ((cmdFieldCondition == null) || (rFieldCondition == null) || rFieldCondition["idfQuerySearchField"] == DBNull.Value) { return; } SetParam(cmdFieldCondition, "@idfQueryConditionGroup", rFieldCondition["idfParentQueryConditionGroup"]); SetParam(cmdFieldCondition, "@idfQuerySearchField", rFieldCondition["idfQuerySearchField"]); SetParam(cmdFieldCondition, "@intOrder", rFieldCondition["intOrder"]); SetParam(cmdFieldCondition, "@strOperator", rFieldCondition["strOperator"]); SetParam(cmdFieldCondition, "@intOperatorType", rFieldCondition["intOperatorType"]); SetParam(cmdFieldCondition, "@blnUseNot", rFieldCondition["blnFieldConditionUseNot"]); SetParam(cmdFieldCondition, "@varValue", rFieldCondition["varValue"]); ExecCommand(cmdFieldCondition, cmdFieldCondition.Connection, cmdFieldCondition.Transaction, true); rFieldCondition["idfQuerySearchFieldCondition"] = ((IDataParameter) m_CmdPostFieldCondition.Parameters["@idfQuerySearchFieldCondition"]).Value; } private void PostGroup(IDbCommand cmdGroup, DataTable dtGroup, DataRow rGroup) { if ((cmdGroup == null) || (dtGroup == null) || (rGroup == null)) { return; } object oldGroupID = rGroup["idfQueryConditionGroup"]; SetParam(cmdGroup, "@idfQuerySearchObject", rGroup["idfQuerySearchObject"]); SetParam(cmdGroup, "@intOrder", rGroup["intOrder"]); SetParam(cmdGroup, "@idfParentQueryConditionGroup", rGroup["idfParentQueryConditionGroup"]); SetParam(cmdGroup, "@blnJoinByOr", rGroup["blnJoinByOr"]); SetParam(cmdGroup, "@blnUseNot", rGroup["blnUseNot"]); SetParam(cmdGroup, "@idfSubQuerySearchObject", rGroup["idfSubQuerySearchObject"]); ExecCommand(cmdGroup, cmdGroup.Connection, cmdGroup.Transaction, true); object groupID = ((IDataParameter) cmdGroup.Parameters["@idfQueryConditionGroup"]).Value; rGroup["idfQueryConditionGroup"] = groupID; //update all group rows with new groupID value returned by stored procedure DataRow[] drGroup = dtGroup.Select(string.Format("idfParentQueryConditionGroup = {0} and idfQueryConditionGroup is null", oldGroupID), "intOrder", DataViewRowState.CurrentRows); foreach (DataRow r in drGroup) { r["idfParentQueryConditionGroup"] = groupID; if (m_CmdPostFieldCondition == null) { m_CmdPostFieldCondition = CreateSPCommand("spAsQuerySearchFieldCondition_Post", cmdGroup.Transaction); AddTypedParam(m_CmdPostFieldCondition, "@idfQuerySearchFieldCondition", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(m_CmdPostFieldCondition, "@idfQueryConditionGroup", SqlDbType.BigInt); AddTypedParam(m_CmdPostFieldCondition, "@idfQuerySearchField", SqlDbType.BigInt); AddTypedParam(m_CmdPostFieldCondition, "@intOrder", SqlDbType.Int); AddTypedParam(m_CmdPostFieldCondition, "@strOperator", SqlDbType.NVarChar, 200); AddTypedParam(m_CmdPostFieldCondition, "@intOperatorType", SqlDbType.Int); AddTypedParam(m_CmdPostFieldCondition, "@blnUseNot", SqlDbType.Bit); AddTypedParam(m_CmdPostFieldCondition, "@varValue", SqlDbType.Variant); } PostFieldCondition(m_CmdPostFieldCondition, r); } drGroup = dtGroup.Select( string.Format("idfParentQueryConditionGroup = {0} and idfQueryConditionGroup is not null", oldGroupID), "intOrder", DataViewRowState.CurrentRows); var postedGroups = new Dictionary<long, int>(); foreach (DataRow r in drGroup) { r["idfParentQueryConditionGroup"] = groupID; if (postedGroups.ContainsKey((long) r["idfQueryConditionGroup"])) { continue; } PostGroup(cmdGroup, dtGroup, r); postedGroups.Add((long) r["idfQueryConditionGroup"], 1); } } public override bool PostDetail(DataSet ds, int postType, IDbTransaction transaction = null) { if ((ds == null) || (ds.Tables.Contains(TasQuerySearchObject) == false) || (ds.Tables.Contains(TasQuerySearchField) == false) || (ds.Tables.Contains(TasQueryConditionGroup) == false)) { return true; } if (IsNewObject) { // Update ID of object in related tables long oldQuerySearchObjectID = -1L; if ((ds.Tables[TasQuerySearchObject].Rows[0]["idfQuerySearchObject"] is long) || ds.Tables[TasQuerySearchObject].Rows[0]["idfQuerySearchObject"] is int) { oldQuerySearchObjectID = (long) (ds.Tables[TasQuerySearchObject].Rows[0]["idfQuerySearchObject"]); } ds.Tables[TasQuerySearchObject].Rows[0]["idflQuery"] = m_QueryID; ds.Tables[TasQuerySearchObject].Rows[0]["idfQuerySearchObject"] = m_QuerySearchObjectID; foreach (DataRow rField in ds.Tables[TasQuerySearchField].Rows) { if (rField.RowState != DataRowState.Deleted) { if (Utils.Str(rField["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) { rField["idfQuerySearchObject"] = m_QuerySearchObjectID; } } } foreach (DataRow rCondition in ds.Tables[TasQueryConditionGroup].Rows) { if (rCondition.RowState != DataRowState.Deleted) { if (Utils.Str(rCondition["idfQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) { rCondition["idfQuerySearchObject"] = m_QuerySearchObjectID; } } } foreach (DataRow rSubQuery in ds.Tables[TasSubquery].Rows) { if (rSubQuery.RowState != DataRowState.Deleted) { if (Utils.Str(rSubQuery["idfParentQuerySearchObject"]).ToLowerInvariant() == Utils.Str(oldQuerySearchObjectID).ToLowerInvariant()) { rSubQuery["idfParentQuerySearchObject"] = m_QuerySearchObjectID; } } } m_ID = m_QuerySearchObjectID; } try { m_CmdPostFieldCondition = null; if (ds.Tables[TasQuerySearchObject].Rows.Count > 0) { // Update Report Type for Object DataRow rObject = ds.Tables[TasQuerySearchObject].Rows[0]; IDbCommand cmdObject = CreateSPCommand("spAsQuerySearchObject_ReportTypePost", transaction); AddTypedParam(cmdObject, "@idfQuerySearchObject", SqlDbType.BigInt); AddTypedParam(cmdObject, "@idfsReportType", SqlDbType.BigInt); SetParam(cmdObject, "@idfQuerySearchObject", m_QuerySearchObjectID); SetParam(cmdObject, "@idfsReportType", rObject["idfsReportType"]); ExecCommand(cmdObject, cmdObject.Connection, cmdObject.Transaction, true); // Delete sub-queries with related objects and links from condition groups of object to sub-queries IDbCommand cmdDeleteSubQueries = CreateSPCommand("spAsQuery_DeleteSubqueries", transaction); AddTypedParam(cmdDeleteSubQueries, "@idfParentQuerySearchObject", SqlDbType.BigInt); SetParam(cmdDeleteSubQueries, "@idfParentQuerySearchObject", m_QuerySearchObjectID); ExecCommand(cmdDeleteSubQueries, cmdDeleteSubQueries.Connection, cmdDeleteSubQueries.Transaction, true); // Sub-queries with root objects if (ds.Tables[TasSubquery].Rows.Count > 0) { IDbCommand cmdSubQuery = CreateSPCommand("spAsSubQuery_PostWithRootObject", transaction); AddTypedParam(cmdSubQuery, "@idflSubQuery", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idfSubQuerySearchObject", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idfsSearchObject", SqlDbType.BigInt); AddTypedParam(cmdSubQuery, "@strFunctionName", SqlDbType.NVarChar, 200, ParameterDirection.InputOutput); AddTypedParam(cmdSubQuery, "@idflSubQueryDescription", SqlDbType.BigInt, ParameterDirection.InputOutput); foreach (DataRow rSubQuery in ds.Tables[TasSubquery].Rows) { PostSubQueryWithRootObject(cmdSubQuery, rSubQuery, ds.Tables[TasSubquerySearchField], ds.Tables[TasQueryConditionGroup]); } } // Fields IDbCommand cmdField = CreateSPCommand("spAsQuerySearchField_Post", transaction); // Fields of object AddTypedParam(cmdField, "@idfQuerySearchField", SqlDbType.BigInt, ParameterDirection.InputOutput); AddTypedParam(cmdField, "@idfQuerySearchObject", SqlDbType.BigInt); AddTypedParam(cmdField, "@idfsSearchField", SqlDbType.BigInt); AddTypedParam(cmdField, "@blnShow", SqlDbType.Bit); AddTypedParam(cmdField, "@idfsParameter", SqlDbType.BigInt); if (ds.Tables[TasQuerySearchField].Rows.Count > 0) { foreach (DataRow rField in ds.Tables[TasQuerySearchField].Rows) { PostField(cmdField, rField, ds.Tables[TasQueryConditionGroup]); } } // Fields of sub-queries if (ds.Tables[TasSubquerySearchField].Rows.Count > 0) { foreach (DataRow rSubQueryField in ds.Tables[TasSubquerySearchField].Rows) { PostField(cmdField, rSubQueryField, ds.Tables[TasQueryConditionGroup]); } } LookupCache.NotifyChange("QuerySearchField", transaction); } // Delete condition groups of object IDbCommand cmdDeleteGroups = CreateSPCommand("spAsQuerySearchObject_DeleteConditions", transaction); SetParam(cmdDeleteGroups, "@idfQuerySearchObject", m_QuerySearchObjectID); ExecCommand(cmdDeleteGroups, cmdDeleteGroups.Connection, cmdDeleteGroups.Transaction, true); // Condition groups including sub-queries if (ds.Tables[TasQueryConditionGroup].Rows.Count > 0) { IDbCommand cmdGroup = CreateSPCommandWithParams("spAsQueryConditionGroup_Post", transaction); DataRow[] dr = ds.Tables[TasQueryConditionGroup].Select("idfParentQueryConditionGroup is null", "idfQueryConditionGroup", DataViewRowState.CurrentRows); if (dr.Length > 0) { PostGroup(cmdGroup, ds.Tables[TasQueryConditionGroup], dr[0]); } } m_IsNewObject = false; } catch (Exception ex) { m_Error = new ErrorMessage(StandardError.PostError, ex); return false; } return true; } public void Copy(DataSet ds, object aID, long aQueryID) { if ((ds == null) || (ds.Tables.Contains(TasQuerySearchObject) == false) || (ds.Tables.Contains(TasQuerySearchField) == false) || (ds.Tables.Contains(TasQueryConditionGroup) == false) || (ds.Tables.Contains(TasSubquery) == false) || (ds.Tables.Contains(TasSubquerySearchField) == false) || (ds.Tables[TasQuerySearchObject].Rows.Count == 0)) { return; } if (Utils.IsEmpty(aID) || (!(aID is long)) || ((long) aID >= 0)) { aID = -1L; } m_QuerySearchObjectID = (long) aID; m_QueryID = aQueryID; m_IsNewObject = true; DataRow rQSO = ds.Tables[TasQuerySearchObject].Rows[0]; rQSO["idfQuerySearchObject"] = aID; rQSO["idflQuery"] = aQueryID; m_ID = aID; if (ds.Tables[TasQueryConditionGroup].Rows.Count == 0) { DataRow rQCG = ds.Tables[TasQueryConditionGroup].NewRow(); rQCG["idfQueryConditionGroup"] = -1L; rQCG["idfQuerySearchObject"] = aID; rQCG["intOrder"] = 0; rQCG["idfParentQueryConditionGroup"] = DBNull.Value; rQCG["blnJoinByOr"] = DBNull.Value; rQCG["blnUseNot"] = false; rQCG["idfQuerySearchFieldCondition"] = DBNull.Value; rQCG["idfSubQuerySearchObject"] = DBNull.Value; rQCG["SearchFieldConditionText"] = "()"; ds.EnforceConstraints = false; ds.Tables[TasQueryConditionGroup].Rows.Add(rQCG); } } public static void CreateNewSubQuery (DataSet ds, long queryId, long querySearchObjectId, long parentQuerySearchObjectId, long searchObjectId) { if (!ds.Tables.Contains(TasSubquery)) { return; } DataTable dt = ds.Tables[TasSubquery]; DataRow row = dt.NewRow(); row["idflQuery"] = queryId; row["idfQuerySearchObject"] = querySearchObjectId; row["idfParentQuerySearchObject"] = parentQuerySearchObjectId; row["idfsSearchObject"] = searchObjectId; dt.Rows.Add(row); } public static DataRow CreateNewSubQuerySearchField (DataSet ds, long querySearchFieldId, long querySearchObjectId, long searchFieldId, string fieldAlias) { if (!ds.Tables.Contains(TasSubquerySearchField)) { return null; } DataTable dt = ds.Tables[TasSubquerySearchField]; DataRow row = dt.NewRow(); if (querySearchFieldId != 0) //if id is passed explicitly, assign it. In other case it will be calcaulated by autoincrement { row["idfQuerySearchField"] = querySearchFieldId; } row["idfQuerySearchObject"] = querySearchObjectId; row["idfsSearchField"] = searchFieldId; row["FieldAlias"] = fieldAlias; row["blnShow"] = false; dt.Rows.Add(row); return row; } } }
using System; using System.Collections; using System.Collections.Generic; using Server; using Server.Network; using Server.Gumps; using Server.Multis; using Server.ContextMenus; namespace Server.Items { [FlipableAttribute( 0x234C, 0x234D )] public class RoseOfTrinsic : Item, ISecurable { private static readonly TimeSpan m_SpawnTime = TimeSpan.FromHours( 4.0 ); private int m_Petals; private DateTime m_NextSpawnTime; private SpawnTimer m_SpawnTimer; private SecureLevel m_Level; public override int LabelNumber{ get{ return 1062913; } } // Rose of Trinsic [CommandProperty( AccessLevel.GameMaster )] public SecureLevel Level { get{ return m_Level; } set{ m_Level = value; } } [CommandProperty( AccessLevel.GameMaster )] public int Petals { get{ return m_Petals; } set { if ( value >= 10 ) { m_Petals = 10; StopSpawnTimer(); } else { if ( value <= 0 ) m_Petals = 0; else m_Petals = value; StartSpawnTimer( m_SpawnTime ); } InvalidateProperties(); } } [Constructable] public RoseOfTrinsic() : base( 0x234D ) { Weight = 1.0; LootType = LootType.Blessed; m_Petals = 0; StartSpawnTimer( TimeSpan.FromMinutes( 1.0 ) ); } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); list.Add( 1062925, Petals.ToString() ); // Petals: ~1_COUNT~ } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { base.GetContextMenuEntries( from, list ); SetSecureLevelEntry.AddTo( from, this, list ); } private void StartSpawnTimer( TimeSpan delay ) { StopSpawnTimer(); m_SpawnTimer = new SpawnTimer( this, delay ); m_SpawnTimer.Start(); m_NextSpawnTime = DateTime.Now + delay; } private void StopSpawnTimer() { if ( m_SpawnTimer != null ) { m_SpawnTimer.Stop(); m_SpawnTimer = null; } } private class SpawnTimer : Timer { private RoseOfTrinsic m_Rose; public SpawnTimer( RoseOfTrinsic rose, TimeSpan delay ) : base( delay ) { m_Rose = rose; Priority = TimerPriority.OneMinute; } protected override void OnTick() { if ( m_Rose.Deleted ) return; m_Rose.m_SpawnTimer = null; m_Rose.Petals++; } } public override void OnDoubleClick( Mobile from ) { if ( !from.InRange( GetWorldLocation(), 2 ) ) { from.LocalOverheadMessage( MessageType.Regular, 0x3B2, 1019045 ); // I can't reach that. } else if ( Petals > 0 ) { from.AddToBackpack( new RoseOfTrinsicPetal( Petals ) ); Petals = 0; } } public RoseOfTrinsic( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( (int) 0 ); // version writer.WriteEncodedInt( (int) m_Petals ); writer.WriteDeltaTime( (DateTime) m_NextSpawnTime ); writer.WriteEncodedInt( (int) m_Level ); } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); m_Petals = reader.ReadEncodedInt(); m_NextSpawnTime = reader.ReadDeltaTime(); m_Level = (SecureLevel) reader.ReadEncodedInt(); if ( m_Petals < 10 ) StartSpawnTimer( m_NextSpawnTime - DateTime.Now ); } } public class RoseOfTrinsicPetal : Item { public override int LabelNumber{ get{ return 1062926; } } // Petal of the Rose of Trinsic [Constructable] public RoseOfTrinsicPetal() : this( 1 ) { } [Constructable] public RoseOfTrinsicPetal( int amount ) : base( 0x1021 ) { Stackable = true; Amount = amount; Weight = 1.0; Hue = 0xE; } public override void OnDoubleClick( Mobile from ) { if ( !IsChildOf( from.Backpack ) ) { from.SendLocalizedMessage( 1042038 ); // You must have the object in your backpack to use it. } else if ( from.GetStatMod( "RoseOfTrinsicPetal" ) != null ) { from.SendLocalizedMessage( 1062927 ); // You have eaten one of these recently and eating another would provide no benefit. } else { from.PlaySound( 0x1EE ); from.AddStatMod( new StatMod( StatType.Str, "RoseOfTrinsicPetal", 5, TimeSpan.FromMinutes( 5.0 ) ) ); Consume(); } } public RoseOfTrinsicPetal( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( (int) 0 ); // version } public override void Deserialize(GenericReader reader) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); } } }
// 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.Input; using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.Collections.Generic; using System.Reflection; using UnityEditor; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI.Editor { [CustomEditor(typeof(Interactable))] [CanEditMultipleObjects] public class InteractableInspector : UnityEditor.Editor { protected Interactable instance; protected SerializedProperty profileList; protected SerializedProperty statesProperty; protected SerializedProperty enabledProperty; protected SerializedProperty voiceCommands; protected SerializedProperty actionId; protected SerializedProperty isGlobal; protected SerializedProperty canSelect; protected SerializedProperty canDeselect; protected SerializedProperty startDimensionIndex; protected SerializedProperty dimensionIndex; protected SerializedProperty dimensions; protected SerializedProperty resetOnDestroy; protected const string ShowProfilesPrefKey = "InteractableInspectorProfiles"; protected const string ShowEventsPrefKey = "InteractableInspectorProfiles_ShowEvents"; protected const string ShowEventReceiversPrefKey = "InteractableInspectorProfiles_ShowEvents_Receivers"; protected bool enabled = false; protected string[] inputActionOptions = null; protected string[] speechKeywordOptions = null; private static readonly GUIContent InputActionsLabel = new GUIContent("Input Actions"); private static readonly GUIContent selectionModeLabel = new GUIContent("Selection Mode", "The selection mode of the Interactable is based on the number of dimensions available."); private static readonly GUIContent dimensionsLabel = new GUIContent("Dimensions", "The amount of theme layers for sequence button functionality (3-9)"); private static readonly GUIContent startDimensionLabel = new GUIContent("Start Dimension Index", "The dimensionIndex value to set on start."); private static readonly GUIContent isToggledLabel = new GUIContent("Is Toggled", "Should this Interactable be toggled on or off by default on start."); private static readonly GUIContent CreateThemeLabel = new GUIContent("Create and Assign New Theme", "Create a new theme"); private static readonly GUIContent SpeechComamndsLabel = new GUIContent("Speech Command", "Speech Commands to use with Interactable, pulled from MRTK/Input/Speech Commands Profile"); private static readonly GUIContent OnClickEventLabel = new GUIContent("OnClick", "Fired when this Interactable is triggered by a click."); private static readonly GUIContent AddEventReceiverLabel = new GUIContent("Add Event", "Add event receiver to this Interactable for special event handling."); private static readonly GUIContent VoiceRequiresFocusLabel = new GUIContent("Requires Focus"); protected virtual void OnEnable() { instance = (Interactable)target; profileList = serializedObject.FindProperty("profiles"); statesProperty = serializedObject.FindProperty("states"); enabledProperty = serializedObject.FindProperty("enabledOnStart"); voiceCommands = serializedObject.FindProperty("VoiceCommand"); actionId = serializedObject.FindProperty("InputActionId"); isGlobal = serializedObject.FindProperty("isGlobal"); canSelect = serializedObject.FindProperty("CanSelect"); canDeselect = serializedObject.FindProperty("CanDeselect"); startDimensionIndex = serializedObject.FindProperty("startDimensionIndex"); dimensionIndex = serializedObject.FindProperty("dimensionIndex"); dimensions = serializedObject.FindProperty("Dimensions"); resetOnDestroy = serializedObject.FindProperty("resetOnDestroy"); enabled = true; } protected virtual void RenderBaseInspector() { base.OnInspectorGUI(); } /// <remarks> /// There is a check in here that verifies whether or not we can get InputActions, if we can't we show an error help box; otherwise we get them. /// This method is sealed, if you wish to override <see cref="OnInspectorGUI"/>, then override <see cref="RenderCustomInspector"/> method instead. /// </remarks> public sealed override void OnInspectorGUI() { if ((inputActionOptions == null && !TryGetInputActions(out inputActionOptions)) || (speechKeywordOptions == null && !TryGetSpeechKeywords(out speechKeywordOptions))) { EditorGUILayout.HelpBox("Mixed Reality Toolkit is missing, configure it by invoking the 'Mixed Reality Toolkit > Add to Scene and Configure...' menu", MessageType.Error); } RenderCustomInspector(); } public virtual void RenderCustomInspector() { serializedObject.Update(); // Disable inspector UI if in play mode bool isPlayMode = EditorApplication.isPlaying || EditorApplication.isPaused; using (new EditorGUI.DisabledScope(isPlayMode)) { RenderGeneralSettings(); EditorGUILayout.Space(); RenderProfileSettings(); EditorGUILayout.Space(); RenderEventSettings(); } serializedObject.ApplyModifiedProperties(); } private void RenderProfileSettings() { if (profileList.arraySize < 1) { AddProfile(0); } if (InspectorUIUtility.DrawSectionFoldoutWithKey("Profiles", ShowProfilesPrefKey, MixedRealityStylesUtility.BoldTitleFoldoutStyle)) { EditorGUILayout.PropertyField(resetOnDestroy); // Render all profile items. Profiles are per GameObject/ThemeContainer for (int i = 0; i < profileList.arraySize; i++) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { SerializedProperty profileItem = profileList.GetArrayElementAtIndex(i); SerializedProperty hostGameObject = profileItem.FindPropertyRelative("Target"); using (new EditorGUILayout.HorizontalScope()) { EditorGUILayout.PropertyField(hostGameObject, new GUIContent("Target", "Target gameObject for this theme properties to manipulate")); if (InspectorUIUtility.SmallButton(new GUIContent(InspectorUIUtility.Minus, "Remove Profile"), i, RemoveProfile)) { // Profile removed via RemoveProfile callback continue; } } if (hostGameObject.objectReferenceValue == null) { InspectorUIUtility.DrawError("Assign a GameObject to apply visual effects"); if (GUILayout.Button("Assign Self")) { hostGameObject.objectReferenceValue = instance.gameObject; } } SerializedProperty themes = profileItem.FindPropertyRelative("Themes"); ValidateThemesForDimensions(dimensions, themes); // Render all themes for current target for (int t = 0; t < themes.arraySize; t++) { SerializedProperty themeItem = themes.GetArrayElementAtIndex(t); string themeLabel = BuildThemeTitle(dimensions.intValue, t); if (themeItem.objectReferenceValue != null) { bool showThemeSettings = false; using (new EditorGUILayout.HorizontalScope()) { string prefKey = themeItem.objectReferenceValue.name + "Profiles" + i + "_Theme" + t + "_Edit"; showThemeSettings = InspectorUIUtility.DrawSectionFoldoutWithKey(themeLabel, prefKey, null, false); EditorGUILayout.PropertyField(themeItem, new GUIContent(string.Empty, "Theme properties for interaction feedback")); } if (themeItem.objectReferenceValue != null) { // TODO: Odd bug where themeStates below is null when it shouldn't be. Use instance object as workaround atm // SerializedProperty themeStates = themeItem.FindPropertyRelative("States"); var themeInstance = themeItem.objectReferenceValue as Theme; if (statesProperty.objectReferenceValue != themeInstance.States) { InspectorUIUtility.DrawWarning($"{themeInstance.name}'s States property does not match Interactable's States property"); } if (showThemeSettings) { using (new EditorGUI.IndentLevelScope()) { UnityEditor.Editor themeEditor = UnityEditor.Editor.CreateEditor(themeItem.objectReferenceValue); themeEditor.OnInspectorGUI(); } } } } else { EditorGUILayout.PropertyField(themeItem, new GUIContent(themeLabel, "Theme properties for interaction feedback")); InspectorUIUtility.DrawError("Assign a Theme to add visual effects"); if (GUILayout.Button(CreateThemeLabel)) { themeItem.objectReferenceValue = CreateThemeAsset(hostGameObject.objectReferenceValue.name); return; } } EditorGUILayout.Space(); } } } if (GUILayout.Button(new GUIContent("Add Profile"))) { AddProfile(profileList.arraySize); } } } private void RenderEventSettings() { if (InspectorUIUtility.DrawSectionFoldoutWithKey("Events", ShowEventsPrefKey, MixedRealityStylesUtility.BoldTitleFoldoutStyle)) { using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { EditorGUILayout.PropertyField(serializedObject.FindProperty("OnClick"), OnClickEventLabel); if (InspectorUIUtility.DrawSectionFoldoutWithKey("Receivers", ShowEventReceiversPrefKey, MixedRealityStylesUtility.TitleFoldoutStyle, false)) { SerializedProperty events = serializedObject.FindProperty("Events"); for (int i = 0; i < events.arraySize; i++) { SerializedProperty eventItem = events.GetArrayElementAtIndex(i); if (InteractableEventInspector.RenderEvent(eventItem)) { events.DeleteArrayElementAtIndex(i); // If removed, skip rendering rest of list till next redraw break; } EditorGUILayout.Space(); } if (GUILayout.Button(AddEventReceiverLabel)) { AddEvent(events.arraySize); } } } } } protected void RenderGeneralSettings() { Rect position; using (new EditorGUILayout.HorizontalScope()) { InspectorUIUtility.DrawLabel("General", InspectorUIUtility.TitleFontSize, InspectorUIUtility.ColorTint10); if (target != null) { var helpURL = target.GetType().GetCustomAttribute<HelpURLAttribute>(); if (helpURL != null) { InspectorUIUtility.RenderDocumentationButton(helpURL.URL); } } } using (new EditorGUILayout.VerticalScope(EditorStyles.helpBox)) { // If states value is not provided, try to use Default states type if (statesProperty.objectReferenceValue == null) { statesProperty.objectReferenceValue = GetDefaultInteractableStatesFile(); } EditorGUILayout.PropertyField(statesProperty, new GUIContent("States")); if (statesProperty.objectReferenceValue == null) { InspectorUIUtility.DrawError("Please assign a States object!"); serializedObject.ApplyModifiedProperties(); return; } EditorGUILayout.PropertyField(enabledProperty, new GUIContent("Enabled")); // Input Actions bool validActionOptions = inputActionOptions != null; using (new EditorGUI.DisabledScope(!validActionOptions)) { var actionOptions = validActionOptions ? inputActionOptions : new string[] { "Missing Mixed Reality Toolkit" }; DrawDropDownProperty(EditorGUILayout.GetControlRect(), actionId, actionOptions, InputActionsLabel); } using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(isGlobal, new GUIContent("Is Global")); } // Speech keywords bool validSpeechKeywords = speechKeywordOptions != null; using (new EditorGUI.DisabledScope(!validSpeechKeywords)) { string[] keywordOptions = validSpeechKeywords ? speechKeywordOptions : new string[] { "Missing Speech Commands" }; int currentIndex = validSpeechKeywords ? SpeechKeywordLookup(voiceCommands.stringValue, speechKeywordOptions) : 0; position = EditorGUILayout.GetControlRect(); // BeginProperty allows tracking of serialized properties for bolding prefab changes etc using (new EditorGUI.PropertyScope(position, SpeechComamndsLabel, voiceCommands)) { currentIndex = EditorGUI.Popup(position, SpeechComamndsLabel.text, currentIndex, keywordOptions); if (validSpeechKeywords) { voiceCommands.stringValue = currentIndex > 0 ? speechKeywordOptions[currentIndex] : string.Empty; } } } // show requires gaze because voice command has a value if (!string.IsNullOrEmpty(voiceCommands.stringValue)) { using (new EditorGUI.IndentLevelScope()) { SerializedProperty requireGaze = serializedObject.FindProperty("voiceRequiresFocus"); EditorGUILayout.PropertyField(requireGaze, VoiceRequiresFocusLabel); } } // should be 1 or more dimensions.intValue = Mathf.Clamp(dimensions.intValue, 1, 9); // user-friendly dimension settings SelectionModes selectionMode = SelectionModes.Button; position = EditorGUILayout.GetControlRect(); using (new EditorGUI.PropertyScope(position, selectionModeLabel, dimensions)) { // Show enum popup for selection mode, hide option to select SelectionModes.Invalid selectionMode = (SelectionModes)EditorGUI.EnumPopup(position, selectionModeLabel, Interactable.ConvertToSelectionMode(dimensions.intValue), (value) => { return (SelectionModes)value != SelectionModes.Invalid; } ); switch (selectionMode) { case SelectionModes.Button: dimensions.intValue = 1; break; case SelectionModes.Toggle: dimensions.intValue = 2; break; case SelectionModes.MultiDimension: // multi dimension mode - set min value to 3 dimensions.intValue = Mathf.Max(3, dimensions.intValue); position = EditorGUILayout.GetControlRect(); dimensions.intValue = EditorGUI.IntField(position, dimensionsLabel, dimensions.intValue); break; default: break; } } if (dimensions.intValue > 1) { // toggle or multi dimensional button using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(canSelect, new GUIContent("Can Select", "The user can toggle this button")); EditorGUILayout.PropertyField(canDeselect, new GUIContent("Can Deselect", "The user can untoggle this button, set false for a radial interaction.")); position = EditorGUILayout.GetControlRect(); using (new EditorGUI.PropertyScope(position, startDimensionLabel, startDimensionIndex)) { var mode = Interactable.ConvertToSelectionMode(dimensions.intValue); if (mode == SelectionModes.Toggle) { bool isToggled = EditorGUI.Toggle(position, isToggledLabel, startDimensionIndex.intValue > 0); startDimensionIndex.intValue = isToggled ? 1 : 0; } else if (mode == SelectionModes.MultiDimension) { startDimensionIndex.intValue = EditorGUI.IntField(position, startDimensionLabel, startDimensionIndex.intValue); } startDimensionIndex.intValue = Mathf.Clamp(startDimensionIndex.intValue, 0, dimensions.intValue - 1); } } } } } public static States GetDefaultInteractableStatesFile() { AssetDatabase.Refresh(); string[] stateLocations = AssetDatabase.FindAssets("DefaultInteractableStates"); if (stateLocations.Length > 0) { for (int i = 0; i < stateLocations.Length; i++) { string path = AssetDatabase.GUIDToAssetPath(stateLocations[i]); States defaultStates = (States)AssetDatabase.LoadAssetAtPath(path, typeof(States)); if (defaultStates != null) { return defaultStates; } } } return null; } private static string BuildThemeTitle(int dimensions, int themeIndex) { if (dimensions == 2) { return "Theme " + (themeIndex % 2 == 0 ? "(Deselected)" : "(Selected)"); } else if (dimensions >= 3) { return "Theme " + (themeIndex + 1); } return "Theme"; } #region Profiles protected void AddProfile(int index) { profileList.InsertArrayElementAtIndex(profileList.arraySize); SerializedProperty newProfile = profileList.GetArrayElementAtIndex(profileList.arraySize - 1); SerializedProperty newTarget = newProfile.FindPropertyRelative("Target"); SerializedProperty themes = newProfile.FindPropertyRelative("Themes"); newTarget.objectReferenceValue = null; themes.ClearArray(); } protected void RemoveProfile(int index, SerializedProperty prop = null) { profileList.DeleteArrayElementAtIndex(index); } #endregion Profiles #region Themes protected static Theme CreateThemeAsset(string themeName = null) { string themeFileName = (string.IsNullOrEmpty(themeName) ? "New " : themeName) + "Theme.asset"; string path = EditorUtility.SaveFilePanelInProject( "Save New Theme", themeFileName, "asset", "Create a name and select a location for this theme"); if (path.Length != 0) { Theme newTheme = ScriptableObject.CreateInstance<Theme>(); newTheme.States = GetDefaultInteractableStatesFile(); newTheme.Definitions = new List<ThemeDefinition>(); AssetDatabase.CreateAsset(newTheme, path); return newTheme; } return null; } /// <summary> /// Ensure the number of theme containers is equal to the number of dimensions /// </summary> /// <param name="dimensions">dimensions property of interactable</param> /// <param name="themes">List of ThemeContainers in Interactable profile</param> private static void ValidateThemesForDimensions(SerializedProperty dimensions, SerializedProperty themes) { int numOfDimensions = dimensions.intValue; if (themes.arraySize < numOfDimensions) { for (int index = themes.arraySize; index < numOfDimensions; index++) { themes.InsertArrayElementAtIndex(themes.arraySize); SerializedProperty newTheme = themes.GetArrayElementAtIndex(themes.arraySize - 1); newTheme.objectReferenceValue = null; } } else { for (int index = themes.arraySize - 1; index > numOfDimensions - 1; index--) { themes.DeleteArrayElementAtIndex(index); } } } #endregion Themes #region Events protected void RemoveEvent(int index, SerializedProperty prop = null) { SerializedProperty events = serializedObject.FindProperty("Events"); if (events.arraySize > index) { events.DeleteArrayElementAtIndex(index); } } protected void AddEvent(int index) { SerializedProperty events = serializedObject.FindProperty("Events"); events.InsertArrayElementAtIndex(events.arraySize); } #endregion Events #region PopupUtilities /// <summary> /// Get the index of the speech keyword array item based on its name, pop-up field helper /// Skips the first item in the array (internal added blank value to turn feature off) /// and returns a 0 if no match is found for the blank value /// </summary> protected int SpeechKeywordLookup(string option, string[] options) { // starting on 1 to skip the blank value for (int i = 1; i < options.Length; i++) { if (options[i] == option) { return i; } } return 0; } /// <summary> /// Draws a popup UI with PropertyField type features. /// Displays prefab pending updates /// </summary> protected void DrawDropDownProperty(Rect position, SerializedProperty prop, string[] options, GUIContent label) { EditorGUI.BeginProperty(position, label, prop); { prop.intValue = EditorGUI.Popup(position, label.text, prop.intValue, options); } EditorGUI.EndProperty(); } #endregion KeywordUtilities #region Inspector Helpers /// <summary> /// Get a list of Mixed Reality Input Actions from the input actions profile. /// </summary> public static bool TryGetInputActions(out string[] descriptionsArray) { if (!MixedRealityToolkit.ConfirmInitialized() || !MixedRealityToolkit.Instance.HasActiveProfile) { descriptionsArray = null; return false; } MixedRealityInputAction[] actions = CoreServices.InputSystem.InputSystemProfile.InputActionsProfile.InputActions; descriptionsArray = new string[actions.Length]; for (int i = 0; i < actions.Length; i++) { descriptionsArray[i] = actions[i].Description; } return true; } /// <summary> /// Try to get a list of speech commands from the MRTK/Input/SpeechCommands profile /// </summary> public static bool TryGetMixedRealitySpeechCommands(out SpeechCommands[] commands) { if (!MixedRealityToolkit.ConfirmInitialized() || !MixedRealityToolkit.Instance.HasActiveProfile) { commands = null; return false; } MixedRealityInputSystemProfile inputSystemProfile = CoreServices.InputSystem?.InputSystemProfile; if (inputSystemProfile != null && inputSystemProfile.SpeechCommandsProfile != null) { commands = inputSystemProfile.SpeechCommandsProfile.SpeechCommands; } else { commands = null; } if (commands == null || commands.Length < 1) { return false; } return true; } /// <summary> /// Look for speech commands in the MRTK Speech Command profile /// Adds a blank value at index zero so the developer can turn the feature off. /// </summary> public static bool TryGetSpeechKeywords(out string[] keywords) { SpeechCommands[] commands; if (!TryGetMixedRealitySpeechCommands(out commands)) { keywords = null; return false; } List<string> keys = new List<string> { "(No Selection)" }; for (var i = 0; i < commands.Length; i++) { keys.Add(commands[i].Keyword); } keywords = keys.ToArray(); return true; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="MessageQueueEnumerator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Messaging { using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System; using System.Collections; using System.Messaging.Interop; using System.Globalization; /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator"]/*' /> /// <devdoc> /// <para>Provides (forward-only) cursor semantics to enumerate the queues on a /// computer.</para> /// <note type="rnotes"> /// I'm assuming all the queues have to /// be /// on the same computer. Is this the case? Do we want to translate this reference /// to "cursor semantics" into English, or is it okay as it stands? Will the users /// understand the concept of a cursor? /// </note> /// </devdoc> public class MessageQueueEnumerator : MarshalByRefObject, IEnumerator, IDisposable { private MessageQueueCriteria criteria; private LocatorHandle locatorHandle = System.Messaging.Interop.LocatorHandle.InvalidHandle; private MessageQueue currentMessageQueue; private bool checkSecurity; private bool disposed; /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.MessageQueueEnumerator"]/*' /> /// <internalonly/> internal MessageQueueEnumerator(MessageQueueCriteria criteria) { this.criteria = criteria; this.checkSecurity = true; } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.MessageQueueEnumerator1"]/*' /> /// <internalonly/> internal MessageQueueEnumerator(MessageQueueCriteria criteria, bool checkSecurity) { this.criteria = criteria; this.checkSecurity = checkSecurity; } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.Current"]/*' /> /// <devdoc> /// Returns the current MessageQueue of the enumeration. /// Before the first call to MoveNext and following a call to MoveNext that /// returned false an InvalidOperationException will be thrown. Multiple /// calls to Current with no intervening calls to MoveNext will return the /// same MessageQueue object. /// </devdoc> public MessageQueue Current { get { if (this.currentMessageQueue == null) throw new InvalidOperationException(Res.GetString(Res.NoCurrentMessageQueue)); return this.currentMessageQueue; } } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.IEnumerator.Current"]/*' /> /// <internalonly/> object IEnumerator.Current { get { return this.Current; } } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.Close"]/*' /> /// <devdoc> /// <para>Frees the managed resources associated with the enumerator.</para> /// </devdoc> public void Close() { if (!this.locatorHandle.IsInvalid) { this.locatorHandle.Close(); this.currentMessageQueue = null; } } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.Dispose"]/*' /> /// <devdoc> /// </devdoc> [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] public void Dispose() { Dispose(true); } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.Dispose1"]/*' /> /// <devdoc> /// <para> /// </para> /// </devdoc> [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "currentMessageQueue")] protected virtual void Dispose(bool disposing) { if (disposing) { this.Close(); } this.disposed = true; } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.LocatorHandle"]/*' /> /// <devdoc> /// <para>Indicates the native Message Queuing handle used to locate queues in a network. This /// property is read-only.</para> /// </devdoc> public IntPtr LocatorHandle { get { return this.Handle.DangerousGetHandle(); } } LocatorHandle Handle { get { if (this.locatorHandle.IsInvalid) { //Cannot allocate the locatorHandle if the object has been disposed, since finalization has been suppressed. if (this.disposed) throw new ObjectDisposedException(GetType().Name); if (this.checkSecurity) { MessageQueuePermission permission = new MessageQueuePermission(MessageQueuePermissionAccess.Browse, MessageQueuePermission.Any); permission.Demand(); } Columns columns = new Columns(2); LocatorHandle enumHandle; columns.AddColumnId(NativeMethods.QUEUE_PROPID_PATHNAME); //Adding the instance property avoids accessing the DS a second //time, the formatName can be resolved by calling MQInstanceToFormatName columns.AddColumnId(NativeMethods.QUEUE_PROPID_INSTANCE); int status; if (this.criteria != null) status = UnsafeNativeMethods.MQLocateBegin(null, this.criteria.Reference, columns.GetColumnsRef(), out enumHandle); else status = UnsafeNativeMethods.MQLocateBegin(null, null, columns.GetColumnsRef(), out enumHandle); if (MessageQueue.IsFatalError(status)) throw new MessageQueueException(status); this.locatorHandle = enumHandle; } return this.locatorHandle; } } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.MoveNext"]/*' /> /// <devdoc> /// <para> /// Advances the enumerator to the next queue of the enumeration, if one /// is currently available.</para> /// </devdoc> public bool MoveNext() { MQPROPVARIANTS[] array = new MQPROPVARIANTS[2]; int propertyCount; string currentItem; byte[] currentGuid = new byte[16]; string machineName = null; if (this.criteria != null && this.criteria.FilterMachine) { if (this.criteria.MachineName.CompareTo(".") == 0) machineName = MessageQueue.ComputerName + "\\"; else machineName = this.criteria.MachineName + "\\"; } do { propertyCount = 2; int status; status = SafeNativeMethods.MQLocateNext(this.Handle, ref propertyCount, array); if (MessageQueue.IsFatalError(status)) throw new MessageQueueException(status); if (propertyCount != 2) { this.currentMessageQueue = null; return false; } //Using Unicode API even on Win9x currentItem = Marshal.PtrToStringUni(array[0].ptr); Marshal.Copy(array[1].ptr, currentGuid, 0, 16); //MSMQ allocated this memory, lets free it. SafeNativeMethods.MQFreeMemory(array[0].ptr); SafeNativeMethods.MQFreeMemory(array[1].ptr); } while (machineName != null && (machineName.Length >= currentItem.Length || String.Compare(machineName, 0, currentItem, 0, machineName.Length, true, CultureInfo.InvariantCulture) != 0)); this.currentMessageQueue = new MessageQueue(currentItem, new Guid(currentGuid)); return true; } /// <include file='doc\MessageQueueEnumerator.uex' path='docs/doc[@for="MessageQueueEnumerator.Reset"]/*' /> /// <devdoc> /// <para>Resets the cursor, so it points to the head of the list..</para> /// </devdoc> public void Reset() { this.Close(); } } }
/* Distributed as part of TiledSharp, Copyright 2012 Marshall Ward * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Xml.Linq; namespace TiledSharp { // TODO: The design here is all wrong. A Tileset should be a list of tiles, // it shouldn't force the user to do so much tile ID management public class TmxTileset : TmxDocument, ITmxElement { public int FirstGid {get; private set;} public string Name {get; private set;} public int TileWidth {get; private set;} public int TileHeight {get; private set;} public int Spacing {get; private set;} public int Margin {get; private set;} public int? Columns {get; private set;} public int? TileCount {get; private set;} public Dictionary<int, TmxTilesetTile> Tiles {get; private set;} public TmxTileOffset TileOffset {get; private set;} public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxTerrain> Terrains {get; private set;} // TSX file constructor public TmxTileset(XContainer xDoc, string tmxDir) : this(xDoc.Element("tileset"), tmxDir) { } // TMX tileset element constructor public TmxTileset(XElement xTileset, string tmxDir = "") { var xFirstGid = xTileset.Attribute("firstgid"); var source = (string) xTileset.Attribute("source"); if (source != null) { // Prepend the parent TMX directory if necessary source = Path.Combine(tmxDir, source); // source is always preceded by firstgid FirstGid = (int) xFirstGid; // Everything else is in the TSX file var xDocTileset = ReadXml(source); var ts = new TmxTileset(xDocTileset, TmxDirectory); Name = ts.Name; TileWidth = ts.TileWidth; TileHeight = ts.TileHeight; Spacing = ts.Spacing; Margin = ts.Margin; Columns = ts.Columns; TileCount = ts.TileCount; TileOffset = ts.TileOffset; Image = ts.Image; Terrains = ts.Terrains; Tiles = ts.Tiles; Properties = ts.Properties; } else { // firstgid is always in TMX, but not TSX if (xFirstGid != null) FirstGid = (int) xFirstGid; Name = (string) xTileset.Attribute("name"); TileWidth = (int) xTileset.Attribute("tilewidth"); TileHeight = (int) xTileset.Attribute("tileheight"); Spacing = (int?) xTileset.Attribute("spacing") ?? 0; Margin = (int?) xTileset.Attribute("margin") ?? 0; Columns = (int?) xTileset.Attribute("columns"); TileCount = (int?) xTileset.Attribute("tilecount"); TileOffset = new TmxTileOffset(xTileset.Element("tileoffset")); Image = new TmxImage(xTileset.Element("image"), tmxDir); Terrains = new TmxList<TmxTerrain>(); var xTerrainType = xTileset.Element("terraintypes"); if (xTerrainType != null) { foreach (var e in xTerrainType.Elements("terrain")) Terrains.Add(new TmxTerrain(e)); } Tiles = new Dictionary<int, TmxTilesetTile>(); foreach (var xTile in xTileset.Elements("tile")) { var tile = new TmxTilesetTile(xTile, Terrains, tmxDir); Tiles[tile.Id] = tile; } Properties = new PropertyDict(xTileset.Element("properties")); } } } public class TmxTileOffset { public int X {get; private set;} public int Y {get; private set;} public TmxTileOffset(XElement xTileOffset) { if (xTileOffset == null) { X = 0; Y = 0; } else { X = (int)xTileOffset.Attribute("x"); Y = (int)xTileOffset.Attribute("y"); } } } public class TmxTerrain : ITmxElement { public string Name {get; private set;} public int Tile {get; private set;} public PropertyDict Properties {get; private set;} public TmxTerrain(XElement xTerrain) { Name = (string)xTerrain.Attribute("name"); Tile = (int)xTerrain.Attribute("tile"); Properties = new PropertyDict(xTerrain.Element("properties")); } } public class TmxTilesetTile { public int Id {get; private set;} public Collection<TmxTerrain> TerrainEdges {get; private set;} public double Probability {get; private set;} public string Type { get; private set; } public PropertyDict Properties {get; private set;} public TmxImage Image {get; private set;} public TmxList<TmxObjectGroup> ObjectGroups {get; private set;} public Collection<TmxAnimationFrame> AnimationFrames {get; private set;} // Human-readable aliases to the Terrain markers public TmxTerrain TopLeft { get { return TerrainEdges[0]; } } public TmxTerrain TopRight { get { return TerrainEdges[1]; } } public TmxTerrain BottomLeft { get { return TerrainEdges[2]; } } public TmxTerrain BottomRight { get { return TerrainEdges[3]; } } public TmxTilesetTile(XElement xTile, TmxList<TmxTerrain> Terrains, string tmxDir = "") { Id = (int)xTile.Attribute("id"); TerrainEdges = new Collection<TmxTerrain>(); int result; TmxTerrain edge; var strTerrain = (string)xTile.Attribute("terrain") ?? ",,,"; foreach (var v in strTerrain.Split(',')) { var success = int.TryParse(v, out result); if (success) edge = Terrains[result]; else edge = null; TerrainEdges.Add(edge); // TODO: Assert that TerrainEdges length is 4 } Probability = (double?)xTile.Attribute("probability") ?? 1.0; Type = (string)xTile.Attribute("type"); Image = new TmxImage(xTile.Element("image"), tmxDir); ObjectGroups = new TmxList<TmxObjectGroup>(); foreach (var e in xTile.Elements("objectgroup")) ObjectGroups.Add(new TmxObjectGroup(e)); AnimationFrames = new Collection<TmxAnimationFrame>(); if (xTile.Element("animation") != null) { foreach (var e in xTile.Element("animation").Elements("frame")) AnimationFrames.Add(new TmxAnimationFrame(e)); } Properties = new PropertyDict(xTile.Element("properties")); } } public class TmxAnimationFrame { public int Id {get; private set;} public int Duration {get; private set;} public TmxAnimationFrame(XElement xFrame) { Id = (int)xFrame.Attribute("tileid"); Duration = (int)xFrame.Attribute("duration"); } } }
using System; using System.Data; using System.IO; using NUnit.Framework; namespace FileHelpers.Tests.CommonTests { [TestFixture] public class Readers { private FileHelperAsyncEngine asyncEngine; [Test] public void ReadFile() { var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = TestCommon.ReadTest<SampleType>(engine, "Good", "Test1.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } #if !NETCOREAPP [Test] public void ReadFileStatic() { SampleType[] res; res = (SampleType[]) CommonEngine.ReadFile(typeof (SampleType), FileTest.Good.Test1.Path); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } #endif [Test] public void AsyncRead() { asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); SampleType rec1, rec2; TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); rec1 = (SampleType) asyncEngine.ReadNext(); Assert.IsNotNull(rec1); rec2 = (SampleType) asyncEngine.ReadNext(); Assert.IsNotNull(rec1); Assert.IsTrue(rec1 != rec2); rec1 = (SampleType) asyncEngine.ReadNext(); Assert.IsNotNull(rec2); rec1 = (SampleType) asyncEngine.ReadNext(); Assert.IsNotNull(rec2); Assert.IsTrue(rec1 != rec2); Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount); asyncEngine.Close(); } [Test] public void AsyncReadMoreAndMore() { asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); SampleType rec1; TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); rec1 = (SampleType) asyncEngine.ReadNext(); rec1 = (SampleType) asyncEngine.ReadNext(); rec1 = (SampleType) asyncEngine.ReadNext(); rec1 = (SampleType) asyncEngine.ReadNext(); rec1 = (SampleType) asyncEngine.ReadNext(); Assert.IsTrue(rec1 == null); rec1 = (SampleType) asyncEngine.ReadNext(); Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount); asyncEngine.Close(); } [Test] public void AsyncRead2() { SampleType rec1; asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); int lineAnt = asyncEngine.LineNumber; while (asyncEngine.ReadNext() != null) { rec1 = (SampleType) asyncEngine.LastRecord; Assert.IsNotNull(rec1); Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber); lineAnt = asyncEngine.LineNumber; } Assert.AreEqual(4, asyncEngine.TotalRecords); Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount); asyncEngine.Close(); } [Test] public void AsyncReadEnumerable() { asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); int lineAnt = asyncEngine.LineNumber; foreach (SampleType rec1 in asyncEngine) { Assert.IsNotNull(rec1); Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber); lineAnt = asyncEngine.LineNumber; } Assert.AreEqual(4, asyncEngine.TotalRecords); Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount); asyncEngine.Close(); } [Test] public void AsyncReadEnumerableBad() { asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); Assert.Throws<FileHelpersException>(() => { foreach (SampleType rec1 in asyncEngine) rec1.ToString(); }); asyncEngine.Close(); } [Test] public void AsyncReadEnumerable2() { using (asyncEngine = new FileHelperAsyncEngine(typeof (SampleType))) { TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); int lineAnt = asyncEngine.LineNumber; foreach (SampleType rec1 in asyncEngine) { Assert.IsNotNull(rec1); Assert.AreEqual(lineAnt + 1, asyncEngine.LineNumber); lineAnt = asyncEngine.LineNumber; } } Assert.AreEqual(4, asyncEngine.TotalRecords); Assert.AreEqual(0, asyncEngine.ErrorManager.ErrorCount); asyncEngine.Close(); } [Test] public void AsyncReadEnumerableAutoDispose() { asyncEngine = new FileHelperAsyncEngine(typeof (SampleType)); TestCommon.BeginReadTest(asyncEngine, "Good", "Test1.txt"); asyncEngine.ReadNext(); asyncEngine.ReadNext(); asyncEngine.Close(); } [Test] public void ReadStream() { string data = "11121314901234" + Environment.NewLine + "10111314012345" + Environment.NewLine + "11101314123456" + Environment.NewLine + "10101314234567" + Environment.NewLine; var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = engine.ReadStream(new StringReader(data)); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } [Test] public void ReadString() { string data = "11121314901234" + Environment.NewLine + "10111314012345" + Environment.NewLine + "11101314123456" + Environment.NewLine + "10101314234567" + Environment.NewLine; var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = engine.ReadString(data); Assert.AreEqual(4, res.Length); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } #if !NETCOREAPP [Test] public void ReadStringStatic() { string data = "11121314901234" + Environment.NewLine + "10111314012345" + Environment.NewLine + "11101314123456" + Environment.NewLine + "10101314234567" + Environment.NewLine; SampleType[] res; res = CommonEngine.ReadString<SampleType>(data); Assert.AreEqual(4, res.Length); Assert.AreEqual(new DateTime(1314, 12, 11), res[0].Field1); Assert.AreEqual("901", res[0].Field2); Assert.AreEqual(234, res[0].Field3); Assert.AreEqual(new DateTime(1314, 11, 10), res[1].Field1); Assert.AreEqual("012", res[1].Field2); Assert.AreEqual(345, res[1].Field3); } #endif [Test] public void ReadEmpty() { string data = ""; var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = engine.ReadStream(new StringReader(data)); Assert.AreEqual(0, res.Length); Assert.AreEqual(0, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); } [Test] public void ReadEmptyStream() { var engine = new FileHelperEngine<SampleType>(); SampleType[] res; res = TestCommon.ReadTest<SampleType>(engine, "Good", "TestEmpty.txt"); Assert.AreEqual(0, res.Length); Assert.AreEqual(0, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); } [Test] public void ReadFileAsDataTable() { var engine = new FileHelperEngine<SampleType>(); DataTable res; res = engine.ReadFileAsDT(FileTest.Good.Test1.Path); Assert.AreEqual(4, res.Rows.Count); Assert.AreEqual(4, engine.TotalRecords); Assert.AreEqual(0, engine.ErrorManager.ErrorCount); Assert.AreEqual(new DateTime(1314, 12, 11), res.Rows[0]["Field1"]); Assert.AreEqual("901", res.Rows[0]["Field2"]); Assert.AreEqual(234, res.Rows[0]["Field3"]); Assert.AreEqual(new DateTime(1314, 11, 10), res.Rows[1]["Field1"]); Assert.AreEqual("012", res.Rows[1]["Field2"]); Assert.AreEqual(345, res.Rows[1]["Field3"]); } [Test] public void ReadAsyncFieldIndex() { string data = "11121314901234" + Environment.NewLine + "10111314012345" + Environment.NewLine + "11101314123456" + Environment.NewLine + "10101314234567" + Environment.NewLine; var asyncEngine = new FileHelperAsyncEngine<SampleType>(); asyncEngine.BeginReadString(data); foreach (var rec in asyncEngine) { Assert.AreEqual(rec.Field1, asyncEngine[0]); Assert.AreEqual(rec.Field2, asyncEngine[1]); Assert.AreEqual(rec.Field3, asyncEngine[2]); Assert.AreEqual(rec.Field1, asyncEngine["Field1"]); Assert.AreEqual(rec.Field2, asyncEngine["Field2"]); Assert.AreEqual(rec.Field3, asyncEngine["Field3"]); } asyncEngine.Close(); } } }
/* * 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; using System.Collections.Generic; using System.Reflection; using System.Threading; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Capabilities; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; using OpenSim.Capabilities.Handlers; namespace OpenSim.Region.ClientStack.Linden { /// <summary> /// This module implements both WebFetchInventoryDescendents and FetchInventoryDescendents2 capabilities. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WebFetchInvDescModule")] public class WebFetchInvDescModule : INonSharedRegionModule { class aPollRequest { public PollServiceInventoryEventArgs thepoll; public UUID reqID; public Hashtable request; public ScenePresence presence; public List<UUID> folders; } private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Control whether requests will be processed asynchronously. /// </summary> /// <remarks> /// Defaults to true. Can currently not be changed once a region has been added to the module. /// </remarks> public bool ProcessQueuedRequestsAsync { get; private set; } /// <summary> /// Number of inventory requests processed by this module. /// </summary> /// <remarks> /// It's the PollServiceRequestManager that actually sends completed requests back to the requester. /// </remarks> public static int ProcessedRequestsCount { get; set; } private static Stat s_queuedRequestsStat; private static Stat s_processedRequestsStat; public Scene Scene { get; private set; } private IInventoryService m_InventoryService; private ILibraryService m_LibraryService; private bool m_Enabled; private string m_fetchInventoryDescendents2Url; private string m_webFetchInventoryDescendentsUrl; private static FetchInvDescHandler m_webFetchHandler; private static Thread[] m_workerThreads = null; private static DoubleQueue<aPollRequest> m_queue = new DoubleQueue<aPollRequest>(); #region ISharedRegionModule Members public WebFetchInvDescModule() : this(true) {} public WebFetchInvDescModule(bool processQueuedResultsAsync) { ProcessQueuedRequestsAsync = processQueuedResultsAsync; } public void Initialise(IConfigSource source) { IConfig config = source.Configs["ClientStack.LindenCaps"]; if (config == null) return; m_fetchInventoryDescendents2Url = config.GetString("Cap_FetchInventoryDescendents2", string.Empty); m_webFetchInventoryDescendentsUrl = config.GetString("Cap_WebFetchInventoryDescendents", string.Empty); if (m_fetchInventoryDescendents2Url != string.Empty || m_webFetchInventoryDescendentsUrl != string.Empty) { m_Enabled = true; } } public void AddRegion(Scene s) { if (!m_Enabled) return; Scene = s; } public void RemoveRegion(Scene s) { if (!m_Enabled) return; Scene.EventManager.OnRegisterCaps -= RegisterCaps; StatsManager.DeregisterStat(s_processedRequestsStat); StatsManager.DeregisterStat(s_queuedRequestsStat); if (ProcessQueuedRequestsAsync) { if (m_workerThreads != null) { foreach (Thread t in m_workerThreads) Watchdog.AbortThread(t.ManagedThreadId); m_workerThreads = null; } } Scene = null; } public void RegionLoaded(Scene s) { if (!m_Enabled) return; if (s_processedRequestsStat == null) s_processedRequestsStat = new Stat( "ProcessedFetchInventoryRequests", "Number of processed fetch inventory requests", "These have not necessarily yet been dispatched back to the requester.", "", "inventory", "httpfetch", StatType.Pull, MeasuresOfInterest.AverageChangeOverTime, stat => { stat.Value = ProcessedRequestsCount; }, StatVerbosity.Debug); if (s_queuedRequestsStat == null) s_queuedRequestsStat = new Stat( "QueuedFetchInventoryRequests", "Number of fetch inventory requests queued for processing", "", "", "inventory", "httpfetch", StatType.Pull, MeasuresOfInterest.AverageChangeOverTime, stat => { stat.Value = m_queue.Count; }, StatVerbosity.Debug); StatsManager.RegisterStat(s_processedRequestsStat); StatsManager.RegisterStat(s_queuedRequestsStat); m_InventoryService = Scene.InventoryService; m_LibraryService = Scene.LibraryService; // We'll reuse the same handler for all requests. m_webFetchHandler = new FetchInvDescHandler(m_InventoryService, m_LibraryService, Scene); Scene.EventManager.OnRegisterCaps += RegisterCaps; int nworkers = 2; // was 2 if (ProcessQueuedRequestsAsync && m_workerThreads == null) { m_workerThreads = new Thread[nworkers]; for (uint i = 0; i < nworkers; i++) { m_workerThreads[i] = WorkManager.StartThread(DoInventoryRequests, String.Format("InventoryWorkerThread{0}", i), ThreadPriority.Normal, false, true, null, int.MaxValue); } } } public void PostInitialise() { } public void Close() { } public string Name { get { return "WebFetchInvDescModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion private class PollServiceInventoryEventArgs : PollServiceEventArgs { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<UUID, Hashtable> responses = new Dictionary<UUID, Hashtable>(); private WebFetchInvDescModule m_module; public PollServiceInventoryEventArgs(WebFetchInvDescModule module, string url, UUID pId) : base(null, url, null, null, null, pId, int.MaxValue) { m_module = module; HasEvents = (x, y) => { lock (responses) return responses.ContainsKey(x); }; GetEvents = (x, y) => { lock (responses) { try { return responses[x]; } finally { responses.Remove(x); } } }; Request = (x, y) => { ScenePresence sp = m_module.Scene.GetScenePresence(Id); aPollRequest reqinfo = new aPollRequest(); reqinfo.thepoll = this; reqinfo.reqID = x; reqinfo.request = y; reqinfo.presence = sp; reqinfo.folders = new List<UUID>(); // Decode the request here string request = y["body"].ToString(); request = request.Replace("<string>00000000-0000-0000-0000-000000000000</string>", "<uuid>00000000-0000-0000-0000-000000000000</uuid>"); request = request.Replace("<key>fetch_folders</key><integer>0</integer>", "<key>fetch_folders</key><boolean>0</boolean>"); request = request.Replace("<key>fetch_folders</key><integer>1</integer>", "<key>fetch_folders</key><boolean>1</boolean>"); Hashtable hash = new Hashtable(); try { hash = (Hashtable)LLSD.LLSDDeserialize(Utils.StringToBytes(request)); } catch (LLSD.LLSDParseException e) { m_log.ErrorFormat("[INVENTORY]: Fetch error: {0}{1}" + e.Message, e.StackTrace); m_log.Error("Request: " + request); return; } catch (System.Xml.XmlException) { m_log.ErrorFormat("[INVENTORY]: XML Format error"); } ArrayList foldersrequested = (ArrayList)hash["folders"]; bool highPriority = false; for (int i = 0; i < foldersrequested.Count; i++) { Hashtable inventoryhash = (Hashtable)foldersrequested[i]; string folder = inventoryhash["folder_id"].ToString(); UUID folderID; if (UUID.TryParse(folder, out folderID)) { if (!reqinfo.folders.Contains(folderID)) { //TODO: Port COF handling from Avination reqinfo.folders.Add(folderID); } } } if (highPriority) m_queue.EnqueueHigh(reqinfo); else m_queue.EnqueueLow(reqinfo); }; NoEvents = (x, y) => { /* lock (requests) { Hashtable request = requests.Find(id => id["RequestID"].ToString() == x.ToString()); requests.Remove(request); } */ Hashtable response = new Hashtable(); response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; }; } public void Process(aPollRequest requestinfo) { UUID requestID = requestinfo.reqID; Hashtable response = new Hashtable(); response["int_response_code"] = 200; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; response["str_response_string"] = m_webFetchHandler.FetchInventoryDescendentsRequest( requestinfo.request["body"].ToString(), String.Empty, String.Empty, null, null); lock (responses) { if (responses.ContainsKey(requestID)) m_log.WarnFormat("[FETCH INVENTORY DESCENDENTS2 MODULE]: Caught in the act of loosing responses! Please report this on mantis #7054"); responses[requestID] = response; } WebFetchInvDescModule.ProcessedRequestsCount++; } } private void RegisterCaps(UUID agentID, Caps caps) { RegisterFetchDescendentsCap(agentID, caps, "FetchInventoryDescendents2", m_fetchInventoryDescendents2Url); } private void RegisterFetchDescendentsCap(UUID agentID, Caps caps, string capName, string url) { string capUrl; // disable the cap clause if (url == "") { return; } // handled by the simulator else if (url == "localhost") { capUrl = "/CAPS/" + UUID.Random() + "/"; // Register this as a poll service PollServiceInventoryEventArgs args = new PollServiceInventoryEventArgs(this, capUrl, agentID); args.Type = PollServiceEventArgs.EventType.Inventory; caps.RegisterPollHandler(capName, args); } // external handler else { capUrl = url; IExternalCapsModule handler = Scene.RequestModuleInterface<IExternalCapsModule>(); if (handler != null) handler.RegisterExternalUserCapsHandler(agentID,caps,capName,capUrl); else caps.RegisterHandler(capName, capUrl); } // m_log.DebugFormat( // "[FETCH INVENTORY DESCENDENTS2 MODULE]: Registered capability {0} at {1} in region {2} for {3}", // capName, capUrl, m_scene.RegionInfo.RegionName, agentID); } // private void DeregisterCaps(UUID agentID, Caps caps) // { // string capUrl; // // if (m_capsDict.TryGetValue(agentID, out capUrl)) // { // MainServer.Instance.RemoveHTTPHandler("", capUrl); // m_capsDict.Remove(agentID); // } // } private void DoInventoryRequests() { while (true) { Watchdog.UpdateThread(); WaitProcessQueuedInventoryRequest(); } } public void WaitProcessQueuedInventoryRequest() { aPollRequest poolreq = m_queue.Dequeue(); if (poolreq != null && poolreq.thepoll != null) { try { poolreq.thepoll.Process(poolreq); } catch (Exception e) { m_log.ErrorFormat( "[INVENTORY]: Failed to process queued inventory request {0} for {1} in {2}. Exception {3}", poolreq.reqID, poolreq.presence != null ? poolreq.presence.Name : "unknown", Scene.Name, e); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.Diagnostics { public partial class BooleanSwitch : System.Diagnostics.Switch { public BooleanSwitch(string displayName, string description) : base(default(string), default(string)) { } public BooleanSwitch(string displayName, string description, string defaultSwitchValue) : base(default(string), default(string)) { } public bool Enabled { get { return default(bool); } set { } } protected override void OnValueChanged() { } } public partial class DefaultTraceListener : System.Diagnostics.TraceListener { public DefaultTraceListener() { } public override void Fail(string message) { } public override void Fail(string message, string detailMessage) { } public override void Write(string message) { } public override void WriteLine(string message) { } } public partial class EventTypeFilter : System.Diagnostics.TraceFilter { public EventTypeFilter(System.Diagnostics.SourceLevels level) { } public System.Diagnostics.SourceLevels EventType { get { return default(System.Diagnostics.SourceLevels); } set { } } public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { return default(bool); } } public partial class SourceFilter : System.Diagnostics.TraceFilter { public SourceFilter(string source) { } public string Source { get { return default(string); } set { } } public override bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data) { return default(bool); } } [System.FlagsAttribute] public enum SourceLevels { All = -1, Critical = 1, Error = 3, Information = 15, Off = 0, Verbose = 31, Warning = 7, } public partial class SourceSwitch : System.Diagnostics.Switch { public SourceSwitch(string name) : base(default(string), default(string)) { } public SourceSwitch(string displayName, string defaultSwitchValue) : base(default(string), default(string)) { } public System.Diagnostics.SourceLevels Level { get { return default(System.Diagnostics.SourceLevels); } set { } } protected override void OnValueChanged() { } public bool ShouldTrace(System.Diagnostics.TraceEventType eventType) { return default(bool); } } public abstract partial class Switch { protected Switch(string displayName, string description) { } protected Switch(string displayName, string description, string defaultSwitchValue) { } public string Description { get { return default(string); } } public string DisplayName { get { return default(string); } } protected int SwitchSetting { get { return default(int); } set { } } protected string Value { get { return default(string); } set { } } protected virtual void OnSwitchSettingChanged() { } protected virtual void OnValueChanged() { } } public sealed partial class Trace { internal Trace() { } public static bool AutoFlush { get { return default(bool); } set { } } public static int IndentLevel { get { return default(int); } set { } } public static int IndentSize { get { return default(int); } set { } } public static System.Diagnostics.TraceListenerCollection Listeners { get { return default(System.Diagnostics.TraceListenerCollection); } } public static bool UseGlobalLock { get { return default(bool); } set { } } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Assert(bool condition, string message, string detailMessage) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Close() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Fail(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Fail(string message, string detailMessage) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Flush() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Indent() { } public static void Refresh() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceError(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceError(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceInformation(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceInformation(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceWarning(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void TraceWarning(string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Unindent() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void Write(string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteIf(bool condition, string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLine(string message, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, object value) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, object value, string category) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public static void WriteLineIf(bool condition, string message, string category) { } } public partial class TraceEventCache { public TraceEventCache() { } public System.DateTime DateTime { get { return default(System.DateTime); } } public int ProcessId { get { return default(int); } } public string ThreadId { get { return default(string); } } public long Timestamp { get { return default(long); } } } public enum TraceEventType { Critical = 1, Error = 2, Information = 8, Verbose = 16, Warning = 4, } public abstract partial class TraceFilter { protected TraceFilter() { } public abstract bool ShouldTrace(System.Diagnostics.TraceEventCache cache, string source, System.Diagnostics.TraceEventType eventType, int id, string formatOrMessage, object[] args, object data1, object[] data); } public enum TraceLevel { Error = 1, Info = 3, Off = 0, Verbose = 4, Warning = 2, } public abstract partial class TraceListener : System.IDisposable { protected TraceListener() { } protected TraceListener(string name) { } public System.Diagnostics.TraceFilter Filter { get { return default(System.Diagnostics.TraceFilter); } set { } } public int IndentLevel { get { return default(int); } set { } } public int IndentSize { get { return default(int); } set { } } public virtual bool IsThreadSafe { get { return default(bool); } } public virtual string Name { get { return default(string); } set { } } protected bool NeedIndent { get { return default(bool); } set { } } public System.Diagnostics.TraceOptions TraceOutputOptions { get { return default(System.Diagnostics.TraceOptions); } set { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } public virtual void Fail(string message) { } public virtual void Fail(string message, string detailMessage) { } public virtual void Flush() { } public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, object data) { } public virtual void TraceData(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, params object[] data) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string message) { } public virtual void TraceEvent(System.Diagnostics.TraceEventCache eventCache, string source, System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { } public virtual void Write(object o) { } public virtual void Write(object o, string category) { } public abstract void Write(string message); public virtual void Write(string message, string category) { } protected virtual void WriteIndent() { } public virtual void WriteLine(object o) { } public virtual void WriteLine(object o, string category) { } public abstract void WriteLine(string message); public virtual void WriteLine(string message, string category) { } } public partial class TraceListenerCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList { internal TraceListenerCollection() { } public int Count { get { return default(int); } } public System.Diagnostics.TraceListener this[int i] { get { return default(System.Diagnostics.TraceListener); } set { } } public System.Diagnostics.TraceListener this[string name] { get { return default(System.Diagnostics.TraceListener); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } object System.Collections.ICollection.SyncRoot { get { return default(object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } object System.Collections.IList.this[int index] { get { return default(object); } set { } } public int Add(System.Diagnostics.TraceListener listener) { return default(int); } public void AddRange(System.Diagnostics.TraceListener[] value) { } public void AddRange(System.Diagnostics.TraceListenerCollection value) { } public void Clear() { } public bool Contains(System.Diagnostics.TraceListener listener) { return default(bool); } public void CopyTo(System.Diagnostics.TraceListener[] listeners, int index) { } public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); } public int IndexOf(System.Diagnostics.TraceListener listener) { return default(int); } public void Insert(int index, System.Diagnostics.TraceListener listener) { } public void Remove(System.Diagnostics.TraceListener listener) { } public void Remove(string name) { } public void RemoveAt(int index) { } void System.Collections.ICollection.CopyTo(System.Array array, int index) { } int System.Collections.IList.Add(object value) { return default(int); } bool System.Collections.IList.Contains(object value) { return default(bool); } int System.Collections.IList.IndexOf(object value) { return default(int); } void System.Collections.IList.Insert(int index, object value) { } void System.Collections.IList.Remove(object value) { } } [System.FlagsAttribute] public enum TraceOptions { DateTime = 2, None = 0, ProcessId = 8, ThreadId = 16, Timestamp = 4, } public partial class TraceSource { public TraceSource(string name) { } public TraceSource(string name, System.Diagnostics.SourceLevels defaultLevel) { } public System.Diagnostics.TraceListenerCollection Listeners { get { return default(System.Diagnostics.TraceListenerCollection); } } public string Name { get { return default(string); } } public System.Diagnostics.SourceSwitch Switch { get { return default(System.Diagnostics.SourceSwitch); } set { } } public void Close() { } public void Flush() { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceData(System.Diagnostics.TraceEventType eventType, int id, object data) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceData(System.Diagnostics.TraceEventType eventType, int id, params object[] data) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceEvent(System.Diagnostics.TraceEventType eventType, int id, string format, params object[] args) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceInformation(string message) { } [System.Diagnostics.ConditionalAttribute("TRACE")] public void TraceInformation(string format, params object[] args) { } } public partial class TraceSwitch : System.Diagnostics.Switch { public TraceSwitch(string displayName, string description) : base(default(string), default(string)) { } public TraceSwitch(string displayName, string description, string defaultSwitchValue) : base(default(string), default(string)) { } public System.Diagnostics.TraceLevel Level { get { return default(System.Diagnostics.TraceLevel); } set { } } public bool TraceError { get { return default(bool); } } public bool TraceInfo { get { return default(bool); } } public bool TraceVerbose { get { return default(bool); } } public bool TraceWarning { get { return default(bool); } } protected override void OnSwitchSettingChanged() { } protected override void OnValueChanged() { } } }
#if !UNITY_WINRT || 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.Linq; using System.Globalization; using System.ComponentModel; using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Serialization; namespace Newtonsoft.Json.Schema { /// <summary> /// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>. /// </summary> public class JsonSchemaGenerator { /// <summary> /// Gets or sets how undefined schemas are handled by the serializer. /// </summary> public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; } private IContractResolver _contractResolver; /// <summary> /// Gets or sets the contract resolver. /// </summary> /// <value>The contract resolver.</value> public IContractResolver ContractResolver { get { if (_contractResolver == null) return DefaultContractResolver.Instance; return _contractResolver; } set { _contractResolver = value; } } private class TypeSchema { public Type Type { get; private set; } public JsonSchema Schema { get; private set;} public TypeSchema(Type type, JsonSchema schema) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(schema, "schema"); Type = type; Schema = schema; } } private JsonSchemaResolver _resolver; private IList<TypeSchema> _stack = new List<TypeSchema>(); private JsonSchema _currentSchema; private JsonSchema CurrentSchema { get { return _currentSchema; } } private void Push(TypeSchema typeSchema) { _currentSchema = typeSchema.Schema; _stack.Add(typeSchema); _resolver.LoadedSchemas.Add(typeSchema.Schema); } private TypeSchema Pop() { TypeSchema popped = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); TypeSchema newValue = _stack.LastOrDefault(); if (newValue != null) { _currentSchema = newValue.Schema; } else { _currentSchema = null; } return popped; } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type) { return Generate(type, new JsonSchemaResolver(), false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver) { return Generate(type, resolver, false); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, bool rootSchemaNullable) { return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); } /// <summary> /// Generate a <see cref="JsonSchema"/> from the specified type. /// </summary> /// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param> /// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param> /// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param> /// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns> public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(resolver, "resolver"); _resolver = resolver; return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); } private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title)) return containerAttribute.Title; return null; } private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description)) return containerAttribute.Description; DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type); if (descriptionAttribute != null) return descriptionAttribute.Description; return null; } private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetJsonContainerAttribute(type); if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id)) return containerAttribute.Id; if (explicitOnly) return null; switch (UndefinedSchemaIdHandling) { case UndefinedSchemaIdHandling.UseTypeName: return type.FullName; case UndefinedSchemaIdHandling.UseAssemblyQualifiedName: return type.AssemblyQualifiedName; default: return null; } } private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) { ValidationUtils.ArgumentNotNull(type, "type"); string resolvedId = GetTypeId(type, false); string explicitId = GetTypeId(type, true); if (!string.IsNullOrEmpty(resolvedId)) { JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId); if (resolvedSchema != null) { // resolved schema is not null but referencing member allows nulls // change resolved schema to allow nulls. hacky but what are ya gonna do? if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null)) resolvedSchema.Type |= JsonSchemaType.Null; if (required && resolvedSchema.Required != true) resolvedSchema.Required = true; return resolvedSchema; } } // test for unresolved circular reference if (_stack.Any(tc => tc.Type == type)) { throw new Exception("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type)); } JsonContract contract = ContractResolver.ResolveContract(type); JsonConverter converter; if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null) { JsonSchema converterSchema = converter.GetSchema(); if (converterSchema != null) return converterSchema; } Push(new TypeSchema(type, new JsonSchema())); if (explicitId != null) CurrentSchema.Id = explicitId; if (required) CurrentSchema.Required = true; CurrentSchema.Title = GetTitle(type); CurrentSchema.Description = GetDescription(type); if (converter != null) { // todo: Add GetSchema to JsonConverter and use here? CurrentSchema.Type = JsonSchemaType.Any; } else if (contract is JsonDictionaryContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); Type keyType; Type valueType; ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType); if (keyType != null) { // can be converted to a string if (typeof (IConvertible).IsAssignableFrom(keyType)) { CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false); } } } else if (contract is JsonArrayContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired); CurrentSchema.Id = GetTypeId(type, false); JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetJsonContainerAttribute(type) as JsonArrayAttribute; bool allowNullItem = (arrayAttribute != null) ? arrayAttribute.AllowNullItems : true; Type collectionItemType = ReflectionUtils.GetCollectionItemType(type); if (collectionItemType != null) { CurrentSchema.Items = new List<JsonSchema>(); CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false)); } } else if (contract is JsonPrimitiveContract) { CurrentSchema.Type = GetJsonSchemaType(type, valueRequired); if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum && !type.IsDefined(typeof(FlagsAttribute), true)) { CurrentSchema.Enum = new List<JToken>(); CurrentSchema.Options = new Dictionary<JToken, string>(); EnumValues<long> enumValues = EnumUtils.GetNamesAndValues<long>(type); foreach (EnumValue<long> enumValue in enumValues) { JToken value = JToken.FromObject(enumValue.Value); CurrentSchema.Enum.Add(value); CurrentSchema.Options.Add(value, enumValue.Name); } } } else if (contract is JsonObjectContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateObjectSchema(type, (JsonObjectContract)contract); } else if (contract is JsonISerializableContract) { CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired); CurrentSchema.Id = GetTypeId(type, false); GenerateISerializableContract(type, (JsonISerializableContract) contract); } else if (contract is JsonStringContract) { JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType)) ? JsonSchemaType.String : AddNullType(JsonSchemaType.String, valueRequired); CurrentSchema.Type = schemaType; } else if (contract is JsonLinqContract) { CurrentSchema.Type = JsonSchemaType.Any; } else { throw new Exception("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract)); } return Pop().Schema; } private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired) { if (valueRequired != Required.Always) return type | JsonSchemaType.Null; return type; } private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag) { return ((value & flag) == flag); } private void GenerateObjectSchema(Type type, JsonObjectContract contract) { CurrentSchema.Properties = new Dictionary<string, JsonSchema>(); foreach (JsonProperty property in contract.Properties) { if (!property.Ignored) { bool optional = property.NullValueHandling == NullValueHandling.Ignore || HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) || property.ShouldSerialize != null || property.GetIsSpecified != null; JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional); if (property.DefaultValue != null) propertySchema.Default = JToken.FromObject(property.DefaultValue); CurrentSchema.Properties.Add(property.PropertyName, propertySchema); } } if (type.IsSealed) CurrentSchema.AllowAdditionalProperties = false; } private void GenerateISerializableContract(Type type, JsonISerializableContract contract) { CurrentSchema.AllowAdditionalProperties = true; } internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag) { // default value is Any if (value == null) return true; return ((value & flag) == flag); } private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired) { JsonSchemaType schemaType = JsonSchemaType.None; if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type)) { schemaType = JsonSchemaType.Null; if (ReflectionUtils.IsNullableType(type)) type = Nullable.GetUnderlyingType(type); } TypeCode typeCode = Type.GetTypeCode(type); switch (typeCode) { case TypeCode.Empty: case TypeCode.Object: return schemaType | JsonSchemaType.String; case TypeCode.DBNull: return schemaType | JsonSchemaType.Null; case TypeCode.Boolean: return schemaType | JsonSchemaType.Boolean; case TypeCode.Char: return schemaType | JsonSchemaType.String; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: return schemaType | JsonSchemaType.Integer; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return schemaType | JsonSchemaType.Float; // convert to string? case TypeCode.DateTime: return schemaType | JsonSchemaType.String; case TypeCode.String: return schemaType | JsonSchemaType.String; default: throw new Exception("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type)); } } } } #endif
using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Internal; namespace Orleans.Runtime.Scheduler { [DebuggerDisplay("WorkItemGroup Name={Name} State={state}")] internal class WorkItemGroup : IWorkItem { private enum WorkGroupStatus { Waiting = 0, Runnable = 1, Running = 2 } private readonly ILogger log; private readonly OrleansTaskScheduler masterScheduler; private WorkGroupStatus state; private readonly object lockable; private readonly Queue<Task> workItems; private long totalItemsEnQueued; // equals total items queued, + 1 private long totalItemsProcessed; private TimeSpan totalQueuingDelay; private long lastLongQueueWarningTimestamp; private Task currentTask; private DateTime currentTaskStarted; private long shutdownSinceTimestamp; private long lastShutdownWarningTimestamp; private readonly QueueTrackingStatistic queueTracking; private readonly long quantumExpirations; private readonly int workItemGroupStatisticsNumber; private readonly CancellationToken cancellationToken; private readonly SchedulerStatisticsGroup schedulerStatistics; internal ActivationTaskScheduler TaskScheduler { get; private set; } public DateTime TimeQueued { get; set; } public TimeSpan TimeSinceQueued => Utils.Since(TimeQueued); public bool IsSystemPriority => this.GrainContext is SystemTarget systemTarget && !systemTarget.IsLowPriority; internal bool IsSystemGroup => this.GrainContext is ISystemTargetBase; public string Name => GrainContext?.ToString() ?? "Unknown"; internal int ExternalWorkItemCount { get { lock (lockable) { return WorkItemCount; } } } private Task CurrentTask { get => currentTask; set { currentTask = value; currentTaskStarted = DateTime.UtcNow; } } private int WorkItemCount => workItems.Count; internal float AverageQueueLength => 0; internal float NumEnqueuedRequests => 0; internal float ArrivalRate => 0; private bool HasWork => this.WorkItemCount != 0; private bool IsShutdown => this.shutdownSinceTimestamp > 0; // This is the maximum number of work items to be processed in an activation turn. // If this is set to zero or a negative number, then the full work queue is drained (MaxTimePerTurn allowing). private const int MaxWorkItemsPerTurn = 0; // Unlimited // This is the maximum number of waiting threads (blocked in WaitForResponse) allowed // per ActivationWorker. An attempt to wait when there are already too many threads waiting // will result in a TooManyWaitersException being thrown. //private static readonly int MaxWaitingThreads = 500; internal WorkItemGroup( OrleansTaskScheduler sched, IGrainContext grainContext, ILogger<WorkItemGroup> logger, ILogger<ActivationTaskScheduler> activationTaskSchedulerLogger, CancellationToken ct, SchedulerStatisticsGroup schedulerStatistics, IOptions<StatisticsOptions> statisticsOptions) { masterScheduler = sched; GrainContext = grainContext; cancellationToken = ct; this.schedulerStatistics = schedulerStatistics; state = WorkGroupStatus.Waiting; workItems = new Queue<Task>(); lockable = new object(); totalItemsEnQueued = 0; totalItemsProcessed = 0; totalQueuingDelay = TimeSpan.Zero; quantumExpirations = 0; TaskScheduler = new ActivationTaskScheduler(this, activationTaskSchedulerLogger); log = logger; if (schedulerStatistics.CollectShedulerQueuesStats) { queueTracking = new QueueTrackingStatistic("Scheduler." + this.Name, statisticsOptions); queueTracking.OnStartExecution(); } if (schedulerStatistics.CollectPerWorkItemStats) { workItemGroupStatisticsNumber = schedulerStatistics.RegisterWorkItemGroup(this.Name, this.GrainContext, () => { var sb = new StringBuilder(); lock (lockable) { sb.Append("QueueLength = " + WorkItemCount); sb.Append($", State = {state}"); if (state == WorkGroupStatus.Runnable) sb.Append($"; oldest item is {(workItems.Count >= 0 ? workItems.Peek().ToString() : "null")} old"); } return sb.ToString(); }); } } /// <summary> /// Adds a task to this activation. /// If we're adding it to the run list and we used to be waiting, now we're runnable. /// </summary> /// <param name="task">The work item to add.</param> public void EnqueueTask(Task task) { #if DEBUG if (log.IsEnabled(LogLevel.Trace)) { this.log.LogTrace( "EnqueueWorkItem {Task} into {GrainContext} when TaskScheduler.Current={TaskScheduler}", task, this.GrainContext, System.Threading.Tasks.TaskScheduler.Current); } #endif if (this.IsShutdown) { if (this.cancellationToken.IsCancellationRequested) { // If the system is shutdown, do not schedule the task. return; } // Log diagnostics and continue to schedule the task. LogEnqueueOnStoppedScheduler(task); } lock (lockable) { long thisSequenceNumber = totalItemsEnQueued++; int count = WorkItemCount; workItems.Enqueue(task); int maxPendingItemsLimit = masterScheduler.MaxPendingItemsSoftLimit; if (maxPendingItemsLimit > 0 && count > maxPendingItemsLimit) { var now = ValueStopwatch.GetTimestamp(); if (ValueStopwatch.FromTimestamp(this.lastLongQueueWarningTimestamp, now).Elapsed > TimeSpan.FromSeconds(10)) { log.LogWarning( (int)ErrorCode.SchedulerTooManyPendingItems, "{PendingWorkItemCount} pending work items for group {WorkGroupName}, exceeding the warning threshold of {WarningThreshold}", count, this.Name, maxPendingItemsLimit); } lastLongQueueWarningTimestamp = now; } if (state != WorkGroupStatus.Waiting) return; state = WorkGroupStatus.Runnable; #if DEBUG if (log.IsEnabled(LogLevel.Trace)) { log.LogTrace( "Add to RunQueue {Task}, #{SequenceNumber}, onto {GrainContext}", task, thisSequenceNumber, GrainContext); } #endif ScheduleExecution(this); } } /// <summary> /// For debugger purposes only. /// </summary> internal IEnumerable<Task> GetScheduledTasks() { foreach (var task in this.workItems) { yield return task; } } [MethodImpl(MethodImplOptions.NoInlining)] private void LogEnqueueOnStoppedScheduler(Task task) { var now = ValueStopwatch.GetTimestamp(); LogLevel logLevel; if (this.lastShutdownWarningTimestamp == 0) { logLevel = LogLevel.Debug; } else if (ValueStopwatch.FromTimestamp(this.lastShutdownWarningTimestamp, now).Elapsed > this.masterScheduler.StoppedWorkItemGroupWarningInterval) { // Upgrade the warning to an error after 1 minute, include a stack trace, and continue to log up to once per minute. logLevel = LogLevel.Error; } else return; this.log.Log( logLevel, (int)ErrorCode.SchedulerEnqueueWorkWhenShutdown, "Enqueuing task {Task} to a work item group which should have terminated. " + "Likely reasons are that the task is not being 'awaited' properly or a TaskScheduler was captured and is being used to schedule tasks " + "after a grain has been deactivated.\nWorkItemGroup: {Status}\nTask.AsyncState: {TaskState}\n{Stack}", OrleansTaskExtentions.ToString(task), this.DumpStatus(), DumpAsyncState(task.AsyncState), Utils.GetStackTrace()); this.lastShutdownWarningTimestamp = now; } private static object DumpAsyncState(object o) { if (o is Delegate action) return action.Target is null ? action.Method.DeclaringType + "." + action.Method.Name : action.Method.DeclaringType.Name + "." + action.Method.Name + ": " + DumpAsyncState(action.Target); if (o?.GetType() is { Name: "ContinuationWrapper" } wrapper && (wrapper.GetField("_continuation", BindingFlags.Instance | BindingFlags.NonPublic) ?? wrapper.GetField("m_continuation", BindingFlags.Instance | BindingFlags.NonPublic) )?.GetValue(o) is Action continuation) return DumpAsyncState(continuation); return o; } /// <summary> /// Shuts down this work item group so that it will not process any additional work items, even if they /// have already been queued. /// </summary> internal void Stop() { lock (lockable) { if (this.HasWork) { log.LogWarning( (int)ErrorCode.SchedulerWorkGroupStopping, "WorkItemGroup is being shutdown while still active. workItemCount = {WorkItemCount}. The likely reason is that the task is not being 'awaited' properly. Status: {Status}", WorkItemCount, DumpStatus()); } if (this.IsShutdown) { log.LogWarning( (int)ErrorCode.SchedulerWorkGroupShuttingDown, "WorkItemGroup is already shutting down {WorkItemGroup}", this.ToString()); return; } this.shutdownSinceTimestamp = ValueStopwatch.GetTimestamp(); if (this.schedulerStatistics.CollectPerWorkItemStats) this.schedulerStatistics.UnRegisterWorkItemGroup(workItemGroupStatisticsNumber); if (this.schedulerStatistics.CollectShedulerQueuesStats) queueTracking.OnStopExecution(); } } public WorkItemType ItemType { get { return WorkItemType.WorkItemGroup; } } public IGrainContext GrainContext { get; } // Execute one or more turns for this activation. // This method is always called in a single-threaded environment -- that is, no more than one // thread will be in this method at once -- but other asynch threads may still be queueing tasks, etc. public void Execute() { try { RuntimeContext.SetExecutionContext(this.GrainContext); // Process multiple items -- drain the applicationMessageQueue (up to max items) for this physical activation int count = 0; var stopwatch = ValueStopwatch.StartNew(); do { lock (lockable) { state = WorkGroupStatus.Running; // Check the cancellation token (means that the silo is stopping) if (cancellationToken.IsCancellationRequested) { this.log.LogWarning( (int)ErrorCode.SchedulerSkipWorkCancelled, "Thread {Thread} is exiting work loop due to cancellation token. WorkItemGroup: {WorkItemGroup}, Have {WorkItemCount} work items in the queue", Thread.CurrentThread.ManagedThreadId.ToString(), this.ToString(), this.WorkItemCount); return; } } // Get the first Work Item on the list Task task; lock (lockable) { if (workItems.Count > 0) CurrentTask = task = workItems.Dequeue(); else // If the list is empty, then we're done break; } #if DEBUG if (log.IsEnabled(LogLevel.Trace)) { log.LogTrace( "About to execute task {Task} in GrainContext={GrainContext}", OrleansTaskExtentions.ToString(task), this.GrainContext); } #endif var taskStart = stopwatch.Elapsed; try { TaskScheduler.RunTask(task); } catch (Exception ex) { this.log.LogError( (int)ErrorCode.SchedulerExceptionFromExecute, ex, "Worker thread caught an exception thrown from Execute by task {Task}. Exception: {Exception}", OrleansTaskExtentions.ToString(task), ex); throw; } finally { totalItemsProcessed++; var taskLength = stopwatch.Elapsed - taskStart; if (taskLength > OrleansTaskScheduler.TurnWarningLengthThreshold) { this.schedulerStatistics.NumLongRunningTurns.Increment(); this.log.LogWarning( (int)ErrorCode.SchedulerTurnTooLong3, "Task {Task} in WorkGroup {GrainContext} took elapsed time {Duration} for execution, which is longer than {TurnWarningLengthThreshold}. Running on thread {Thread}", OrleansTaskExtentions.ToString(task), this.GrainContext.ToString(), taskLength.ToString("g"), OrleansTaskScheduler.TurnWarningLengthThreshold, Thread.CurrentThread.ManagedThreadId.ToString()); } CurrentTask = null; } count++; } while (((MaxWorkItemsPerTurn <= 0) || (count <= MaxWorkItemsPerTurn)) && ((masterScheduler.SchedulingOptions.ActivationSchedulingQuantum <= TimeSpan.Zero) || (stopwatch.Elapsed < masterScheduler.SchedulingOptions.ActivationSchedulingQuantum))); } catch (Exception ex) { this.log.LogError( (int)ErrorCode.Runtime_Error_100032, ex, "Worker thread {Thread} caught an exception thrown from IWorkItem.Execute: {Exception}", Thread.CurrentThread.ManagedThreadId, ex); } finally { // Now we're not Running anymore. // If we left work items on our run list, we're Runnable, and need to go back on the silo run queue; // If our run list is empty, then we're waiting. lock (lockable) { if (WorkItemCount > 0) { state = WorkGroupStatus.Runnable; ScheduleExecution(this); } else { state = WorkGroupStatus.Waiting; } } RuntimeContext.ResetExecutionContext(); } } public override string ToString() => $"{(IsSystemGroup ? "System*" : "")}WorkItemGroup:Name={Name},WorkGroupStatus={state}"; public string DumpStatus() { lock (lockable) { var sb = new StringBuilder(); sb.Append(this); sb.AppendFormat(". Currently QueuedWorkItems={0}; Total Enqueued={1}; Total processed={2}; Quantum expirations={3}; ", WorkItemCount, totalItemsEnQueued, totalItemsProcessed, quantumExpirations); if (CurrentTask is Task task) { sb.AppendFormat(" Executing Task Id={0} Status={1} for {2}.", task.Id, task.Status, Utils.Since(currentTaskStarted)); } if (AverageQueueLength > 0) { sb.AppendFormat("average queue length at enqueue: {0}; ", AverageQueueLength); if (!totalQueuingDelay.Equals(TimeSpan.Zero) && totalItemsProcessed > 0) { sb.AppendFormat("average queue delay: {0}ms; ", totalQueuingDelay.Divide(totalItemsProcessed).TotalMilliseconds); } } sb.AppendFormat("TaskRunner={0}; ", TaskScheduler); if (GrainContext != null) { var detailedStatus = this.GrainContext switch { ActivationData activationData => activationData.ToDetailedString(includeExtraDetails: true), SystemTarget systemTarget => systemTarget.ToDetailedString(), object obj => obj.ToString(), _ => "None" }; sb.AppendFormat("Detailed context=<{0}>", detailedStatus); } return sb.ToString(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ScheduleExecution(WorkItemGroup workItem) { ThreadPool.UnsafeQueueUserWorkItem(workItem, preferLocal: true); } } }
//============================================================================= // System : EWSoftware Design Time Attributes and Editors // File : PresenationStyleTypeConverter.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 09/17/2007 // Note : Copyright 2007, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a type converter that allows you to select a presentation // style folder from those currently installed in the .\Presentation folder // found in the main installation folder of Sandcastle. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.0.0.0 08/08/2006 EFW Created the code // 1.5.0.0 06/19/2007 EFW Updated for use with the June CTP //============================================================================= using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Text.RegularExpressions; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.BuildEngine; namespace SandcastleBuilder.Utils.Design { /// <summary> /// This type converter allows you to select a presentation style folder /// from those currently installed in the <b>.\Presentation</b> folder /// found in the main installation folder of Sandcastle. /// </summary> internal sealed class PresentationStyleTypeConverter : StringConverter { //===================================================================== // Private data members private static List<string> styles = new List<string>(); private static StandardValuesCollection standardValues = PresentationStyleTypeConverter.InitializeStandardValues(); //===================================================================== // Properties /// <summary> /// This returns the default style /// </summary> /// <value>Returns <b>vs2005</b> if present. If not, it returns the /// first best match or, failing that, the first style in the list.</value> public static string DefaultStyle { get { string defaultStyle = "vs2005"; if(!IsPresent(defaultStyle)) defaultStyle = FirstMatching(defaultStyle); return defaultStyle; } } //===================================================================== // Methods /// <summary> /// This is used to get the standard values by searching for the /// .NET Framework versions installed on the current system. /// </summary> private static StandardValuesCollection InitializeStandardValues() { string folder; try { // Try the DXROOT environment variable first folder = Environment.GetEnvironmentVariable("DXROOT"); if(String.IsNullOrEmpty(folder) || !folder.Contains(@"\Sandcastle")) folder = String.Empty; // Try to find Sandcastle based on the path if not there if(folder.Length == 0) { Match m = Regex.Match( Environment.GetEnvironmentVariable("PATH"), @"[A-Z]:\\.[^;]+\\Sandcastle(?=\\Prod)", RegexOptions.IgnoreCase); // If not found in the path, search all fixed drives if(m.Success) folder = m.Value; else { folder = BuildProcess.FindOnFixedDrives(@"\Sandcastle"); // If not found there, try the VS 2005 SDK folders if(folder.Length == 0) { folder = BuildProcess.FindSdkExecutable( "MRefBuilder.exe"); if(folder.Length != 0) folder = folder.Substring(0, folder.LastIndexOf('\\')); } } } if(folder.Length != 0) { folder += @"\Presentation"; string[] dirs = Directory.GetDirectories(folder); // The Shared folder is omitted as it contains files // common to all presentation styles. foreach(string s in dirs) if(!s.EndsWith("Shared", StringComparison.Ordinal)) styles.Add(s.Substring(s.LastIndexOf('\\') + 1)); } } catch(Exception) { // Eat the exception. If we can't find Sandcastle here, the // build will fail too so the user will be notified then. } // Add the three basic styles as placeholders if nothing was found. // The build will fail but the project will still load. if(styles.Count == 0) { styles.Add("hana"); styles.Add("Prototype"); styles.Add("vs2005"); } styles.Sort(); return new StandardValuesCollection(styles); } /// <summary> /// This is overridden to return the values for the type converter's /// dropdown list. /// </summary> /// <param name="context">The format context object</param> /// <returns>Returns the standard values for the type</returns> public override StandardValuesCollection GetStandardValues( ITypeDescriptorContext context) { return standardValues; } /// <summary> /// This is overridden to indicate that the values are exclusive /// and values outside the list cannot be entered. /// </summary> /// <param name="context">The format context object</param> /// <returns>Always returns true</returns> public override bool GetStandardValuesExclusive( ITypeDescriptorContext context) { return true; } /// <summary> /// This is overridden to indicate that standard values are supported /// and can be chosen from a list. /// </summary> /// <param name="context">The format context object</param> /// <returns>Always returns true</returns> public override bool GetStandardValuesSupported( ITypeDescriptorContext context) { return true; } /// <summary> /// This is used to find out if the specified style is present on the /// system. /// </summary> /// <param name="style">The style for which to look</param> /// <returns>True if present, false if not found</returns> public static bool IsPresent(string style) { return styles.Contains(style); } /// <summary> /// This is used to get the first style that matches case-insensitively /// or, failing that, starts with or contains the given value /// case-insensitively. /// </summary> /// <param name="style">The style for which to look</param> /// <returns>The best match or the first style if not found.</returns> public static string FirstMatching(string style) { string compareStyle; if(!String.IsNullOrEmpty(style)) { // Try for a case-insensitive match first foreach(string s in styles) if(String.Compare(s, style, StringComparison.OrdinalIgnoreCase) == 0) return s; // Try for the closest match style = style.ToLower(CultureInfo.InvariantCulture); foreach(string s in styles) { compareStyle = s.ToLower(CultureInfo.InvariantCulture); if(compareStyle.StartsWith(style, StringComparison.Ordinal) || compareStyle.Contains(style)) return s; } } // Not found, return the first style return styles[0]; } } }
#region Apache Notice /***************************************************************************** * $Header: $ * $Revision: 383115 $ * $Date: 2006-03-04 07:21:51 -0700 (Sat, 04 Mar 2006) $ * * iBATIS.NET Data Mapper * Copyright (C) 2004 - Gilles Bayon * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ********************************************************************************/ #endregion #region Imports using System; using System.Data; using IBatisNet.Common; using IBatisNet.DataAccess; using IBatisNet.DataAccess.Exceptions; using IBatisNet.DataAccess.Interfaces; using NHibernate; using NHibernate.Cfg; using log4net; #endregion namespace IBatisNet.DataAccess.Extensions.DaoSessionHandlers { /// <summary> /// Summary description for NHibernateDaoSession. /// </summary> public class NHibernateDaoSession : DaoSession { #region Fields private ISessionFactory _factory = null; private ISession _session = null; private ITransaction _transaction = null; private bool _consistent = false; #endregion #region Properties /// <summary> /// Changes the vote for transaction to commit (true) or to abort (false). /// </summary> private bool Consistent { set { _consistent = value; } } /// <summary> /// /// </summary> public ISession Session { get { return _session; } } /// <summary> /// /// </summary> public ISessionFactory Factory { get { return _factory; } } /// <summary> /// /// </summary> public override DataSource DataSource { get { throw new DataAccessException("DataSource is not supported with Hibernate."); } } /// <summary> /// /// </summary> public override IDbConnection Connection { get { return _session.Connection; } } /// <summary> /// /// </summary> public override IDbTransaction Transaction { get { return (_session.Transaction as IDbTransaction); } } #endregion #region Constructor (s) / Destructor /// <summary> /// /// </summary> /// <param name="daoManager"></param> /// <param name="factory"></param> public NHibernateDaoSession(DaoManager daoManager, ISessionFactory factory):base(daoManager) { _factory = factory; } #endregion #region Methods /// <summary> /// Complete (commit) a transaction /// </summary> /// <remarks> /// Use in 'using' syntax. /// </remarks> public override void Complete() { this.Consistent = true; } /// <summary> /// Opens a database connection. /// </summary> public override void OpenConnection() { _session = _factory.OpenSession(); } /// <summary> /// Closes the connection /// </summary> public override void CloseConnection() { _session.Flush();// or Close ? } /// <summary> /// Begins a transaction. /// </summary> public override void BeginTransaction() { try { _session = _factory.OpenSession(); _transaction = _session.BeginTransaction(); } catch (HibernateException e) { throw new DataAccessException("Error starting Hibernate transaction. Cause: " + e.Message, e); } } /// <summary> /// Begins a database transaction /// </summary> /// <param name="openConnection">Open a connection.</param> public override void BeginTransaction(bool openConnection) { if (openConnection) { this.BeginTransaction(); } else { if (_session == null) { throw new DataAccessException("NHibernateDaoSession could not invoke BeginTransaction(). A Connection must be started. Call OpenConnection() first."); } try { _transaction = _session.BeginTransaction(); } catch (HibernateException e) { throw new DataAccessException("Error starting Hibernate transaction. Cause: " + e.Message, e); } } } /// <summary> /// Begins a transaction at the data source with the specified IsolationLevel value. /// </summary> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> public override void BeginTransaction(IsolationLevel isolationLevel) { throw new DataAccessException("IsolationLevel is not supported with Hibernate transaction."); } /// <summary> /// Begins a transaction on the current connection /// with the specified IsolationLevel value. /// </summary> /// <param name="isolationLevel">The transaction isolation level for this connection.</param> /// <param name="openConnection">Open a connection.</param> public override void BeginTransaction(bool openConnection, IsolationLevel isolationLevel) { throw new DataAccessException("IsolationLevel is not supported with Hibernate transaction."); } /// <summary> /// Commits the database transaction. /// </summary> /// <remarks> /// Will close the session. /// </remarks> public override void CommitTransaction() { try { _transaction.Commit(); _session.Close(); } catch (HibernateException e) { throw new DataAccessException("Error committing Hibernate transaction. Cause: " + e.Message, e); } } /// <summary> /// Commits the database transaction. /// </summary> /// <param name="closeConnection">Close the session</param> public override void CommitTransaction(bool closeConnection) { try { _transaction.Commit(); if(closeConnection) { _session.Close(); } } catch (HibernateException e) { throw new DataAccessException("Error committing Hibernate transaction. Cause: " + e.Message, e); } } /// <summary> /// Rolls back a transaction from a pending state. /// </summary> /// <remarks> /// Will close the session. /// </remarks> public override void RollBackTransaction() { try { _transaction.Rollback(); _session.Close(); } catch (HibernateException e) { throw new DataAccessException("Error ending Hibernate transaction. Cause: " + e.Message, e); } } /// <summary> /// Rolls back a transaction from a pending state. /// </summary> /// <param name="closeConnection">Close the connection</param> public override void RollBackTransaction(bool closeConnection) { try { _transaction.Rollback(); if(closeConnection) { _session.Close(); } } catch (HibernateException e) { throw new DataAccessException("Error ending Hibernate transaction. Cause: " + e.Message, e); } } /// <summary> /// /// </summary> /// <param name="commandType"></param> /// <returns></returns> public override IDbCommand CreateCommand(CommandType commandType) { throw new DataAccessException("CreateCommand is not supported with Hibernate."); } /// <summary> /// /// </summary> /// <returns></returns> public override IDataParameter CreateDataParameter() { throw new DataAccessException("CreateDataParameter is not supported with Hibernate."); } /// <summary> /// /// </summary> /// <returns></returns> public override IDbDataAdapter CreateDataAdapter() { throw new DataAccessException("CreateDataAdapter is not supported with Hibernate."); } /// <summary> /// /// </summary> /// <param name="command"></param> /// <returns></returns> public override IDbDataAdapter CreateDataAdapter(IDbCommand command) { throw new DataAccessException("CreateDataAdapter is not supported with Hibernate."); } #endregion #region IDisposable Members /// <summary> /// Releasing, or resetting resources. /// </summary> public override void Dispose() { if (_consistent) { this.CommitTransaction(); } else { this.RollBackTransaction(); } _session.Dispose(); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="Debug.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* */ #define DEBUG namespace System.Diagnostics { using System; using System.Text; using System.Reflection; using System.Collections; using System.Security.Permissions; using System.Globalization; /// <devdoc> /// <para>Provides a set of properties and /// methods /// for debugging code.</para> /// </devdoc> public static class Debug { #if !SILVERLIGHT /// <devdoc> /// <para>Gets /// the collection of listeners that is monitoring the debug /// output.</para> /// </devdoc> public static TraceListenerCollection Listeners { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] [HostProtection(SharedState=true)] get { return TraceInternal.Listeners; } } /// <devdoc> /// <para>Gets or sets a value indicating whether <see cref='System.Diagnostics.Debug.Flush'/> should be called on the /// <see cref='System.Diagnostics.Debug.Listeners'/> /// after every write.</para> /// </devdoc> public static bool AutoFlush { [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] get { return TraceInternal.AutoFlush; } [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] set { TraceInternal.AutoFlush = value; } } /// <devdoc> /// <para>Gets or sets /// the indent level.</para> /// </devdoc> public static int IndentLevel { get { return TraceInternal.IndentLevel; } set { TraceInternal.IndentLevel = value; } } /// <devdoc> /// <para>Gets or sets the number of spaces in an indent.</para> /// </devdoc> public static int IndentSize { get { return TraceInternal.IndentSize; } set { TraceInternal.IndentSize = value; } } /// <devdoc> /// <para>Clears the output buffer, and causes buffered data to /// be written to the <see cref='System.Diagnostics.Debug.Listeners'/>.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Flush() { TraceInternal.Flush(); } /// <devdoc> /// <para>Clears the output buffer, and then closes the <see cref='System.Diagnostics.Debug.Listeners'/> so that they no longer receive /// debugging output.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.UnmanagedCode)] public static void Close() { TraceInternal.Close(); } /// <devdoc> /// <para>Checks for a condition, and outputs the callstack if the condition is <see langword='false'/>.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition) { TraceInternal.Assert(condition); } /// <devdoc> /// <para>Checks for a condition, and displays a message if the condition is /// <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message) { TraceInternal.Assert(condition, message); } /// <devdoc> /// <para>Checks for a condition, and displays both the specified messages if the condition /// is <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessage) { TraceInternal.Assert(condition, message, detailMessage); } /// <devdoc> /// <para>Checks for a condition, and displays both the specified messages if the condition /// is <see langword='false'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessageFormat, params Object[] args) { TraceInternal.Assert(condition, message, String.Format(CultureInfo.InvariantCulture, detailMessageFormat, args)); } /// <devdoc> /// <para>Emits or displays a message for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message) { TraceInternal.Fail(message); } /// <devdoc> /// <para>Emits or displays both messages for an assertion that always fails.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Fail(string message, string detailMessage) { TraceInternal.Fail(message, detailMessage); } [System.Diagnostics.Conditional("DEBUG")] public static void Print(string message) { TraceInternal.WriteLine(message); } [System.Diagnostics.Conditional("DEBUG")] public static void Print(string format, params object[] args) { TraceInternal.WriteLine(String.Format(CultureInfo.InvariantCulture, format, args)); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message) { TraceInternal.Write(message); } /// <devdoc> /// <para>Writes the name of the value /// parameter to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value) { TraceInternal.Write(value); } /// <devdoc> /// <para>Writes a category name and message /// to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Write(string message, string category) { TraceInternal.Write(message, category); } /// <devdoc> /// <para>Writes a category name and the name of the value parameter to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection.</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Write(object value, string category) { TraceInternal.Write(value, category); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the trace listeners in the /// <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line terminator /// is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message) { TraceInternal.WriteLine(message); } /// <devdoc> /// <para>Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value) { TraceInternal.WriteLine(value); } /// <devdoc> /// <para>Writes a category name and message followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The default line /// terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message, string category) { TraceInternal.WriteLine(message, category); } /// <devdoc> /// <para>Writes a category name and the name of the value /// parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The /// default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value, string category) { TraceInternal.WriteLine(value, category); } /// <devdoc> /// <para>Writes a category name and the name of the value /// parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection. The /// default line terminator is a carriage return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string format, params object[] args) { TraceInternal.WriteLine(String.Format(CultureInfo.InvariantCulture, format, args)); } /// <devdoc> /// <para>Writes a message to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection /// if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message) { TraceInternal.WriteIf(condition, message); } /// <devdoc> /// <para>Writes the name of the value /// parameter to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> /// collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value) { TraceInternal.WriteIf(condition, value); } /// <devdoc> /// <para>Writes a category name and message /// to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> /// collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, string message, string category) { TraceInternal.WriteIf(condition, message, category); } /// <devdoc> /// <para>Writes a category name and the name of the value /// parameter to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. </para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteIf(bool condition, object value, string category) { TraceInternal.WriteIf(condition, value, category); } /// <devdoc> /// <para>Writes a message followed by a line terminator to the trace listeners in the /// <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string message) { TraceInternal.WriteLineIf(condition, message); } /// <devdoc> /// <para>Writes the name of the value /// parameter followed by a line terminator to the /// trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value) { TraceInternal.WriteLineIf(condition, value); } /// <devdoc> /// <para>Writes a category name and message /// followed by a line terminator to the trace /// listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection if a condition is /// <see langword='true'/>. The default line terminator is a carriage return followed /// by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string message, string category) { TraceInternal.WriteLineIf(condition, message, category); } /// <devdoc> /// <para>Writes a category name and the name of the value parameter followed by a line /// terminator to the trace listeners in the <see cref='System.Diagnostics.Debug.Listeners'/> collection /// if a condition is <see langword='true'/>. The default line terminator is a carriage /// return followed by a line feed (\r\n).</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, object value, string category) { TraceInternal.WriteLineIf(condition, value, category); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Indent() { TraceInternal.Indent(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.Conditional("DEBUG")] public static void Unindent() { TraceInternal.Unindent(); } #else static readonly object s_ForLock = new Object(); // This is the number of characters that OutputDebugString chunks at. const int internalWriteSize = 4091; [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition) { Assert(condition, String.Empty, String.Empty); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message) { Assert(condition, message, String.Empty); } [System.Diagnostics.Conditional("DEBUG")] [System.Security.SecuritySafeCritical] public static void Assert(bool condition, string message, string detailMessage) { if (!condition) { StackTrace stack = new StackTrace(true); int userStackFrameIndex = 0; string stackTrace; try { stackTrace = StackTraceToString(stack, userStackFrameIndex, stack.FrameCount - 1); } catch { stackTrace = ""; } WriteAssert(stackTrace, message, detailMessage); AssertWrapper.ShowAssert(stackTrace, stack.GetFrame(userStackFrameIndex), message, detailMessage); } } // Given a stack trace and start and end frame indexes, construct a // callstack that contains method, file and line number information. [System.Security.SecuritySafeCritical] private static string StackTraceToString(StackTrace trace, int startFrameIndex, int endFrameIndex) { StringBuilder sb = new StringBuilder(512); for (int i = startFrameIndex; i <= endFrameIndex; i++) { StackFrame frame = trace.GetFrame(i); MethodBase method = frame.GetMethod(); sb.Append(Environment.NewLine); sb.Append(" at "); if (method.ReflectedType != null) { sb.Append(method.ReflectedType.Name); } else { // This is for global methods and this is what shows up in windbg. sb.Append("<Module>"); } sb.Append("."); sb.Append(method.Name); sb.Append("("); ParameterInfo[] parameters = method.GetParameters(); for (int j = 0; j < parameters.Length; j++) { ParameterInfo parameter = parameters[j]; if (j > 0) sb.Append(", "); sb.Append(parameter.ParameterType.Name); sb.Append(" "); sb.Append(parameter.Name); } sb.Append(") "); sb.Append(frame.GetFileName()); int line = frame.GetFileLineNumber(); if (line > 0) { sb.Append("("); sb.Append(line.ToString(CultureInfo.InvariantCulture)); sb.Append(")"); } } sb.Append(Environment.NewLine); return sb.ToString(); } private static void WriteAssert(string stackTrace, string message, string detailMessage) { string assertMessage = SR.GetString(SR.DebugAssertBanner) + Environment.NewLine + SR.GetString(SR.DebugAssertShortMessage) + Environment.NewLine + message + Environment.NewLine + SR.GetString(SR.DebugAssertLongMessage) + Environment.NewLine + detailMessage + Environment.NewLine + stackTrace; WriteLine(assertMessage); } [System.Diagnostics.Conditional("DEBUG")] public static void Assert(bool condition, string message, string detailMessageFormat, params object[] args) { Assert(condition, message, String.Format(detailMessageFormat, args)); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message) { message = message + "\r\n"; // Use Windows end line on *all* Platforms // We don't want output from multiple threads to be interleaved. lock (s_ForLock) { // really huge messages mess up both VS and dbmon, so we chop it up into // reasonable chunks if it's too big if (message == null || message.Length <= internalWriteSize) { internalWrite(message); } else { int offset; for (offset = 0; offset < message.Length - internalWriteSize; offset += internalWriteSize) { internalWrite(message.Substring(offset, internalWriteSize)); } internalWrite(message.Substring(offset)); } } } [System.Security.SecuritySafeCritical] private static void internalWrite(string message) { if (Debugger.IsLogging()) { Debugger.Log(0, null, message); #if !FEATURE_PAL } else { if (message == null) Microsoft.Win32.SafeNativeMethods.OutputDebugString(String.Empty); else Microsoft.Win32.SafeNativeMethods.OutputDebugString(message); #endif //!FEATURE_PAL } } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(object value) { WriteLine((value == null) ? String.Empty : value.ToString()); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string format, params object[] args) { WriteLine(String.Format(null, format, args)); } #if FEATURE_NETCORE [System.Diagnostics.Conditional("DEBUG")] public static void WriteLineIf(bool condition, string message) { if(condition) { WriteLine(message); } } [System.Diagnostics.Conditional("DEBUG")] // This is used by our compression code. internal static void WriteLineIf(bool condition, string message, string category) { if (condition) { WriteLine(message); } } #endif // FEATURE_NETCORE #endif // SILVERLIGHT } }
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 HelloWebAPI.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; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cosmos.Core.IOGroup; using Cosmos.Common.Extensions; using Cosmos.Debug.Kernel; namespace Cosmos.HAL { public class PCIDevice { #region Enums public enum PCIHeaderType : byte { Normal = 0x00, Bridge = 0x01, Cardbus = 0x02 }; public enum PCIBist : byte { CocdMask = 0x0f, /* Return result */ Start = 0x40, /* 1 to start BIST, 2 secs or less */ Capable = 0x80 /* 1 if BIST capable */ } public enum PCIInterruptPIN : byte { None = 0x00, INTA = 0x01, INTB = 0x02, INTC = 0x03, INTD = 0x04 }; public enum PCICommand : short { IO = 0x1, /* Enable response in I/O space */ Memory = 0x2, /* Enable response in Memory space */ Master = 0x4, /* Enable bus mastering */ Special = 0x8, /* Enable response to special cycles */ Invalidate = 0x10, /* Use memory write and invalidate */ VGA_Pallete = 0x20, /* Enable palette snooping */ Parity = 0x40, /* Enable parity checking */ Wait = 0x80, /* Enable address/data stepping */ SERR = 0x100, /* Enable SERR */ Fast_Back = 0x200, /* Enable back-to-back writes */ } public enum Config : byte { VendorID = 0, DeviceID = 2, Command = 4, Status = 6, RevisionID = 8, ProgIF = 9, SubClass = 10, Class = 11, CacheLineSize = 12, LatencyTimer = 13, HeaderType = 14, BIST = 15, BAR0 = 16, BAR1 = 20, PrimaryBusNo = 24, SecondaryBusNo = 25, SubBusNo = 26, SecondarLT = 27, IOBase = 28, IOLimit = 29, SecondaryStatus = 30, MemoryBase = 32, MemoryLimit = 34, PrefMemoryBase = 36, PrefMemoryLimit = 38, PrefBase32Upper = 40, PrefLimit32upper = 44, PrefBase16Upper = 48, PrefLimit16upper = 50, CapabilityPointer = 52, Reserved = 53, ExpROMBaseAddress = 56, InterruptLine = 60, InterruptPIN = 61, BridgeControl = 62 }; #endregion public readonly uint bus; public readonly uint slot; public readonly uint function; public readonly uint BAR0; public readonly ushort VendorID; public readonly ushort DeviceID; public readonly ushort Status; public readonly byte RevisionID; public readonly byte ProgIF; public readonly byte Subclass; public readonly byte ClassCode; public readonly byte SecondaryBusNumber; public readonly bool DeviceExists; public readonly PCIHeaderType HeaderType; public readonly PCIBist BIST; public readonly PCIInterruptPIN InterruptPIN; public const ushort ConfigAddressPort = 0xCF8; public const ushort ConfigDataPort = 0xCFC; public PCIBaseAddressBar[] BaseAddressBar; protected static Core.IOGroup.PCI IO = new Core.IOGroup.PCI(); public byte InterruptLine { get; private set; } public PCICommand Command { get { return (PCICommand)ReadRegister16(0x04); } set { WriteRegister16(0x04, (ushort)value); } } /// <summary> /// Has this device been claimed by a driver /// </summary> public bool Claimed { get; set; } public PCIDevice(uint bus, uint slot, uint function) { this.bus = bus; this.slot = slot; this.function = function; VendorID = ReadRegister16((byte)Config.VendorID); DeviceID = ReadRegister16((byte)Config.DeviceID); BAR0 = ReadRegister32((byte)Config.BAR0); //Command = ReadRegister16((byte)Config.Command); //Status = ReadRegister16((byte)Config.Status); RevisionID = ReadRegister8((byte)Config.RevisionID); ProgIF = ReadRegister8((byte)Config.ProgIF); Subclass = ReadRegister8((byte)Config.SubClass); ClassCode = ReadRegister8((byte)Config.Class); SecondaryBusNumber = ReadRegister8((byte)Config.SecondaryBusNo); HeaderType = (PCIHeaderType)ReadRegister8((byte)Config.HeaderType); BIST = (PCIBist)ReadRegister8((byte)Config.BIST); InterruptPIN = (PCIInterruptPIN)ReadRegister8((byte)Config.InterruptPIN); InterruptLine = ReadRegister8((byte)Config.InterruptLine); if ((uint)VendorID == 0xFF && (uint)DeviceID == 0xFFFF) { DeviceExists = false; } else { DeviceExists = true; } if (HeaderType == PCIHeaderType.Normal) { BaseAddressBar = new PCIBaseAddressBar[6]; BaseAddressBar[0] = new PCIBaseAddressBar(ReadRegister32(0x10)); BaseAddressBar[1] = new PCIBaseAddressBar(ReadRegister32(0x14)); BaseAddressBar[2] = new PCIBaseAddressBar(ReadRegister32(0x18)); BaseAddressBar[3] = new PCIBaseAddressBar(ReadRegister32(0x1C)); BaseAddressBar[4] = new PCIBaseAddressBar(ReadRegister32(0x20)); BaseAddressBar[5] = new PCIBaseAddressBar(ReadRegister32(0x24)); } } public void EnableDevice() { Command |= PCICommand.Master | PCICommand.IO | PCICommand.Memory; } /// <summary> /// Get header type. /// </summary> /// <param name="Bus">A bus.</param> /// <param name="Slot">A slot.</param> /// <param name="Function">A function.</param> /// <returns>ushort value.</returns> public static ushort GetHeaderType(ushort Bus, ushort Slot, ushort Function) { uint xAddr = GetAddressBase(Bus, Slot, Function) | 0xE & 0xFC; IO.ConfigAddressPort.DWord = xAddr; return (byte)(IO.ConfigDataPort.DWord >> ((0xE % 4) * 8) & 0xFF); } /// <summary> /// Get vendor ID. /// </summary> /// <param name="Bus">A bus.</param> /// <param name="Slot">A slot.</param> /// <param name="Function">A function.</param> /// <returns>UInt16 value.</returns> public static ushort GetVendorID(ushort Bus, ushort Slot, ushort Function) { uint xAddr = GetAddressBase(Bus, Slot, Function) | 0x0 & 0xFC; IO.ConfigAddressPort.DWord = xAddr; return (ushort)(IO.ConfigDataPort.DWord >> ((0x0 % 4) * 8) & 0xFFFF); } #region IOReadWrite /// <summary> /// Read register - 8-bit. /// </summary> /// <param name="aRegister">A register to read.</param> /// <returns>byte value.</returns> protected byte ReadRegister8(byte aRegister) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; return (byte)(IO.ConfigDataPort.DWord >> ((aRegister % 4) * 8) & 0xFF); } protected void WriteRegister8(byte aRegister, byte value) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; IO.ConfigDataPort.Byte = value; } /// <summary> /// Read register 16. /// </summary> /// <param name="aRegister">A register.</param> /// <returns>UInt16 value.</returns> protected ushort ReadRegister16(byte aRegister) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; return (ushort)(IO.ConfigDataPort.DWord >> ((aRegister % 4) * 8) & 0xFFFF); } /// <summary> /// Write register 16. /// </summary> /// <param name="aRegister">A register.</param> /// <param name="value">A value.</param> protected void WriteRegister16(byte aRegister, ushort value) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; IO.ConfigDataPort.Word = value; } protected uint ReadRegister32(byte aRegister) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; return IO.ConfigDataPort.DWord; } protected void WriteRegister32(byte aRegister, uint value) { uint xAddr = GetAddressBase(bus, slot, function) | ((uint)(aRegister & 0xFC)); IO.ConfigAddressPort.DWord = xAddr; IO.ConfigDataPort.DWord = value; } #endregion /// <summary> /// Get address base. /// </summary> /// <param name="aBus">A bus.</param> /// <param name="aSlot">A slot.</param> /// <param name="aFunction">A function.</param> /// <returns>UInt32 value.</returns> protected static uint GetAddressBase(uint aBus, uint aSlot, uint aFunction) { return 0x80000000 | (aBus << 16) | ((aSlot & 0x1F) << 11) | ((aFunction & 0x07) << 8); } /// <summary> /// Enable memory. /// </summary> /// <param name="enable">bool value.</param> public void EnableMemory(bool enable) { ushort command = ReadRegister16(0x04); ushort flags = 0x0007; if (enable) command |= flags; else command &= (ushort)~flags; WriteRegister16(0x04, command); } public void EnableBusMaster(bool enable) { ushort command = ReadRegister16(0x04); ushort flags = (1 << 2); if (enable) command |= flags; else command &= (ushort)~flags; WriteRegister16(0x04, command); } public class DeviceClass { public static string GetDeviceString(PCIDevice device) { switch (device.VendorID) { case 0x1022: //AMD switch (device.DeviceID) { case 0x2000: return "AMD PCnet LANCE PCI Ethernet Controller"; default: return "AMD Unknown device"; } case 0x104B: //Sony switch (device.DeviceID) { case 0x1040: return "Mylex BT958 SCSI Host Adaptor"; default: return "Mylex Unknown device"; } case 0x1234: //Bochs switch (device.DeviceID) { case 0x1111: return "Bochs BGA"; default: return "Bochs Unknown device"; } case 0x1274: //Ensoniq switch (device.DeviceID) { case 0x1371: return "Ensoniq AudioPCI"; default: return "Ensoniq Unknown device"; } case 0x15AD: //VMware switch (device.DeviceID) { case 0x0405: return "VMware NVIDIA 9500MGS"; case 0x0740: return "Vmware Virtual Machine Communication Interface"; case 0x0770: return "VMware Standard Enhanced PCI to USB Host Controller"; case 0x0790: return "VMware 6.0 Virtual USB 2.0 Host Controller"; case 0x07A0: return "VMware PCI Express Root Port"; default: return "VMware Unknown device"; } case 0x8086: //Intel switch (device.DeviceID) { case 0x7190: return "Intel 440BX/ZX AGPset Host Bridge"; case 0x7191: return "Intel 440BX/ZX AGPset PCI-to-PCI bridge"; case 0x7110: return "Intel PIIX4/4E/4M ISA Bridge"; case 0x7111: return "Intel PIIX4/82371AB/EB/MB IDE"; case 0x7112: return "Intel PIIX4/4E/4M USB Interface"; case 0x7113: return "Intel PIIX4/82371AB/EB/MB ACPI"; default: return "Intel Unknown device"; } case 0x80EE: //VirtualBox switch (device.DeviceID) { case 0xBEEF: return "VirtualBox Graphics Adapter"; case 0xCAFE: return "VirtualBox Guest Service"; default: return "VirtualBox Unknown device"; } default: return "Unknown device"; } } public static string GetTypeString(PCIDevice device) { switch (device.ClassCode) { case 0x00: switch (device.Subclass) { case 0x01: return "VGA-Compatible Device"; default: return "0x00 Subclass"; } case 0x01: switch (device.Subclass) { case 0x00: return "SCSI Bus Controller"; case 0x01: return "IDE Controller"; case 0x02: return "Floppy Disk Controller"; case 0x03: return "IPI Bus Controller"; case 0x04: return "RAID Controller"; case 0x05: return "ATA Controller"; case 0x06: return "Serial ATA"; case 0x80: return "Unknown Mass Storage Controller"; default: return "Mass Storage Controller"; } case 0x02: switch (device.Subclass) { case 0x00: return "Ethernet Controller"; case 0x01: return "Token Ring Controller"; case 0x02: return "FDDI Controller"; case 0x03: return "ATM Controller"; case 0x04: return "ISDN Controller"; case 0x05: return "WorldFip Controller"; case 0x06: return "PICMG 2.14 Multi Computing"; case 0x80: return "Unknown Network Controller"; default: return "Network Controller"; } case 0x03: switch (device.Subclass) { case 0x00: switch (device.ProgIF) { case 0x00: return "VGA-Compatible Controller"; case 0x01: return "8512-Compatible Controller"; default: return "Unknown Display Controller"; } case 0x01: return "XGA Controller"; case 0x02: return "3D Controller (Not VGA-Compatible)"; case 0x80: return "Unknown Display Controller"; default: return "Display Controller"; } case 0x04: switch (device.Subclass) { case 0x00: return "Video Device"; case 0x01: return "Audio Device"; case 0x02: return "Computer Telephony Device"; case 0x80: return "Unknown Multimedia Controller"; default: return "Multimedia Controller"; } case 0x05: switch (device.Subclass) { case 0x00: return "RAM Controller"; case 0x01: return "Flash Controller"; case 0x80: return "Unknown Memory Controller"; default: return "Memory Controller"; } case 0x06: switch (device.Subclass) { case 0x00: return "Host Bridge"; case 0x01: return "ISA Bridge"; case 0x02: return "EISA Bridge"; case 0x03: return "MCA Bridge"; case 0x04: switch (device.ProgIF) { case 0x00: return "PCI-to-PCI Bridge"; case 0x01: return "PCI-to-PCI Bridge (Subtractive Decode)"; default: return "Unknown PCI-to-PCI Bridge"; } case 0x05: return "PCMCIA Bridge"; case 0x06: return "NuBus Bridge"; case 0x07: return "CardBus Bridge"; case 0x08: return "RACEway Bridge"; case 0x09: switch (device.ProgIF) { case 0x00: return "PCI-to-PCI Bridge (Semi-Transparent, Primary)"; case 0x01: return "PCI-to-PCI Bridge (Semi-Transparent, Secondary)"; default: return "Unknown PCI-to-PCI Bridge"; } case 0x0A: return "InfiniBrand-to-PCI Host Bridge"; case 0x80: return "Unknown Bridge Device"; default: return "Bridge Device"; } case 0x07: switch (device.Subclass) { case 0x00: switch (device.ProgIF) { case 0x00: return "Generic XT-Compatible Serial Controller"; case 0x01: return "16450-Compatible Serial Controller"; case 0x02: return "16550-Compatible Serial Controller"; case 0x03: return "16650-Compatible Serial Controller"; case 0x04: return "16750-Compatible Serial Controller"; case 0x05: return "16850-Compatible Serial Controller"; case 0x06: return "16950-Compatible Serial Controller"; default: return "Simple Communication Controller"; } case 0x01: switch (device.ProgIF) { case 0x00: return "Parallel Port"; case 0x01: return "Bi-Directional Parallel Port"; case 0x02: return "ECP 1.X Compliant Parallel Port"; case 0x03: return "IEEE 1284 Controller"; case 0xFE: return "IEEE 1284 Target Device"; default: return "Parallel Port"; } case 0x02: return "Multiport Serial Controller"; case 0x03: switch (device.ProgIF) { case 0x00: return "Generic Modem"; case 0x01: return "Hayes Compatible Modem (16450-Compatible Interface)"; case 0x02: return "Hayes Compatible Modem (16550-Compatible Interface)"; case 0x03: return "Hayes Compatible Modem (16650-Compatible Interface)"; case 0x04: return "Hayes Compatible Modem (16750-Compatible Interface)"; default: return "Modem"; } case 0x04: return "IEEE 488.1/2 (GPIB) Controller"; case 0x05: return "Smart Card"; case 0x80: return "Unknown Communications Device"; default: return "Simple Communication Controller"; } case 0x08: switch (device.Subclass) { case 0x00: switch (device.ProgIF) { case 0x00: return "Generic 8259 PIC"; case 0x01: return "ISA PIC"; case 0x02: return "EISA PIC"; case 0x10: return "I/O APIC Interrupt Controller"; case 0x20: return "I/O(x) APIC Interrupt Controller"; default: return "PIC"; } case 0x01: switch (device.ProgIF) { case 0x00: return "Generic 8237 DMA Controller"; case 0x01: return "ISA DMA Controller"; case 0x02: return "EISA DMA Controller"; default: return "DMA Controller"; } case 0x02: switch (device.ProgIF) { case 0x00: return "Generic 8254 System Timer"; case 0x01: return "ISA System Timer"; case 0x02: return "EISA System Timer"; default: return "System Timer"; } case 0x03: switch (device.ProgIF) { case 0x00: return "Generic RTC Controller"; case 0x01: return "ISA RTC Controller"; default: return "RTC Controller"; } case 0x04: return "Generic PCI Hot-Plug Controller"; case 0x80: return "Unknown System Peripheral"; default: return "Base System Peripheral"; } case 0x09: switch (device.Subclass) { case 0x00: return "Keyboard Controller"; case 0x01: return "Digitizer"; case 0x02: return "Mouse Controller"; case 0x03: return "Scanner Controller"; case 0x04: switch (device.ProgIF) { case 0x00: return "Gameport Controller (Generic)"; case 0x10: return "Gameport Controller (Legacy)"; default: return "Gameport Controller"; } case 0x80: return "Unknown Input Controller"; default: return "Input Device"; } case 0x0A: switch (device.Subclass) { case 0x00: return "Generic Docking Station"; case 0x80: return "Unknown Docking Station"; default: return "Docking Station"; } case 0x0B: switch (device.Subclass) { case 0x00: return "386 Processor"; case 0x01: return "486 Processor"; case 0x02: return "Pentium Processor"; case 0x10: return "Alpha Processor"; case 0x20: return "PowerPC Processor"; case 0x30: return "MIPS Processor"; case 0x40: return "Co-Processor"; default: return "Processor"; } case 0x0C: switch (device.Subclass) { case 0x00: switch (device.ProgIF) { case 0x00: return "IEEE 1394 Controller (FireWire)"; case 0x10: return "IEEE 1394 Controller (1394 OpenHCI Spec)"; default: return "IEEE Controller"; } case 0x01: return "ACCESS.bus"; case 0x02: return "SSA"; case 0x03: switch (device.ProgIF) { case 0x00: return "USB (Universal Host Controller Spec)"; case 0x10: return "USB (Open Host Controller Spec)"; case 0x20: return "USB2 Host Controller (Intel Enhanced Host Controller Interface)"; case 0x30: return "USB3 XHCI Controller"; case 0x80: return "Unspecified USB Controller"; case 0xFE: return "USB (Not Host Controller)"; default: return "USB"; } case 0x04: return "Fibre Channel"; case 0x05: return "SMBus"; case 0x06: return "InfiniBand"; case 0x07: switch (device.ProgIF) { case 0x00: return "IPMI SMIC Interface"; case 0x01: return "IPMI Kybd Controller Style Interface"; case 0x02: return "IPMI Block Transfer Interface"; default: return "IPMI SMIC Interface"; } case 0x08: return "SERCOS Interface Standard (IEC 61491)"; case 0x09: return "CANbus"; default: return "Serial Bus Controller"; } case 0x0D: switch (device.Subclass) { case 0x00: return "iRDA Compatible Controller"; case 0x01: return "Consumer IR Controller"; case 0x10: return "RF Controller"; case 0x11: return "Bluetooth Controller"; case 0x12: return "Broadband Controller"; case 0x20: return "Ethernet Controller (802.11a)"; case 0x21: return "Ethernet Controller (802.11b)"; case 0x80: return "Unknown Wireless Controller"; default: return "Wireless Controller"; } case 0x0E: switch (device.Subclass) { case 0x00: return "Message FIFO"; default: return "Intelligent I/O Controller"; } case 0x0F: switch (device.Subclass) { case 0x01: return "TV Controller"; case 0x02: return "Audio Controller"; case 0x03: return "Voice Controller"; case 0x04: return "Data Controller"; default: return "Satellite Communication Controller"; } case 0x10: switch (device.Subclass) { case 0x00: return "Network and Computing Encrpytion/Decryption"; case 0x10: return "Entertainment Encryption/Decryption"; case 0x80: return "Unknown Encryption/Decryption"; default: return "Encryption/Decryption Controller"; } case 0x11: switch (device.Subclass) { case 0x00: return "DPIO Modules"; case 0x01: return "Performance Counters"; case 0x10: return "Communications Syncrhonization Plus Time and Frequency Test/Measurment"; case 0x20: return "Management Card"; case 0x80: return "Unknown Data Acquisition/Signal Processing Controller"; default: return "Data Acquisition and Signal Processing Controller"; } default: return "Unknown device type"; } } } private static string ToHex(uint aNumber, byte aBits) { return "0x" + aNumber.ToHex(aBits / 4); } } public class PCIBaseAddressBar { private uint baseAddress = 0; private ushort prefetchable = 0; private ushort type = 0; private bool isIO = false; public PCIBaseAddressBar(uint raw) { isIO = (raw & 0x01) == 1; if (isIO) { baseAddress = raw & 0xFFFFFFFC; } else { type = (ushort)((raw >> 1) & 0x03); prefetchable = (ushort)((raw >> 3) & 0x01); switch (type) { case 0x00: baseAddress = raw & 0xFFFFFFF0; break; case 0x01: baseAddress = raw & 0xFFFFFFF0; break; } } } public uint BaseAddress { get { return baseAddress; } } public bool IsIO { get { return isIO; } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using Google.ProtocolBuffers.Collections; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers { public abstract partial class ExtendableMessage<TMessage, TBuilder> : GeneratedMessage<TMessage, TBuilder> where TMessage : GeneratedMessage<TMessage, TBuilder> where TBuilder : GeneratedBuilder<TMessage, TBuilder>, new() { protected ExtendableMessage() { } private readonly FieldSet extensions = FieldSet.CreateInstance(); /// <summary> /// Access for the builder. /// </summary> internal FieldSet Extensions { get { return extensions; } } /// <summary> /// Checks if a singular extension is present. /// </summary> public bool HasExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) { return extensions.HasField(extension.Descriptor); } /// <summary> /// Returns the number of elements in a repeated extension. /// </summary> public int GetExtensionCount<TExtension>(GeneratedExtensionBase<IList<TExtension>> extension) { return extensions.GetRepeatedFieldCount(extension.Descriptor); } /// <summary> /// Returns the value of an extension. /// </summary> public TExtension GetExtension<TExtension>(GeneratedExtensionBase<TExtension> extension) { object value = extensions[extension.Descriptor]; if (value == null) { return (TExtension) extension.MessageDefaultInstance; } else { return (TExtension) extension.FromReflectionType(value); } } /// <summary> /// Returns one element of a repeated extension. /// </summary> public TExtension GetExtension<TExtension>(GeneratedExtensionBase<IList<TExtension>> extension, int index) { return (TExtension) extension.SingularFromReflectionType(extensions[extension.Descriptor, index]); } /// <summary> /// Called to check if all extensions are initialized. /// </summary> protected bool ExtensionsAreInitialized { get { return extensions.IsInitialized; } } public override bool IsInitialized { get { return base.IsInitialized && ExtensionsAreInitialized; } } #region Reflection public override IDictionary<FieldDescriptor, object> AllFields { get { IDictionary<FieldDescriptor, object> result = GetMutableFieldMap(); foreach (KeyValuePair<IFieldDescriptorLite, object> entry in extensions.AllFields) { result[(FieldDescriptor) entry.Key] = entry.Value; } return Dictionaries.AsReadOnly(result); } } public override bool HasField(FieldDescriptor field) { if (field.IsExtension) { VerifyContainingType(field); return extensions.HasField(field); } else { return base.HasField(field); } } public override object this[FieldDescriptor field] { get { if (field.IsExtension) { VerifyContainingType(field); object value = extensions[field]; if (value == null) { // Lacking an ExtensionRegistry, we have no way to determine the // extension's real type, so we return a DynamicMessage. // TODO(jonskeet): Work out what this means return DynamicMessage.GetDefaultInstance(field.MessageType); } else { return value; } } else { return base[field]; } } } public override int GetRepeatedFieldCount(FieldDescriptor field) { if (field.IsExtension) { VerifyContainingType(field); return extensions.GetRepeatedFieldCount(field); } else { return base.GetRepeatedFieldCount(field); } } public override object this[FieldDescriptor field, int index] { get { if (field.IsExtension) { VerifyContainingType(field); return extensions[field, index]; } else { return base[field, index]; } } } internal void VerifyContainingType(FieldDescriptor field) { if (field.ContainingType != DescriptorForType) { throw new ArgumentException("FieldDescriptor does not match message type."); } } #endregion /// <summary> /// Used by subclasses to serialize extensions. Extension ranges may be /// interleaves with field numbers, but we must write them in canonical /// (sorted by field number) order. This class helps us to write individual /// ranges of extensions at once. /// /// TODO(jonskeet): See if we can improve this in terms of readability. /// </summary> protected class ExtensionWriter { private readonly IEnumerator<KeyValuePair<IFieldDescriptorLite, object>> iterator; private readonly FieldSet extensions; private KeyValuePair<IFieldDescriptorLite, object>? next = null; internal ExtensionWriter(ExtendableMessage<TMessage, TBuilder> message) { extensions = message.extensions; iterator = message.extensions.GetEnumerator(); if (iterator.MoveNext()) { next = iterator.Current; } } public void WriteUntil(int end, ICodedOutputStream output) { while (next != null && next.Value.Key.FieldNumber < end) { extensions.WriteField(next.Value.Key, next.Value.Value, output); if (iterator.MoveNext()) { next = iterator.Current; } else { next = null; } } } } protected ExtensionWriter CreateExtensionWriter(ExtendableMessage<TMessage, TBuilder> message) { return new ExtensionWriter(message); } /// <summary> /// Called by subclasses to compute the size of extensions. /// </summary> protected int ExtensionsSerializedSize { get { return extensions.SerializedSize; } } internal void VerifyExtensionContainingType<TExtension>(GeneratedExtensionBase<TExtension> extension) { if (extension.Descriptor.ContainingType != DescriptorForType) { // This can only happen if someone uses unchecked operations. throw new ArgumentException("Extension is for type \"" + extension.Descriptor.ContainingType.FullName + "\" which does not match message type \"" + DescriptorForType.FullName + "\"."); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Sqlite; using osu.Framework.Development; using osu.Framework.IO.Network; using osu.Framework.Logging; using osu.Framework.Platform; using osu.Framework.Testing; using osu.Framework.Threading; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using SharpCompress.Compressors; using SharpCompress.Compressors.BZip2; namespace osu.Game.Beatmaps { public partial class BeatmapManager { [ExcludeFromDynamicCompile] private class BeatmapOnlineLookupQueue : IDisposable { private readonly IAPIProvider api; private readonly Storage storage; private const int update_queue_request_concurrency = 4; private readonly ThreadedTaskScheduler updateScheduler = new ThreadedTaskScheduler(update_queue_request_concurrency, nameof(BeatmapOnlineLookupQueue)); private FileWebRequest cacheDownloadRequest; private const string cache_database_name = "online.db"; public BeatmapOnlineLookupQueue(IAPIProvider api, Storage storage) { this.api = api; this.storage = storage; // avoid downloading / using cache for unit tests. if (!DebugUtils.IsNUnitRunning && !storage.Exists(cache_database_name)) prepareLocalCache(); } public Task UpdateAsync(BeatmapSetInfo beatmapSet, CancellationToken cancellationToken) { return Task.WhenAll(beatmapSet.Beatmaps.Select(b => UpdateAsync(beatmapSet, b, cancellationToken)).ToArray()); } // todo: expose this when we need to do individual difficulty lookups. protected Task UpdateAsync(BeatmapSetInfo beatmapSet, BeatmapInfo beatmap, CancellationToken cancellationToken) => Task.Factory.StartNew(() => lookup(beatmapSet, beatmap), cancellationToken, TaskCreationOptions.HideScheduler | TaskCreationOptions.RunContinuationsAsynchronously, updateScheduler); private void lookup(BeatmapSetInfo set, BeatmapInfo beatmap) { if (checkLocalCache(set, beatmap)) return; if (api?.State.Value != APIState.Online) return; var req = new GetBeatmapRequest(beatmap); req.Failure += fail; try { // intentionally blocking to limit web request concurrency api.Perform(req); var res = req.Result; if (res != null) { beatmap.Status = res.Status; beatmap.BeatmapSet.Status = res.BeatmapSet.Status; beatmap.BeatmapSet.OnlineBeatmapSetID = res.OnlineBeatmapSetID; beatmap.OnlineBeatmapID = res.OnlineBeatmapID; if (beatmap.Metadata != null) beatmap.Metadata.AuthorID = res.AuthorID; if (beatmap.BeatmapSet.Metadata != null) beatmap.BeatmapSet.Metadata.AuthorID = res.AuthorID; LogForModel(set, $"Online retrieval mapped {beatmap} to {res.OnlineBeatmapSetID} / {res.OnlineBeatmapID}."); } } catch (Exception e) { fail(e); } void fail(Exception e) { beatmap.OnlineBeatmapID = null; LogForModel(set, $"Online retrieval failed for {beatmap} ({e.Message})"); } } private void prepareLocalCache() { string cacheFilePath = storage.GetFullPath(cache_database_name); string compressedCacheFilePath = $"{cacheFilePath}.bz2"; cacheDownloadRequest = new FileWebRequest(compressedCacheFilePath, $"https://assets.ppy.sh/client-resources/{cache_database_name}.bz2?{DateTimeOffset.UtcNow:yyyyMMdd}"); cacheDownloadRequest.Failed += ex => { File.Delete(compressedCacheFilePath); File.Delete(cacheFilePath); Logger.Log($"{nameof(BeatmapOnlineLookupQueue)}'s online cache download failed: {ex}", LoggingTarget.Database); }; cacheDownloadRequest.Finished += () => { try { using (var stream = File.OpenRead(cacheDownloadRequest.Filename)) using (var outStream = File.OpenWrite(cacheFilePath)) using (var bz2 = new BZip2Stream(stream, CompressionMode.Decompress, false)) bz2.CopyTo(outStream); // set to null on completion to allow lookups to begin using the new source cacheDownloadRequest = null; } catch (Exception ex) { Logger.Log($"{nameof(BeatmapOnlineLookupQueue)}'s online cache extraction failed: {ex}", LoggingTarget.Database); File.Delete(cacheFilePath); } finally { File.Delete(compressedCacheFilePath); } }; cacheDownloadRequest.PerformAsync(); } private bool checkLocalCache(BeatmapSetInfo set, BeatmapInfo beatmap) { // download is in progress (or was, and failed). if (cacheDownloadRequest != null) return false; // database is unavailable. if (!storage.Exists(cache_database_name)) return false; try { using (var db = new SqliteConnection(storage.GetDatabaseConnectionString("online"))) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = "SELECT beatmapset_id, beatmap_id, approved, user_id FROM osu_beatmaps WHERE checksum = @MD5Hash OR beatmap_id = @OnlineBeatmapID OR filename = @Path"; cmd.Parameters.Add(new SqliteParameter("@MD5Hash", beatmap.MD5Hash)); cmd.Parameters.Add(new SqliteParameter("@OnlineBeatmapID", beatmap.OnlineBeatmapID ?? (object)DBNull.Value)); cmd.Parameters.Add(new SqliteParameter("@Path", beatmap.Path)); using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { var status = (BeatmapSetOnlineStatus)reader.GetByte(2); beatmap.Status = status; beatmap.BeatmapSet.Status = status; beatmap.BeatmapSet.OnlineBeatmapSetID = reader.GetInt32(0); beatmap.OnlineBeatmapID = reader.GetInt32(1); if (beatmap.Metadata != null) beatmap.Metadata.AuthorID = reader.GetInt32(3); if (beatmap.BeatmapSet.Metadata != null) beatmap.BeatmapSet.Metadata.AuthorID = reader.GetInt32(3); LogForModel(set, $"Cached local retrieval for {beatmap}."); return true; } } } } } catch (Exception ex) { LogForModel(set, $"Cached local retrieval for {beatmap} failed with {ex}."); } return false; } public void Dispose() { cacheDownloadRequest?.Dispose(); updateScheduler?.Dispose(); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Deployment; /// <summary> /// Compute implementation. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class ComputeImpl : PlatformTargetAdapter { /** */ private const int OpBroadcast = 2; /** */ private const int OpExec = 3; /** */ private const int OpExecAsync = 4; /** */ private const int OpUnicast = 5; /** */ private const int OpWithNoFailover = 6; /** */ private const int OpWithTimeout = 7; /** */ private const int OpExecNative = 8; /** */ private const int OpWithNoResultCache = 9; /** */ private const int OpWithExecutor = 10; /** */ private const int OpAffinityCallPartition = 11; /** */ private const int OpAffinityRunPartition = 12; /** */ private const int OpAffinityCall = 13; /** */ private const int OpAffinityRun = 14; /** Underlying projection. */ private readonly ClusterGroupImpl _prj; /** Whether objects must be kept in binary form. */ private readonly ThreadLocal<bool> _keepBinary = new ThreadLocal<bool>(() => false); /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="prj">Projection.</param> /// <param name="keepBinary">Binary flag.</param> public ComputeImpl(IPlatformTargetInternal target, ClusterGroupImpl prj, bool keepBinary) : base(target) { _prj = prj; _keepBinary.Value = keepBinary; } /// <summary> /// Grid projection to which this compute instance belongs. /// </summary> public IClusterGroup ClusterGroup { get { return _prj; } } /// <summary> /// Sets no-failover flag for the next executed task on this projection in the current thread. /// If flag is set, job will be never failed over even if remote node crashes or rejects execution. /// When task starts execution, the no-failover flag is reset, so all other task will use default /// failover policy, unless this flag is set again. /// </summary> public void WithNoFailover() { DoOutInOp(OpWithNoFailover); } /// <summary> /// Sets task timeout for the next executed task on this projection in the current thread. /// When task starts execution, the timeout is reset, so one timeout is used only once. /// </summary> /// <param name="timeout">Computation timeout in milliseconds.</param> public void WithTimeout(long timeout) { DoOutInOp(OpWithTimeout, timeout); } /// <summary> /// Disables caching for the next executed task in the current thread. /// </summary> public void WithNoResultCache() { DoOutInOp(OpWithNoResultCache); } /// <summary> /// Sets keep-binary flag for the next executed Java task on this projection in the current /// thread so that task argument passed to Java and returned task results will not be /// deserialized. /// </summary> public void WithKeepBinary() { _keepBinary.Value = true; } /// <summary> /// Returns a new <see cref="ComputeImpl"/> instance associated with a specified executor. /// </summary> /// <param name="executorName">Executor name.</param> /// <returns>New <see cref="ComputeImpl"/> instance associated with a specified executor.</returns> public ComputeImpl WithExecutor(string executorName) { var target = DoOutOpObject(OpWithExecutor, w => w.WriteString(executorName)); return new ComputeImpl(target, _prj, _keepBinary.Value); } /// <summary> /// Executes given Java task on the grid projection. If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { return DoOutInOp<TReduceRes>(OpExec, writer => WriteTask(writer, taskName, taskArg, nodes)); } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given Java task asynchronously on the grid projection. /// If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public Future<TReduceRes> ExecuteJavaTaskAsync<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { return DoOutOpObjectAsync<TReduceRes>(OpExecAsync, w => WriteTask(w, taskName, taskArg, nodes)); } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="task">Task to execute.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task, TArg taskArg) { IgniteArgumentCheck.NotNull(task, "task"); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, taskArg); long ptr = Marshaller.Ignite.HandleRegistry.Allocate(holder); var futTarget = DoOutOpObject(OpExecNative, (IBinaryStream s) => { s.WriteLong(ptr); s.WriteLong(_prj.TopologyVersion); }); var future = holder.Future; future.SetTarget(new Listenable(futTarget)); return future; } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="taskType">Task type.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg) { IgniteArgumentCheck.NotNull(taskType, "taskType"); object task = FormatterServices.GetUninitializedObject(taskType); var task0 = task as IComputeTask<TArg, TJobRes, TReduceRes>; if (task0 == null) throw new IgniteException("Task type doesn't implement IComputeTask: " + taskType.Name); return Execute(task0, taskArg); } /// <summary> /// Executes provided job on a node in this grid projection. The result of the /// job execution is returned from the result closure. /// </summary> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Execute<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(clo.ToNonGeneric()), null, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <returns>Collection of job results for this execution.</returns> public Future<ICollection<TJobRes>> Execute<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (IComputeFunc<TJobRes> clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Collection of job results for this execution.</returns> public Future<TReduceRes> Execute<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (var clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeReducingClosureTask<object, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Broadcasts given job to all nodes in grid projection. Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeOutFuncJob(clo.ToNonGeneric()), null, true); } /// <summary> /// Broadcasts given closure job with passed in argument to all nodes in grid projection. /// Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <param name="arg">Job closure argument.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, true); } /// <summary> /// Broadcasts given job to all nodes in grid projection. /// </summary> /// <param name="action">Job to broadcast to all projection nodes.</param> public Future<object> Broadcast(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action), opId: OpBroadcast); } /// <summary> /// Executes provided job on a node in this grid projection. /// </summary> /// <param name="action">Job to execute.</param> public Future<object> Run(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action)); } /// <summary> /// Executes collection of jobs on Ignite nodes within this grid projection. /// </summary> /// <param name="actions">Jobs to execute.</param> public Future<object> Run(IEnumerable<IComputeAction> actions) { IgniteArgumentCheck.NotNull(actions, "actions"); var actions0 = actions as ICollection; if (actions0 == null) { var jobs = actions.Select(a => new ComputeActionJob(a)).ToList(); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: jobs.Count); } else { var jobs = actions.Select(a => new ComputeActionJob(a)); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: actions0.Count); } } /// <summary> /// Executes provided closure job on a node in this grid projection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="arg">Job argument.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<TArg, TJobRes, TJobRes>(), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <returns>Collection of job results.</returns> public Future<ICollection<TJobRes>> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); var jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeMultiClosureTask<TArg, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. The returned job results will be reduced /// into an individual result by provided reducer. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Reduced job result for this execution.</returns> public Future<TReduceRes> Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeReducingClosureTask<TArg, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="action">Job to execute.</param> public Future<object> AffinityRun(string cacheName, object affinityKey, IComputeAction action) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); IgniteArgumentCheck.NotNull(action, "action"); return DoAffinityOp<object>(cacheName, null, affinityKey, action, OpAffinityRun); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> /// <typeparam name="TJobRes">Type of job result.</typeparam> public Future<TJobRes> AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); IgniteArgumentCheck.NotNull(clo, "clo"); return DoAffinityOp<TJobRes>(cacheName, null, affinityKey, clo, OpAffinityCall); } /// <summary> /// Executes given func on a node where specified partition is located. /// </summary> /// <param name="cacheNames">Cache names. First cache is used for co-location.</param> /// <param name="partition">Partition.</param> /// <param name="func">Func to execute.</param> /// <typeparam name="TJobRes">Result type.</typeparam> /// <returns>Result.</returns> public Future<TJobRes> AffinityCall<TJobRes>(IEnumerable<string> cacheNames, int partition, IComputeFunc<TJobRes> func) { return DoAffinityOp<TJobRes>(cacheNames, partition, null, func, OpAffinityCallPartition); } /// <summary> /// Executes given func on a node where specified partition is located. /// </summary> /// <param name="cacheNames">Cache names. First cache is used for co-location.</param> /// <param name="partition">Partition.</param> /// <param name="func">Func to execute.</param> /// <returns>Result.</returns> public Future<object> AffinityRun(IEnumerable<string> cacheNames, int partition, IComputeAction func) { return DoAffinityOp<object>(cacheNames, partition, null, func, OpAffinityRunPartition); } /// <summary> /// Performs affinity operation with. /// </summary> private Future<TJobRes> DoAffinityOp<TJobRes>(object cacheNames, int? partition, object key, object func, int op) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); IgniteArgumentCheck.NotNull(func, "func"); var handleRegistry = Marshaller.Ignite.HandleRegistry; var handle = handleRegistry.Allocate(func); try { var fut = DoOutOpObjectAsync<TJobRes>(op, w => { var cacheName = cacheNames as string; if (cacheName != null) { w.WriteString(cacheName); } else { var cacheCount = w.WriteStrings((IEnumerable<string>) cacheNames); if (cacheCount == 0) { throw new ArgumentException("cacheNames can not be empty", "cacheNames"); } } if (partition != null) { w.WriteInt(partition.Value); } else { w.WriteObjectDetached(key); } w.WriteWithPeerDeployment(func); w.WriteLong(handle); }); fut.Task.ContWith(_ => handleRegistry.Release(handle), TaskContinuationOptions.ExecuteSynchronously); return fut; } catch { handleRegistry.Release(handle); throw; } } /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { bool keep = _keepBinary.Value; return Marshaller.Unmarshal<T>(stream, keep); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="broadcast">Broadcast flag.</param> /// <returns>Future.</returns> private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job, ICollection<IComputeJob> jobs, bool broadcast) { return ExecuteClosures0(task, job, jobs, broadcast ? OpBroadcast : OpUnicast, jobs == null ? 1 : jobs.Count); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="opId">Op code.</param> /// <param name="jobsCount">Jobs count.</param> /// <param name="writeAction">Custom write action.</param> /// <returns>Future.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job = null, IEnumerable<IComputeJob> jobs = null, int opId = OpUnicast, int jobsCount = 0, Action<BinaryWriter> writeAction = null) { Debug.Assert(job != null || jobs != null); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, default(TArg)); var taskHandle = Marshaller.Ignite.HandleRegistry.Allocate(holder); var jobHandles = new List<long>(job != null ? 1 : jobsCount); try { Exception err = null; try { var futTarget = DoOutOpObject(opId, writer => { writer.WriteLong(taskHandle); if (job != null) { writer.WriteInt(1); jobHandles.Add(WriteJob(job, writer)); } else { writer.WriteInt(jobsCount); Debug.Assert(jobs != null, "jobs != null"); jobHandles.AddRange(jobs.Select(jobEntry => WriteJob(jobEntry, writer))); } holder.JobHandles(jobHandles); if (writeAction != null) writeAction(writer); }); holder.Future.SetTarget(new Listenable(futTarget)); } catch (Exception e) { err = e; } if (err != null) { // Manual job handles release because they were not assigned to the task yet. foreach (var hnd in jobHandles) Marshaller.Ignite.HandleRegistry.Release(hnd); holder.CompleteWithError(taskHandle, err); } } catch (Exception e) { // This exception means that out-op failed. holder.CompleteWithError(taskHandle, e); } return holder.Future; } /// <summary> /// Writes the job. /// </summary> /// <param name="job">The job.</param> /// <param name="writer">The writer.</param> /// <returns>Handle to the job holder</returns> private long WriteJob(IComputeJob job, BinaryWriter writer) { var jobHolder = new ComputeJobHolder((Ignite) _prj.Ignite, job); var jobHandle = Marshaller.Ignite.HandleRegistry.Allocate(jobHolder); writer.WriteLong(jobHandle); try { writer.WriteObjectDetached(jobHolder); } catch (Exception) { Marshaller.Ignite.HandleRegistry.Release(jobHandle); throw; } return jobHandle; } /// <summary> /// Write task to the writer. /// </summary> /// <param name="writer">Writer.</param> /// <param name="taskName">Task name.</param> /// <param name="taskArg">Task arg.</param> /// <param name="nodes">Nodes.</param> private void WriteTask(IBinaryRawWriter writer, string taskName, object taskArg, ICollection<IClusterNode> nodes) { writer.WriteString(taskName); writer.WriteBoolean(_keepBinary.Value); writer.WriteObject(taskArg); WriteNodeIds(writer, nodes); } /// <summary> /// Write node IDs. /// </summary> /// <param name="writer">Writer.</param> /// <param name="nodes">Nodes.</param> private static void WriteNodeIds(IBinaryRawWriter writer, ICollection<IClusterNode> nodes) { if (nodes == null) writer.WriteBoolean(false); else { writer.WriteBoolean(true); writer.WriteInt(nodes.Count); foreach (IClusterNode node in nodes) writer.WriteGuid(node.Id); } } /// <summary> /// Gets element count or zero. /// </summary> private static int GetCountOrZero(object collection) { var coll = collection as ICollection; return coll == null ? 0 : coll.Count; } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if ENCODER && BLOCK_ENCODER && CODE_ASSEMBLER using System; using Iced.Intel; using Iced.UnitTests.Intel.EncoderTests; using Xunit; using static Iced.Intel.AssemblerRegisters; namespace Iced.UnitTests.Intel.AssemblerTests { // Make sure it can be derived sealed class MyAssembler : Assembler { public MyAssembler() : base(64) { } } public sealed partial class AssemblerTests64 { [Fact] void xlatb() { TestAssembler(c => c.xlatb(), Instruction.Create(Code.Xlat_m8, new MemoryOperand(Register.RBX, Register.AL))); } [Fact] public void xbegin_label() { TestAssembler(c => c.xbegin(CreateAndEmitLabel(c)), AssignLabel(Instruction.CreateXbegin(Bitness, 1), 1), LocalOpCodeFlags.Branch); } [Fact] public void xbegin_offset() { TestAssembler(c => c.xbegin(12752), Instruction.CreateXbegin(Bitness, 12752), LocalOpCodeFlags.BranchUlong | LocalOpCodeFlags.IgnoreCode); } [Fact] void Ctor() { var c = new Assembler(Bitness); Assert.Equal(Bitness, c.Bitness); Assert.True(c.PreferVex); Assert.True(c.PreferBranchShort); Assert.Empty(c.Instructions); Assert.True(c.CurrentLabel.IsEmpty); } [Fact] void Reset_works() { var c = new Assembler(Bitness); c.CreateLabel(); c.add(rax, rcx); _ = c.@lock; c.PreferVex = false; c.PreferBranchShort = false; c.Reset(); Assert.False(c.PreferVex); Assert.False(c.PreferBranchShort); Assert.Empty(c.Instructions); Assert.True(c.CurrentLabel.IsEmpty); var writer = new CodeWriterImpl(); var result = c.Assemble(writer, 0); Assert.Single(result.Result); Assert.Empty(writer.ToArray()); } [Fact] void Invalid_bitness_throws() { foreach (var bitness in BitnessUtils.GetInvalidBitnessValues()) Assert.Throws<ArgumentOutOfRangeException>(() => new Assembler(bitness)); } [Fact] void Assemble_throws_if_null_writer() { var c = new Assembler(Bitness); c.nop(); Assert.Throws<ArgumentNullException>(() => c.Assemble(null, 0)); } [Fact] void TryAssemble_throws_if_null_writer() { var c = new Assembler(Bitness); c.nop(); Assert.Throws<ArgumentNullException>(() => c.TryAssemble(null, 0, out _, out _)); } [Fact] void Assemble_throws_if_error() { var c = new Assembler(64); c.aaa(); Assert.Throws<InvalidOperationException>(() => c.Assemble(new CodeWriterImpl(), 0)); } [Fact] void TryAssemble_returns_error_string_if_it_failed() { var c = new Assembler(64); c.aaa(); bool b = c.TryAssemble(new CodeWriterImpl(), 0, out var errorMessage, out var result); Assert.False(b); Assert.NotNull(errorMessage); Assert.NotNull(result.Result); Assert.Empty(result.Result); } #if !NO_EVEX [Fact] void Test_opmask_registers() { TestAssembler(c => c.vmovups(zmm0.k1, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K1), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k2, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K2), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k3, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K3), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k4, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K4), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k5, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K5), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k6, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K6), LocalOpCodeFlags.PreferEvex); TestAssembler(c => c.vmovups(zmm0.k7, zmm1), ApplyK(Instruction.Create(Code.EVEX_Vmovups_zmm_k1z_zmmm512, zmm0, zmm1), Register.K7), LocalOpCodeFlags.PreferEvex); } #endif [Fact] public void TestDeclareData_db_array() { TestAssemblerDeclareData(c => c.db(Array.Empty<byte>()), Array.Empty<byte>()); TestAssemblerDeclareData(c => c.db(new byte[] { 1 }), new byte[] { 1 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }); } #if HAS_SPAN [Fact] public void TestDeclareData_db_span() { TestAssemblerDeclareData(c => c.db(Array.Empty<byte>().AsSpan()), Array.Empty<byte>()); TestAssemblerDeclareData(c => c.db(new byte[] { 1 }.AsSpan()), new byte[] { 1 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }.AsSpan()), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }.AsSpan()), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }.AsSpan()), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }); TestAssemblerDeclareData(c => c.db(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }.AsSpan()), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }); } #endif [Fact] public void TestDeclareData_db_array_index_length() { TestAssemblerDeclareData(c => c.db(new byte[] { 97, 98, 1, 99, 100, 101 }, 2, 1), new byte[] { 1 }); TestAssemblerDeclareData(c => c.db(new byte[] { 97, 98, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 99, 100, 101 }, 2, 16), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }); TestAssemblerDeclareData(c => c.db(new byte[] { 97, 98, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 99, 100, 101 }, 2, 17), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }); TestAssemblerDeclareData(c => c.db(new byte[] { 97, 98, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 99, 100, 101 }, 2, 32), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }); TestAssemblerDeclareData(c => c.db(new byte[] { 97, 98, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 99, 100, 101 }, 2, 33), new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 }); } [Fact] public void TestDeclareData_db_array_throws_if_null_array() { var assembler = new Assembler(Bitness); Assert.Throws<ArgumentNullException>(() => assembler.db(null)); } [Fact] public void TestDeclareData_db_array_index_length_throws() { var assembler = new Assembler(Bitness); Assert.Throws<ArgumentNullException>(() => assembler.db(null, 0, 0)); Assert.Throws<ArgumentNullException>(() => assembler.db(null, 1, 2)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { }, 1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { }, 0, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, -1, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 0, 4)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 1, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 3, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 4, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => assembler.db(new byte[] { 1, 2, 3 }, 4, -1)); } [Fact] public void TestManualInvalid() { // pop_regSegment AssertInvalid(() => { TestAssembler(c => c.pop(cs), default); }); // push_regSegment // create a none register which won't match with any entries AssertInvalid(() => { TestAssembler(c => c.push(new AssemblerRegisterSegment()), default); }); } [Fact] public void TestInvalidStateAssembler() { { var assembler = new Assembler(Bitness); var writer = new CodeWriterImpl(); var ex = Assert.Throws<InvalidOperationException>(() => assembler.rep.Assemble(writer, 0)); Assert.Contains("Unused prefixes", ex.Message); } { var assembler = new Assembler(Bitness); var label = assembler.CreateLabel(("BadLabel")); assembler.Label(ref label); var writer = new CodeWriterImpl(); var ex = Assert.Throws<InvalidOperationException>(() => assembler.Assemble(writer, 0)); Assert.Contains("Unused label", ex.Message); } } [Fact] public void TestLabelRIP() { { var c = new Assembler(Bitness); var label0 = c.CreateLabel(); var label1 = c.CreateLabel(); c.nop(); c.nop(); c.nop(); c.Label(ref label1); c.nop(); var writer = new CodeWriterImpl(); var result = c.Assemble(writer, 0x100, BlockEncoderOptions.ReturnNewInstructionOffsets); var label1RIP = result.GetLabelRIP(label1); Assert.Equal((ulong)0x103, label1RIP); Assert.Throws<ArgumentOutOfRangeException>(() => result.GetLabelRIP(label1, 1)); Assert.Throws<ArgumentException>(() => result.GetLabelRIP(label0)); } { var c = new Assembler(Bitness); var label1 = c.CreateLabel(); c.nop(); c.Label(ref label1); c.nop(); // Cannot use a label not created via CreateLabel var emptyLabel = new Label(); Assert.Throws<ArgumentException>(() => c.Label(ref emptyLabel)); // Cannot use a label already emitted Assert.Throws<ArgumentException>(() => c.Label(ref label1)); var writer = new CodeWriterImpl(); var result = c.Assemble(writer, 0); // Will throw without BlockEncoderOptions.ReturnNewInstructionOffsets Assert.Throws<ArgumentOutOfRangeException>(() => result.GetLabelRIP(label1)); Assert.Throws<ArgumentOutOfRangeException>(() => default(AssemblerResult).GetLabelRIP(label1)); Assert.Throws<ArgumentException>(() => result.GetLabelRIP(new Label())); } } [Fact] public void TestInstructionPrefixes() { { var inst = Instruction.CreateStosd(Bitness); inst.HasRepPrefix = true; TestAssembler(c => c.rep.stosd(), inst); } { var inst = Instruction.CreateStosd(Bitness); inst.HasRepePrefix = true; TestAssembler(c => c.repe.stosd(), inst); } { var inst = Instruction.CreateStosd(Bitness); inst.HasRepnePrefix = true; TestAssembler(c => c.repne.stosd(), inst); } { var inst = Instruction.Create(Code.Xchg_rm64_r64, __[rdx].ToMemoryOperand(64), rax); inst.HasXacquirePrefix = true; TestAssembler(c => c.xacquire.xchg(__[rdx], rax), inst); } { var inst = Instruction.Create(Code.Xchg_rm64_r64, __[rdx].ToMemoryOperand(64), rax); inst.HasLockPrefix = true; TestAssembler(c => c.@lock.xchg(__[rdx], rax), inst); } { var inst = Instruction.Create(Code.Xchg_rm64_r64, __[rdx].ToMemoryOperand(64), rax); inst.HasXreleasePrefix = true; TestAssembler(c => c.xrelease.xchg(__[rdx], rax), inst); } { var inst = Instruction.Create(Code.Call_rm64, __[rax].ToMemoryOperand(64)); inst.SegmentPrefix = Register.DS; TestAssembler(c => c.notrack.call(__qword_ptr[rax]), inst); } { var inst = Instruction.Create(Code.Call_rm64, __[rax].ToMemoryOperand(64)); inst.SegmentPrefix = Register.DS; inst.HasRepnePrefix = true; TestAssembler(c => c.bnd.notrack.call(__qword_ptr[rax]), inst); } } #if !NO_EVEX [Fact] public void TestOperandModifiers() { { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K1; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k1.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K2; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k2.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K3; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k3.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K4; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k4.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K5; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k5.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K6; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k6.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vunpcklps_xmm_k1z_xmm_xmmm128b32, xmm2, xmm6, __[rax].ToMemoryOperand(64)); inst.ZeroingMasking = true; inst.OpMask = Register.K7; inst.IsBroadcast = true; TestAssembler(c => c.vunpcklps(xmm2.k7.z, xmm6, __dword_bcst[rax]), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vcvttss2si_r64_xmmm32_sae, rax, xmm1); inst.SuppressAllExceptions = true; TestAssembler(c => c.vcvttss2si(rax, xmm1.sae), inst, LocalOpCodeFlags.PreferEvex); } { var inst = Instruction.Create(Code.EVEX_Vaddpd_zmm_k1z_zmm_zmmm512b64_er, zmm1, zmm2, zmm3); inst.OpMask = Register.K1; inst.RoundingControl = RoundingControl.RoundDown; TestAssembler(c => c.vaddpd(zmm1.k1, zmm2, zmm3.rd_sae), inst); } { var inst = Instruction.Create(Code.EVEX_Vaddpd_zmm_k1z_zmm_zmmm512b64_er, zmm1, zmm2, zmm3); inst.OpMask = Register.K1; inst.ZeroingMasking = true; inst.RoundingControl = RoundingControl.RoundUp; TestAssembler(c => c.vaddpd(zmm1.k1.z, zmm2, zmm3.ru_sae), inst); } { var inst = Instruction.Create(Code.EVEX_Vaddpd_zmm_k1z_zmm_zmmm512b64_er, zmm1, zmm2, zmm3); inst.OpMask = Register.K2; inst.RoundingControl = RoundingControl.RoundToNearest; TestAssembler(c => c.vaddpd(zmm1.k2, zmm2, zmm3.rn_sae), inst); } { var inst = Instruction.Create(Code.EVEX_Vaddpd_zmm_k1z_zmm_zmmm512b64_er, zmm1, zmm2, zmm3); inst.OpMask = Register.K3; inst.ZeroingMasking = true; inst.RoundingControl = RoundingControl.RoundTowardZero; TestAssembler(c => c.vaddpd(zmm1.k3.z, zmm2, zmm3.rz_sae), inst); } } #endif } } #endif
using System; using System.Collections.Generic; namespace BTDB.KVDBLayer.BTree { class BTreeLeaf : IBTreeLeafNode, IBTreeNode { internal readonly long TransactionId; BTreeLeafMember[] _keyValues; internal const int MaxMembers = 30; BTreeLeaf(long transactionId, int length) { TransactionId = transactionId; _keyValues = new BTreeLeafMember[length]; } internal BTreeLeaf(long transactionId, BTreeLeafMember[] newKeyValues) { TransactionId = transactionId; _keyValues = newKeyValues; } internal static IBTreeNode CreateFirst(ref CreateOrUpdateCtx ctx) { var result = new BTreeLeaf(ctx.TransactionId, 1); result._keyValues[0] = NewMemberFromCtx(ref ctx); return result; } int Find(in ReadOnlySpan<byte> key) { var left = 0; var right = _keyValues.Length; while (left < right) { var middle = (left + right) / 2; var currentKey = _keyValues[middle].Key; var result = key.SequenceCompareTo(currentKey); if (result == 0) { return middle * 2 + 1; } if (result < 0) { right = middle; } else { left = middle + 1; } } return left * 2; } public void CreateOrUpdate(ref CreateOrUpdateCtx ctx) { var index = Find(ctx.Key); if ((index & 1) == 1) { index = (int)((uint)index / 2); ctx.Created = false; ctx.KeyIndex = index; var m = _keyValues[index]; m.ValueFileId = ctx.ValueFileId; m.ValueOfs = ctx.ValueOfs; m.ValueSize = ctx.ValueSize; var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeaf(ctx.TransactionId, _keyValues.Length); Array.Copy(_keyValues, leaf._keyValues, _keyValues.Length); ctx.Node1 = leaf; ctx.Update = true; } leaf._keyValues[index] = m; ctx.Stack!.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } index = (int)((uint)index / 2); ctx.Created = true; ctx.KeyIndex = index; if (_keyValues.Length < MaxMembers) { var newKeyValues = new BTreeLeafMember[_keyValues.Length + 1]; Array.Copy(_keyValues, 0, newKeyValues, 0, index); newKeyValues[index] = NewMemberFromCtx(ref ctx); Array.Copy(_keyValues, index, newKeyValues, index + 1, _keyValues.Length - index); var leaf = this; if (ctx.TransactionId != TransactionId) { leaf = new BTreeLeaf(ctx.TransactionId, newKeyValues); ctx.Node1 = leaf; ctx.Update = true; } else { _keyValues = newKeyValues; } ctx.Stack!.Add(new NodeIdxPair { Node = leaf, Idx = index }); return; } ctx.Split = true; var keyCountLeft = (_keyValues.Length + 1) / 2; var keyCountRight = _keyValues.Length + 1 - keyCountLeft; var leftNode = new BTreeLeaf(ctx.TransactionId, keyCountLeft); var rightNode = new BTreeLeaf(ctx.TransactionId, keyCountRight); ctx.Node1 = leftNode; ctx.Node2 = rightNode; if (index < keyCountLeft) { Array.Copy(_keyValues, 0, leftNode._keyValues, 0, index); leftNode._keyValues[index] = NewMemberFromCtx(ref ctx); Array.Copy(_keyValues, index, leftNode._keyValues, index + 1, keyCountLeft - index - 1); Array.Copy(_keyValues, keyCountLeft - 1, rightNode._keyValues, 0, keyCountRight); ctx.Stack!.Add(new NodeIdxPair { Node = leftNode, Idx = index }); ctx.SplitInRight = false; } else { Array.Copy(_keyValues, 0, leftNode._keyValues, 0, keyCountLeft); Array.Copy(_keyValues, keyCountLeft, rightNode._keyValues, 0, index - keyCountLeft); rightNode._keyValues[index - keyCountLeft] = NewMemberFromCtx(ref ctx); Array.Copy(_keyValues, index, rightNode._keyValues, index - keyCountLeft + 1, keyCountLeft + keyCountRight - 1 - index); ctx.Stack!.Add(new NodeIdxPair { Node = rightNode, Idx = index - keyCountLeft }); ctx.SplitInRight = true; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key) { var idx = Find(key); FindResult result; if ((idx & 1) == 1) { result = FindResult.Exact; idx = (int)((uint)idx / 2); } else { result = FindResult.Previous; idx = (int)((uint)idx / 2) - 1; } stack.Add(new NodeIdxPair { Node = this, Idx = idx }); keyIndex = idx; return result; } static BTreeLeafMember NewMemberFromCtx(ref CreateOrUpdateCtx ctx) { return new BTreeLeafMember { Key = ctx.Key.ToArray(), ValueFileId = ctx.ValueFileId, ValueOfs = ctx.ValueOfs, ValueSize = ctx.ValueSize }; } public long CalcKeyCount() { return _keyValues.Length; } public byte[] GetLeftMostKey() { return _keyValues[0].Key; } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { stack.Add(new NodeIdxPair { Node = this, Idx = (int)keyIndex }); } public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix) { var left = 0; var right = _keyValues.Length - 1; byte[] currentKey; int result; while (left < right) { var middle = (left + right) / 2; currentKey = _keyValues[middle].Key; result = prefix.SequenceCompareTo(currentKey.AsSpan(0, Math.Min(currentKey.Length, prefix.Length))); if (result < 0) { right = middle; } else { left = middle + 1; } } currentKey = _keyValues[left].Key; result = prefix.SequenceCompareTo(currentKey.AsSpan(0, Math.Min(currentKey.Length, prefix.Length))); if (result < 0) left--; return left; } public bool NextIdxValid(int idx) { return idx + 1 < _keyValues.Length; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { // Nothing to do } public void FillStackByRightMost(List<NodeIdxPair> stack, int i) { // Nothing to do } public int GetLastChildrenIdx() { return _keyValues.Length - 1; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { var newKeyValues = new BTreeLeafMember[_keyValues.Length + firstKeyIndex - lastKeyIndex - 1]; Array.Copy(_keyValues, 0, newKeyValues, 0, (int)firstKeyIndex); Array.Copy(_keyValues, (int)lastKeyIndex + 1, newKeyValues, (int)firstKeyIndex, newKeyValues.Length - (int)firstKeyIndex); if (TransactionId == transactionId) { _keyValues = newKeyValues; return this; } return new BTreeLeaf(transactionId, newKeyValues); } public IBTreeNode EraseOne(long transactionId, long keyIndex) { var newKeyValues = new BTreeLeafMember[_keyValues.Length - 1]; Array.Copy(_keyValues, 0, newKeyValues, 0, (int)keyIndex); Array.Copy(_keyValues, (int)keyIndex + 1, newKeyValues, (int)keyIndex, newKeyValues.Length - (int)keyIndex); if (TransactionId == transactionId) { _keyValues = newKeyValues; return this; } return new BTreeLeaf(transactionId, newKeyValues); } public void Iterate(ValuesIterateAction action) { var kv = _keyValues; foreach (var member in kv) { if (member.ValueFileId == 0) continue; action(member.ValueFileId, member.ValueOfs, member.ValueSize); } } public IBTreeNode ReplaceValues(ReplaceValuesCtx ctx) { var result = this; var keyValues = _keyValues; var map = ctx._newPositionMap; for (var i = 0; i < keyValues.Length; i++) { ref var ii = ref keyValues[i]; if (map.TryGetValue(((ulong)ii.ValueFileId << 32) | ii.ValueOfs, out var newOffset)) { if (result.TransactionId != ctx._transactionId) { var newKeyValues = new BTreeLeafMember[keyValues.Length]; Array.Copy(keyValues, newKeyValues, newKeyValues.Length); result = new BTreeLeaf(ctx._transactionId, newKeyValues); keyValues = newKeyValues; } keyValues[i].ValueFileId = (uint)(newOffset >> 32); keyValues[i].ValueOfs = (uint)newOffset; } } return result; } public ReadOnlySpan<byte> GetKey(int idx) { return _keyValues[idx].Key; } public BTreeValue GetMemberValue(int idx) { var kv = _keyValues[idx]; return new BTreeValue { ValueFileId = kv.ValueFileId, ValueOfs = kv.ValueOfs, ValueSize = kv.ValueSize }; } public void SetMemberValue(int idx, in BTreeValue value) { ref var kv = ref _keyValues[idx]; kv.ValueFileId = value.ValueFileId; kv.ValueOfs = value.ValueOfs; kv.ValueSize = value.ValueSize; } } }
// InflaterInputStream.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. // HISTORY // 11-08-2009 GeoffHart T9121 Added Multi-member gzip support using System; using System.IO; #if !NETCF_1_0 && !UNITY_WINRT using System.Security.Cryptography; #endif namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// An input buffer customised for use by <see cref="InflaterInputStream"/> /// </summary> /// <remarks> /// The buffer supports decryption of incoming data. /// </remarks> public class InflaterInputBuffer { #region Constructors /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> with a default buffer size /// </summary> /// <param name="stream">The stream to buffer.</param> public InflaterInputBuffer(Stream stream) : this(stream , 4096) { } /// <summary> /// Initialise a new instance of <see cref="InflaterInputBuffer"/> /// </summary> /// <param name="stream">The stream to buffer.</param> /// <param name="bufferSize">The size to use for the buffer</param> /// <remarks>A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB.</remarks> public InflaterInputBuffer(Stream stream, int bufferSize) { inputStream = stream; if ( bufferSize < 1024 ) { bufferSize = 1024; } rawData = new byte[bufferSize]; clearText = rawData; } #endregion /// <summary> /// Get the length of bytes bytes in the <see cref="RawData"/> /// </summary> public int RawLength { get { return rawLength; } } /// <summary> /// Get the contents of the raw data buffer. /// </summary> /// <remarks>This may contain encrypted data.</remarks> public byte[] RawData { get { return rawData; } } /// <summary> /// Get the number of useable bytes in <see cref="ClearText"/> /// </summary> public int ClearTextLength { get { return clearTextLength; } } /// <summary> /// Get the contents of the clear text buffer. /// </summary> public byte[] ClearText { get { return clearText; } } /// <summary> /// Get/set the number of bytes available /// </summary> public int Available { get { return available; } set { available = value; } } /// <summary> /// Call <see cref="Inflater.SetInput(byte[], int, int)"/> passing the current clear text buffer contents. /// </summary> /// <param name="inflater">The inflater to set input for.</param> public void SetInflaterInput(Inflater inflater) { if ( available > 0 ) { inflater.SetInput(clearText, clearTextLength - available, available); available = 0; } } /// <summary> /// Fill the buffer from the underlying input stream. /// </summary> public void Fill() { rawLength = 0; int toRead = rawData.Length; while (toRead > 0) { int count = inputStream.Read(rawData, rawLength, toRead); if ( count <= 0 ) { break; } rawLength += count; toRead -= count; } #if !NETCF_1_0 && !UNITY_WINRT if ( cryptoTransform != null ) { clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); } else #endif { clearTextLength = rawLength; } available = clearTextLength; } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="buffer">The buffer to fill</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] buffer) { return ReadRawBuffer(buffer, 0, buffer.Length); } /// <summary> /// Read a buffer directly from the input stream /// </summary> /// <param name="outBuffer">The buffer to read into</param> /// <param name="offset">The offset to start reading data into.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes read.</returns> public int ReadRawBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read clear text data from the input stream. /// </summary> /// <param name="outBuffer">The buffer to add data to.</param> /// <param name="offset">The offset to start adding data at.</param> /// <param name="length">The number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) { if ( length < 0 ) { throw new ArgumentOutOfRangeException("length"); } int currentOffset = offset; int currentLength = length; while ( currentLength > 0 ) { if ( available <= 0 ) { Fill(); if (available <= 0) { return 0; } } int toCopy = Math.Min(currentLength, available); Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); currentOffset += toCopy; currentLength -= toCopy; available -= toCopy; } return length; } /// <summary> /// Read a <see cref="byte"/> from the input stream. /// </summary> /// <returns>Returns the byte read.</returns> public int ReadLeByte() { if (available <= 0) { Fill(); if (available <= 0) { throw new ZipException("EOF in header"); } } byte result = rawData[rawLength - available]; available -= 1; return result; } /// <summary> /// Read an <see cref="short"/> in little endian byte order. /// </summary> /// <returns>The short value read case to an int.</returns> public int ReadLeShort() { return ReadLeByte() | (ReadLeByte() << 8); } /// <summary> /// Read an <see cref="int"/> in little endian byte order. /// </summary> /// <returns>The int value read.</returns> public int ReadLeInt() { return ReadLeShort() | (ReadLeShort() << 16); } /// <summary> /// Read a <see cref="long"/> in little endian byte order. /// </summary> /// <returns>The long value read.</returns> public long ReadLeLong() { return (uint)ReadLeInt() | ((long)ReadLeInt() << 32); } #if !NETCF_1_0 && !UNITY_WINRT /// <summary> /// Get/set the <see cref="ICryptoTransform"/> to apply to any data. /// </summary> /// <remarks>Set this value to null to have no transform applied.</remarks> public ICryptoTransform CryptoTransform { set { cryptoTransform = value; if ( cryptoTransform != null ) { if ( rawData == clearText ) { if ( internalClearText == null ) { internalClearText = new byte[rawData.Length]; } clearText = internalClearText; } clearTextLength = rawLength; if ( available > 0 ) { cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); } } else { clearText = rawData; clearTextLength = rawLength; } } } #endif #region Instance Fields int rawLength; byte[] rawData; int clearTextLength; byte[] clearText; #if !NETCF_1_0 && !UNITY_WINRT byte[] internalClearText; #endif int available; #if !NETCF_1_0 && !UNITY_WINRT ICryptoTransform cryptoTransform; #endif Stream inputStream; #endregion } /// <summary> /// This filter stream is used to decompress data compressed using the "deflate" /// format. The "deflate" format is described in RFC 1951. /// /// This stream may form the basis for other decompression filters, such /// as the <see cref="ICSharpCode.SharpZipLib.GZip.GZipInputStream">GZipInputStream</see>. /// /// Author of the original java version : John Leuner. /// </summary> public class InflaterInputStream : Stream { #region Constructors /// <summary> /// Create an InflaterInputStream with the default decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> public InflaterInputStream(Stream baseInputStream) : this(baseInputStream, new Inflater(), 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and a default buffer size of 4KB. /// </summary> /// <param name = "baseInputStream"> /// The source of input data /// </param> /// <param name = "inf"> /// The decompressor used to decompress data read from baseInputStream /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inf) : this(baseInputStream, inf, 4096) { } /// <summary> /// Create an InflaterInputStream with the specified decompressor /// and the specified buffer size. /// </summary> /// <param name = "baseInputStream"> /// The InputStream to read bytes from /// </param> /// <param name = "inflater"> /// The decompressor to use /// </param> /// <param name = "bufferSize"> /// Size of the buffer to use /// </param> public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) { if (baseInputStream == null) { throw new ArgumentNullException("baseInputStream"); } if (inflater == null) { throw new ArgumentNullException("inflater"); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } this.baseInputStream = baseInputStream; this.inf = inflater; inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); } #endregion /// <summary> /// Get/set flag indicating ownership of underlying stream. /// When the flag is true <see cref="Close"/> will close the underlying stream also. /// </summary> /// <remarks> /// The default value is true. /// </remarks> public bool IsStreamOwner { get { return isStreamOwner; } set { isStreamOwner = value; } } /// <summary> /// Skip specified number of bytes of uncompressed data /// </summary> /// <param name ="count"> /// Number of bytes to skip /// </param> /// <returns> /// The number of bytes skipped, zero if the end of /// stream has been reached /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="count">The number of bytes</paramref> to skip is less than or equal to zero. /// </exception> public long Skip(long count) { if (count <= 0) { throw new ArgumentOutOfRangeException("count"); } // v0.80 Skip by seeking if underlying stream supports it... if (baseInputStream.CanSeek) { baseInputStream.Seek(count, SeekOrigin.Current); return count; } else { int length = 2048; if (count < length) { length = (int) count; } byte[] tmp = new byte[length]; int readCount = 1; long toSkip = count; while ((toSkip > 0) && (readCount > 0) ) { if (toSkip < length) { length = (int)toSkip; } readCount = baseInputStream.Read(tmp, 0, length); toSkip -= readCount; } return count - toSkip; } } /// <summary> /// Clear any cryptographic state. /// </summary> protected void StopDecrypting() { #if !NETCF_1_0 && !UNITY_WINRT inputBuffer.CryptoTransform = null; #endif } /// <summary> /// Returns 0 once the end of the stream (EOF) has been reached. /// Otherwise returns 1. /// </summary> public virtual int Available { get { return inf.IsFinished ? 0 : 1; } } /// <summary> /// Fills the buffer with more data to decompress. /// </summary> /// <exception cref="SharpZipBaseException"> /// Stream ends early /// </exception> protected void Fill() { // Protect against redundant calls if (inputBuffer.Available <= 0) { inputBuffer.Fill(); if (inputBuffer.Available <= 0) { throw new SharpZipBaseException("Unexpected EOF"); } } inputBuffer.SetInflaterInput(inf); } #region Stream Overrides /// <summary> /// Gets a value indicating whether the current stream supports reading /// </summary> public override bool CanRead { get { return baseInputStream.CanRead; } } /// <summary> /// Gets a value of false indicating seeking is not supported for this stream. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Gets a value of false indicating that this stream is not writeable. /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// A value representing the length of the stream in bytes. /// </summary> public override long Length { get { return inputBuffer.RawLength; } } /// <summary> /// The current position within the stream. /// Throws a NotSupportedException when attempting to set the position /// </summary> /// <exception cref="NotSupportedException">Attempting to set the position</exception> public override long Position { get { return baseInputStream.Position; } set { throw new NotSupportedException("InflaterInputStream Position not supported"); } } /// <summary> /// Flushes the baseInputStream /// </summary> public override void Flush() { baseInputStream.Flush(); } /// <summary> /// Sets the position within the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="offset">The relative offset to seek to.</param> /// <param name="origin">The <see cref="SeekOrigin"/> defining where to seek from.</param> /// <returns>The new position in the stream.</returns> /// <exception cref="NotSupportedException">Any access</exception> public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException("Seek not supported"); } /// <summary> /// Set the length of the current stream /// Always throws a NotSupportedException /// </summary> /// <param name="value">The new length value for the stream.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void SetLength(long value) { throw new NotSupportedException("InflaterInputStream SetLength not supported"); } /// <summary> /// Writes a sequence of bytes to stream and advances the current position /// This method always throws a NotSupportedException /// </summary> /// <param name="buffer">Thew buffer containing data to write.</param> /// <param name="offset">The offset of the first byte to write.</param> /// <param name="count">The number of bytes to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException("InflaterInputStream Write not supported"); } /// <summary> /// Writes one byte to the current stream and advances the current position /// Always throws a NotSupportedException /// </summary> /// <param name="value">The byte to write.</param> /// <exception cref="NotSupportedException">Any access</exception> public override void WriteByte(byte value) { throw new NotSupportedException("InflaterInputStream WriteByte not supported"); } /// <summary> /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. /// </summary> /// <param name="buffer">The buffer to write data from</param> /// <param name="offset">Offset of first byte to write</param> /// <param name="count">The maximum number of bytes to write</param> /// <param name="callback">The method to be called when the asynchronous write operation is completed</param> /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests</param> /// <returns>An <see cref="System.IAsyncResult">IAsyncResult</see> that references the asynchronous write</returns> /// <exception cref="NotSupportedException">Any access</exception> #if UNITY_METRO && !UNITY_EDITOR public IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) #else public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) #endif { throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); } /// <summary> /// Closes the input stream. When <see cref="IsStreamOwner"></see> /// is true the underlying stream is also closed. /// </summary> #if UNITY_METRO && !UNITY_EDITOR public void Close() #else public override void Close() #endif { if ( !isClosed ) { isClosed = true; if ( isStreamOwner ) { baseInputStream.Dispose(); } } } /// <summary> /// Reads decompressed data into the provided buffer byte array /// </summary> /// <param name ="buffer"> /// The array to read and decompress data into /// </param> /// <param name ="offset"> /// The offset indicating where the data should be placed /// </param> /// <param name ="count"> /// The number of bytes to decompress /// </param> /// <returns>The number of bytes read. Zero signals the end of stream</returns> /// <exception cref="SharpZipBaseException"> /// Inflater needs a dictionary /// </exception> public override int Read(byte[] buffer, int offset, int count) { if (inf.IsNeedingDictionary) { throw new SharpZipBaseException("Need a dictionary"); } int remainingBytes = count; while (true) { int bytesRead = inf.Inflate(buffer, offset, remainingBytes); offset += bytesRead; remainingBytes -= bytesRead; if (remainingBytes == 0 || inf.IsFinished) { break; } if ( inf.IsNeedingInput ) { Fill(); } else if ( bytesRead == 0 ) { throw new ZipException("Dont know what to do"); } } return count - remainingBytes; } #endregion #region Instance Fields /// <summary> /// Decompressor for this stream /// </summary> protected Inflater inf; /// <summary> /// <see cref="InflaterInputBuffer">Input buffer</see> for this stream. /// </summary> protected InflaterInputBuffer inputBuffer; /// <summary> /// Base stream the inflater reads from. /// </summary> private Stream baseInputStream; /// <summary> /// The compressed size /// </summary> protected long csize; /// <summary> /// Flag indicating wether this instance has been closed or not. /// </summary> bool isClosed; /// <summary> /// Flag indicating wether this instance is designated the stream owner. /// When closing if this flag is true the underlying stream is closed. /// </summary> bool isStreamOwner = true; #endregion } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.IO; using System.Security; namespace Alphaleonis.Win32.Filesystem { partial class FileInfo { #region CopyTo #region .NET /// <summary>Copies an existing file to a new file, disallowing the overwriting of an existing file.</summary> /// <returns>A new <see cref="FileInfo"/> instance with a fully qualified path.</returns> /// <remarks> /// <para>Use this method to prevent overwriting of an existing file by default.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, CopyOptions.FailIfExists, null, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>Copies an existing file to a new file, allowing the overwriting of an existing file.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="overwrite"/> is <see langword="true"/>.</para> /// <para>If the file exists and <paramref name="overwrite"/> is <see langword="false"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="overwrite"><see langword="true"/> to allow an existing file to be overwritten; otherwise, <see langword="false"/>.</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, bool overwrite) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } #endregion // .NET #region AlphaFS /// <summary>[AlphaFS] Copies an existing file to a new file, disallowing the overwriting of an existing file.</summary> /// <returns>A new <see cref="FileInfo"/> instance with a fully qualified path.</returns> /// <remarks> /// <para>Use this method to prevent overwriting of an existing file by default.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, CopyOptions.FailIfExists, null, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="overwrite"/> is <see langword="true"/>.</para> /// <para>If the file exists and <paramref name="overwrite"/> is <see langword="false"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="overwrite"><see langword="true"/> to allow an existing file to be overwritten; otherwise, <see langword="false"/>.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, bool overwrite, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, overwrite ? CopyOptions.None : CopyOptions.FailIfExists, null, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, copyOptions, null, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="preserveDates"><see langword="true"/> if original Timestamps must be preserved, <see langword="false"/> otherwise.</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified.</summary> /// <returns> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="preserveDates"><see langword="true"/> if original Timestamps must be preserved, <see langword="false"/> otherwise.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified. /// <para>and the possibility of notifying the application of its progress through a callback function.</para> /// </summary> /// <returns> /// <para>Returns a <see cref="CopyMoveResult"/> class with the status of the Copy action.</para> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, false, copyOptions, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified.</summary> /// <returns> /// <para>Returns a <see cref="CopyMoveResult"/> class with the status of the Copy action.</para> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, false, copyOptions, null, progressHandler, userProgressData, out destinationPathLp, pathFormat); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified. /// <para>and the possibility of notifying the application of its progress through a callback function.</para> /// </summary> /// <returns> /// <para>Returns a <see cref="CopyMoveResult"/> class with the status of the Copy action.</para> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="preserveDates"><see langword="true"/> if original Timestamps must be preserved, <see langword="false"/> otherwise.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } /// <summary>[AlphaFS] Copies an existing file to a new file, allowing the overwriting of an existing file, <see cref="CopyOptions"/> can be specified. /// <para>and the possibility of notifying the application of its progress through a callback function.</para> /// </summary> /// <returns> /// <para>Returns a <see cref="CopyMoveResult"/> class with the status of the Copy action.</para> /// <para>Returns a new file, or an overwrite of an existing file if <paramref name="copyOptions"/> is not <see cref="CopyOptions.FailIfExists"/>.</para> /// <para>If the file exists and <paramref name="copyOptions"/> contains <see cref="CopyOptions.FailIfExists"/>, an <see cref="IOException"/> is thrown.</para> /// </returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The name of the new file to copy to.</param> /// <param name="copyOptions"><see cref="CopyOptions"/> that specify how the file is to be copied.</param> /// <param name="preserveDates"><see langword="true"/> if original Timestamps must be preserved, <see langword="false"/> otherwise.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the file has been copied. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public CopyMoveResult CopyTo(string destinationPath, CopyOptions copyOptions, bool preserveDates, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, preserveDates, copyOptions, null, progressHandler, userProgressData, out destinationPathLp, pathFormat); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } #endregion // AlphaFS #endregion // CopyTo #region MoveTo #region .NET /// <summary>Moves a specified file to a new location, providing the option to specify a new file name.</summary> /// <remarks> /// <para>Use this method to prevent overwriting of an existing file by default.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> [SecurityCritical] public void MoveTo(string destinationPath) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, MoveOptions.CopyAllowed, null, null, out destinationPathLp, PathFormat.RelativePath); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); } #endregion // .NET #region AlphaFS /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name.</summary> /// <returns><para>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved,</para></returns> /// <remarks> /// <para>Use this method to prevent overwriting of an existing file by default.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable /// behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo MoveTo(string destinationPath, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, MoveOptions.CopyAllowed, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary> /// <returns><para>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved,</para></returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable /// behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <see langword="null"/>.</param> [SecurityCritical] public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, PathFormat.RelativePath); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary> /// <returns><para>Returns a new <see cref="FileInfo"/> instance with a fully qualified path when successfully moved,</para></returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable /// behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <see langword="null"/>.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public FileInfo MoveTo(string destinationPath, MoveOptions moveOptions, PathFormat pathFormat) { string destinationPathLp; CopyToMoveToCore(destinationPath, false, null, moveOptions, null, null, out destinationPathLp, pathFormat); return new FileInfo(Transaction, destinationPathLp, PathFormat.LongFullPath); } /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified, /// <para>and the possibility of notifying the application of its progress through a callback function.</para> /// </summary> /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <see langword="null"/>.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, PathFormat.RelativePath); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } /// <summary>[AlphaFS] Moves a specified file to a new location, providing the option to specify a new file name, <see cref="MoveOptions"/> can be specified.</summary> /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Move action.</returns> /// <remarks> /// <para>Use this method to allow or prevent overwriting of an existing file.</para> /// <para>This method works across disk volumes.</para> /// <para>For example, the file c:\MyFile.txt can be moved to d:\public and renamed NewFile.txt.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="FileNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> /// <param name="destinationPath">The path to move the file to, which can specify a different file name.</param> /// <param name="moveOptions"><see cref="MoveOptions"/> that specify how the directory is to be moved. This parameter can be <see langword="null"/>.</param> /// <param name="progressHandler">A callback function that is called each time another portion of the directory has been moved. This parameter can be <see langword="null"/>.</param> /// <param name="userProgressData">The argument to be passed to the callback function. This parameter can be <see langword="null"/>.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> [SecurityCritical] public CopyMoveResult MoveTo(string destinationPath, MoveOptions moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, PathFormat pathFormat) { string destinationPathLp; CopyMoveResult cmr = CopyToMoveToCore(destinationPath, false, null, moveOptions, progressHandler, userProgressData, out destinationPathLp, pathFormat); CopyToMoveToCoreRefresh(destinationPath, destinationPathLp); return cmr; } #endregion // AlphaFS #endregion // MoveTo #region Internal Methods /// <summary>Copy/move an existing file to a new file, allowing the overwriting of an existing file.</summary> /// <returns>A <see cref="CopyMoveResult"/> class with the status of the Copy or Move action.</returns> /// <remarks> /// <para>Option <see cref="CopyOptions.NoBuffering"/> is recommended for very large file transfers.</para> /// <para>Whenever possible, avoid using short file names (such as XXXXXX~1.XXX) with this method.</para> /// <para>If two files have equivalent short file names then this method may fail and raise an exception and/or result in undesirable behavior.</para> /// </remarks> /// <param name="destinationPath"><para>A full path string to the destination directory</para></param> /// <param name="preserveDates"><see langword="true"/> if original Timestamps must be preserved, <see langword="false"/> otherwise.</param> /// <param name="copyOptions"><para>This parameter can be <see langword="null"/>. Use <see cref="CopyOptions"/> to specify how the file is to be copied.</para></param> /// <param name="moveOptions"><para>This parameter can be <see langword="null"/>. Use <see cref="MoveOptions"/> that specify how the file is to be moved.</para></param> /// <param name="progressHandler"><para>This parameter can be <see langword="null"/>. A callback function that is called each time another portion of the file has been copied.</para></param> /// <param name="userProgressData"><para>This parameter can be <see langword="null"/>. The argument to be passed to the callback function.</para></param> /// <param name="longFullPath">[out] Returns the retrieved long full path.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <exception cref="ArgumentException"/> /// <exception cref="ArgumentNullException"/> /// <exception cref="DirectoryNotFoundException"/> /// <exception cref="IOException"/> /// <exception cref="NotSupportedException"/> /// <exception cref="UnauthorizedAccessException"/> [SecurityCritical] private CopyMoveResult CopyToMoveToCore(string destinationPath, bool preserveDates, CopyOptions? copyOptions, MoveOptions? moveOptions, CopyMoveProgressRoutine progressHandler, object userProgressData, out string longFullPath, PathFormat pathFormat) { string destinationPathLp = Path.GetExtendedLengthPathCore(Transaction, destinationPath, pathFormat, GetFullPathOptions.TrimEnd | GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); longFullPath = destinationPathLp; // Returns false when CopyMoveProgressResult is PROGRESS_CANCEL or PROGRESS_STOP. return File.CopyMoveCore(false, Transaction, LongFullName, destinationPathLp, preserveDates, copyOptions, moveOptions, progressHandler, userProgressData, PathFormat.LongFullPath); } private void CopyToMoveToCoreRefresh(string destinationPath, string destinationPathLp) { LongFullName = destinationPathLp; FullPath = Path.GetRegularPathCore(destinationPathLp, GetFullPathOptions.None); OriginalPath = destinationPath; DisplayPath = Path.GetRegularPathCore(OriginalPath, GetFullPathOptions.None); _name = Path.GetFileName(destinationPathLp, true); // Flush any cached information about the file. Reset(); } #endregion // Internal Methods } }
using OpenKh.Common; using OpenKh.Imaging; using OpenKh.Kh2; using OpenKh.Kh2.Messages; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using YamlDotNet.Serialization; namespace OpenKh.Patcher { public class PatcherProcessor { public class Context { public Metadata Metadata { get; set; } public string OriginalAssetPath { get; } public string SourceModAssetPath { get; set; } public string DestinationPath { get; set; } public Context( Metadata metadata, string originalAssetPath, string sourceModAssetPath, string destinationPath) { Metadata = metadata; OriginalAssetPath = originalAssetPath; SourceModAssetPath = sourceModAssetPath; DestinationPath = destinationPath; } public string GetOriginalAssetPath(string path) => Path.Combine(OriginalAssetPath, path); public string GetSourceModAssetPath(string path) => Path.Combine(SourceModAssetPath, path); public string GetDestinationPath(string path) => Path.Combine(DestinationPath, path); public void EnsureDirectoryExists(string fileName) => Directory.CreateDirectory(Path.GetDirectoryName(fileName)); public void CopyOriginalFile(string fileName) { var dstFile = GetDestinationPath(fileName); EnsureDirectoryExists(dstFile); if (!File.Exists(dstFile)) { var originalFile = GetOriginalAssetPath(fileName); if (File.Exists(originalFile)) File.Copy(originalFile, dstFile,true); } } } public void Patch(string originalAssets, string outputDir, string modFilePath) { var metadata = File.OpenRead(modFilePath).Using(Metadata.Read); var modBasePath = Path.GetDirectoryName(modFilePath); Patch(originalAssets, outputDir, metadata, modBasePath); } public void Patch(string originalAssets, string outputDir, Metadata metadata, string modBasePath) { var context = new Context(metadata, originalAssets, modBasePath, outputDir); try { if (metadata.Assets == null) throw new Exception("No assets found."); metadata.Assets.AsParallel().ForAll(assetFile => { var names = new List<string>(); names.Add(assetFile.Name); if (assetFile.Multi != null) names.AddRange(assetFile.Multi.Select(x => x.Name).Where(x => !string.IsNullOrEmpty(x))); foreach (var name in names) { if (assetFile.Required && !File.Exists(context.GetOriginalAssetPath(name))) continue; context.CopyOriginalFile(name); var dstFile = context.GetDestinationPath(name); using var stream = File.Open(dstFile, FileMode.OpenOrCreate, FileAccess.ReadWrite); PatchFile(context, assetFile, stream); } }); } catch (Exception ex) { Log.Err($"Patcher failed: {ex.Message}"); throw new PatcherException(metadata, ex); } } private static void PatchFile(Context context, AssetFile assetFile, Stream stream) { if (assetFile == null) throw new Exception("Asset file is null."); switch (assetFile.Method) { case "copy": CopyFile(context, assetFile, stream); break; case "bar": case "binarc": PatchBinarc(context, assetFile, stream); break; case "imd": case "imgd": CreateImageImd(context, assetFile.Source[0]).Write(stream); break; case "imz": case "imgz": PatchImageImz(context, assetFile, stream); break; case "fac": Imgd.WriteAsFac(stream, assetFile.Source.Select(x => CreateImageImd(context, x))); break; case "kh2msg": PatchKh2Msg(context, assetFile.Source, stream); break; case "areadatascript": PatchAreaDataScript(context, assetFile.Source, stream); break; case "spawnpoint": PatchSpawnPoint(context, assetFile, stream); break; case "listpatch": PatchList(context, assetFile.Source, stream); break; default: Log.Warn($"Method '{assetFile.Method}' not recognized for '{assetFile.Name}'. Falling back to 'copy'"); CopyFile(context, assetFile, stream); break; } stream.SetLength(stream.Position); } private static void CopyFile(Context context, AssetFile assetFile, Stream stream) { if (assetFile.Source == null || assetFile.Source.Count == 0) throw new Exception($"File '{assetFile.Name}' does not contain any source"); string srcFile; if (assetFile.Source[0].Type == "internal") { srcFile = context.GetOriginalAssetPath(assetFile.Source[0].Name); } else { srcFile = context.GetSourceModAssetPath(assetFile.Source[0].Name); if (!File.Exists(srcFile)) throw new FileNotFoundException($"The mod does not contain the file {assetFile.Source[0].Name}", srcFile); } using var srcStream = File.OpenRead(srcFile); srcStream.CopyTo(stream); } private static void PatchBinarc(Context context, AssetFile assetFile, Stream stream) { var binarc = Bar.IsValid(stream) ? Bar.Read(stream) : new Bar() { Motionset = assetFile.MotionsetType }; foreach (var file in assetFile.Source) { if (!Enum.TryParse<Bar.EntryType>(file.Type, true, out var barEntryType)) throw new Exception($"BinArc type {file.Type} not recognized"); var entry = binarc.FirstOrDefault(x => x.Name == file.Name && x.Type == barEntryType); if (entry == null) { entry = new Bar.Entry { Name = file.Name, Type = barEntryType, Stream = new MemoryStream() }; binarc.Add(entry); } PatchFile(context, file, entry.Stream); } Bar.Write(stream.SetPosition(0), binarc); foreach (var entry in binarc) entry.Stream?.Dispose(); } private static Imgd CreateImageImd(Context context, AssetFile source) { var srcFile = context.GetSourceModAssetPath(source.Name); using var srcStream = File.OpenRead(srcFile); if (PngImage.IsValid(srcStream)) { var png = PngImage.Read(srcStream); return Imgd.Create(png.Size, png.PixelFormat, png.GetData(), png.GetClut(), source.IsSwizzled); } else if (Imgd.IsValid(srcStream)) return Imgd.Read(srcStream); throw new Exception($"Image source '{source.Name}' not recognized"); } private static void PatchImageImz(Context context, AssetFile assetFile, Stream stream) { var index = 0; var images = Imgz.IsValid(stream) ? Imgz.Read(stream).ToList() : new List<Imgd>(); foreach (var source in assetFile.Source) { if (source.Index > 0) index = source.Index; var imd = CreateImageImd(context, source); if (images.Count <= index) images.Add(imd); else images[index] = imd; index++; } Imgz.Write(stream.SetPosition(0), images); } private static void PatchKh2Msg(Context context, List<AssetFile> sources, Stream stream) { var msgs = Msg.IsValid(stream) ? Msg.Read(stream) : new List<Msg.Entry>(); foreach (var source in sources) { if (string.IsNullOrEmpty(source.Language)) throw new Exception($"No language specified in '{source.Name}'"); var content = File.ReadAllText(context.GetSourceModAssetPath(source.Name)); var patchedMsgs = new Deserializer().Deserialize<List<Dictionary<string, string>>>(content); foreach (var msg in patchedMsgs) { if (!msg.TryGetValue("id", out var strId)) throw new Exception($"Source '{source.Name}' contains a message without an ID"); if (!ushort.TryParse(strId, out var id)) { if (strId.Length > 2 && strId[1] == 'x') { if (!ushort.TryParse(strId.Substring(2), NumberStyles.HexNumber, null, out id)) throw new Exception($"Message ID '{strId} in '{source.Name}' must be between 0 and 65535"); } else throw new Exception($"Message ID '{strId} in '{source.Name}' must be between 0 and 65535"); } if (!msg.TryGetValue(source.Language, out var text)) continue; var encoder = source.Language switch { "jp" => Encoders.JapaneseSystem, "tr" => Encoders.TurkishSystem, _ => Encoders.InternationalSystem, }; var data = encoder.Encode(MsgSerializer.DeserializeText(text ?? string.Empty).ToList()); var originalMsg = msgs.FirstOrDefault(x => x.Id == id); if (originalMsg == null) msgs.Add(new Msg.Entry { Id = id, Data = data }); else originalMsg.Data = data; } } Msg.WriteOptimized(stream.SetPosition(0), msgs); } private static void PatchAreaDataScript(Context context, List<AssetFile> sources, Stream stream) { var scripts = Kh2.Ard.AreaDataScript.IsValid(stream) ? Kh2.Ard.AreaDataScript.Read(stream).ToDictionary(x => x.ProgramId, x => x) : new Dictionary<short, Kh2.Ard.AreaDataScript>(); foreach (var source in sources) { var programsInput = File.ReadAllText(context.GetSourceModAssetPath(source.Name)); foreach (var newScript in Kh2.Ard.AreaDataScript.Compile(programsInput)) scripts[newScript.ProgramId] = newScript; } Kh2.Ard.AreaDataScript.Write(stream.SetPosition(0), scripts.Values); } private static void PatchSpawnPoint(Context context, AssetFile assetFile, Stream stream) { if (assetFile.Source == null || assetFile.Source.Count == 0) throw new Exception($"File '{assetFile.Name}' does not contain any source"); var srcFile = context.GetSourceModAssetPath(assetFile.Source[0].Name); if (!File.Exists(srcFile)) throw new FileNotFoundException($"The mod does not contain the file {assetFile.Source[0].Name}", srcFile); var spawnPoint = Helpers.YamlDeserialize<List<Kh2.Ard.SpawnPoint>>(File.ReadAllText(srcFile)); Kh2.Ard.SpawnPoint.Write(stream.SetPosition(0), spawnPoint); } private static readonly Dictionary<string, byte> characterMap = new Dictionary<string, byte>(){ { "Sora", 1 }, { "Donald", 2 }, { "Goofy", 3 }, { "Mickey", 4 }, { "Auron", 5 }, { "PingMulan",6 }, { "Aladdin", 7 }, { "Sparrow", 8 }, { "Beast", 9 }, { "Jack", 10 }, { "Simba", 11 }, { "Tron", 12 }, { "Riku", 13 }, { "Roxas", 14}, {"Ping", 15} }; private static readonly IDeserializer deserializer = new DeserializerBuilder().IgnoreUnmatchedProperties().Build(); private static void PatchList(Context context, List<AssetFile> sources, Stream stream) { foreach (var source in sources) { string sourceText = File.ReadAllText(context.GetSourceModAssetPath(source.Name)); switch (source.Type) { case "trsr": var trsrList = Kh2.SystemData.Trsr.Read(stream).ToDictionary(x => x.Id, x => x); var moddedTrsr = deserializer.Deserialize<Dictionary<ushort, Kh2.SystemData.Trsr>>(sourceText); foreach (var treasure in moddedTrsr) { if (trsrList.ContainsKey(treasure.Key)) { if (treasure.Value.World == 0) { trsrList[treasure.Key].ItemId = treasure.Value.ItemId; } else { trsrList[treasure.Key] = treasure.Value; } } else { trsrList.Add(treasure.Key, treasure.Value); } } Kh2.SystemData.Trsr.Write(stream.SetPosition(0), trsrList.Values); break; case "item": var itemList = Kh2.SystemData.Item.Read(stream); var moddedItem = deserializer.Deserialize<Kh2.SystemData.Item>(sourceText); if (moddedItem.Items != null) { foreach (var item in moddedItem.Items) { var itemToUpdate = itemList.Items.FirstOrDefault(x => x.Id == item.Id); if (itemToUpdate != null) { itemList.Items[itemList.Items.IndexOf(itemToUpdate)] = item; } else { itemList.Items.Add(item); } } } if (moddedItem.Stats != null) { foreach (var item in moddedItem.Stats) { var itemToUpdate = itemList.Stats.FirstOrDefault(x => x.Id == item.Id); if (itemToUpdate != null) { itemList.Stats[itemList.Stats.IndexOf(itemToUpdate)] = item; } else { itemList.Stats.Add(item); } } } itemList.Write(stream.SetPosition(0)); break; case "fmlv": var formRaw = Kh2.Battle.Fmlv.Read(stream).ToList(); var formList = new Dictionary<Kh2.Battle.Fmlv.FormFm, List<Kh2.Battle.Fmlv>>(); foreach (var form in formRaw) { if (!formList.ContainsKey(form.FinalMixForm)) { formList.Add(form.FinalMixForm, new List<Kh2.Battle.Fmlv>()); } formList[form.FinalMixForm].Add(form); } var moddedForms = deserializer.Deserialize<Dictionary<Kh2.Battle.Fmlv.FormFm, List<FmlvDTO>>>(sourceText); foreach (var form in moddedForms) { foreach (var level in form.Value) { formList[form.Key][level.FormLevel - 1].Ability = (ushort)level.Ability; formList[form.Key][level.FormLevel - 1].Exp = level.Experience; formList[form.Key][level.FormLevel - 1].Unk1= level.GrowthAbilityLevel; } } Kh2.Battle.Fmlv.Write(stream.SetPosition(0), formList.Values.SelectMany(x=>x).ToList()); break; case "lvup": var levelList = Kh2.Battle.Lvup.Read(stream); var moddedLevels = deserializer.Deserialize<Dictionary<string, Dictionary<int, Kh2.Battle.Lvup.PlayableCharacter.Level>>> (sourceText); foreach (var character in moddedLevels) { foreach (var level in moddedLevels[character.Key]) { levelList.Characters[characterMap[character.Key] - 1].Levels[level.Key - 1] = moddedLevels[character.Key][level.Key]; } } levelList.Write(stream.SetPosition(0)); break; case "bons": var bonusRaw = Kh2.Battle.Bons.Read(stream); var bonusList = new Dictionary<byte, Dictionary<string, Kh2.Battle.Bons>>(); foreach (var bonus in bonusRaw) { if (!bonusList.ContainsKey(bonus.RewardId)) { bonusList.Add(bonus.RewardId, new Dictionary<string, Kh2.Battle.Bons>()); } var character = characterMap.First(x => x.Value == bonus.CharacterId).Key; if (!bonusList[bonus.RewardId].ContainsKey(character)) { bonusList[bonus.RewardId].Add(character, bonus); } } var moddedBonus = deserializer.Deserialize<Dictionary<byte, Dictionary<string, Kh2.Battle.Bons>>>(sourceText); foreach (var bonus in moddedBonus) { if (!bonusList.ContainsKey(bonus.Key)) { bonusList.Add(bonus.Key, new Dictionary<string, Kh2.Battle.Bons>()); } foreach (var character in moddedBonus[bonus.Key]) { if (!bonusList[bonus.Key].ContainsKey(character.Key)) { bonusList[bonus.Key].Add(character.Key, new Kh2.Battle.Bons()); } bonusList[bonus.Key][character.Key] = character.Value; } } Kh2.Battle.Bons.Write(stream.SetPosition(0), bonusList.Values.SelectMany(x => x.Values)); break; case "objentry": var objEntryList = Kh2.Objentry.Read(stream).ToDictionary(x => x.ObjectId, x=>x); var moddedObjEntry = deserializer.Deserialize<Dictionary<uint, Kh2.Objentry>>(sourceText); foreach (var objEntry in moddedObjEntry) { if (objEntryList.ContainsKey(objEntry.Key)) { objEntryList[objEntry.Key] = objEntry.Value; } else { objEntryList.Add(objEntry.Key, objEntry.Value); } } Kh2.Objentry.Write(stream.SetPosition(0), objEntryList.Values); break; case "plrp": var plrpList = Kh2.Battle.Plrp.Read(stream); var moddedPlrp = deserializer.Deserialize<List<Kh2.Battle.Plrp>>(sourceText); foreach (var plrp in moddedPlrp) { var oldPlrp = plrpList.First(x => x.Character == plrp.Character && x.Id == plrp.Id); plrpList[plrpList.IndexOf(oldPlrp)] = plrp; } Kh2.Battle.Plrp.Write(stream.SetPosition(0), plrpList); break; default: break; } } } } }
using System; using System.Threading; using Solenoid.Expressions.Parser.antlr.collections.impl; namespace Solenoid.Expressions.Parser.antlr.debug { public abstract class DebuggingCharScanner : CharScanner, DebuggingParser { private void InitBlock() { eventSupport = new ScannerEventSupport(this); } public virtual void setDebugMode(bool mode) { _notDebugMode = !mode; } private ScannerEventSupport eventSupport; private bool _notDebugMode = false; protected internal string[] ruleNames; protected internal string[] semPredNames; public DebuggingCharScanner(InputBuffer cb) : base(cb) { InitBlock(); } public DebuggingCharScanner(LexerSharedInputState state) : base(state) { InitBlock(); } public virtual void addMessageListener(MessageListener l) { eventSupport.addMessageListener(l); } public virtual void addNewLineListener(NewLineListener l) { eventSupport.addNewLineListener(l); } public virtual void addParserListener(ParserListener l) { eventSupport.addParserListener(l); } public virtual void addParserMatchListener(ParserMatchListener l) { eventSupport.addParserMatchListener(l); } public virtual void addParserTokenListener(ParserTokenListener l) { eventSupport.addParserTokenListener(l); } public virtual void addSemanticPredicateListener(SemanticPredicateListener l) { eventSupport.addSemanticPredicateListener(l); } public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l) { eventSupport.addSyntacticPredicateListener(l); } public virtual void addTraceListener(TraceListener l) { eventSupport.addTraceListener(l); } public override void consume() { var la_1 = - 99; try { la_1 = LA(1); } catch (CharStreamException) { } base.consume(); eventSupport.fireConsume(la_1); } protected internal virtual void fireEnterRule(int num, int data) { if (isDebugMode()) eventSupport.fireEnterRule(num, inputState.guessing, data); } protected internal virtual void fireExitRule(int num, int ttype) { if (isDebugMode()) eventSupport.fireExitRule(num, inputState.guessing, ttype); } protected internal virtual bool fireSemanticPredicateEvaluated(int type, int num, bool condition) { if (isDebugMode()) return eventSupport.fireSemanticPredicateEvaluated(type, num, condition, inputState.guessing); else return condition; } protected internal virtual void fireSyntacticPredicateFailed() { if (isDebugMode()) eventSupport.fireSyntacticPredicateFailed(inputState.guessing); } protected internal virtual void fireSyntacticPredicateStarted() { if (isDebugMode()) eventSupport.fireSyntacticPredicateStarted(inputState.guessing); } protected internal virtual void fireSyntacticPredicateSucceeded() { if (isDebugMode()) eventSupport.fireSyntacticPredicateSucceeded(inputState.guessing); } public virtual string getRuleName(int num) { return ruleNames[num]; } public virtual string getSemPredName(int num) { return semPredNames[num]; } public virtual void goToSleep() { lock(this) { try { Monitor.Wait(this); } catch (System.Threading.ThreadInterruptedException) { } } } public virtual bool isDebugMode() { return !_notDebugMode; } public override char LA(int i) { var la = base.LA(i); eventSupport.fireLA(i, la); return la; } protected internal override IToken makeToken(int t) { // do something with char buffer??? // try { // IToken tok = (Token)tokenObjectClass.newInstance(); // tok.setType(t); // // tok.setText(getText()); done in generated lexer now // tok.setLine(line); // return tok; // } // catch (InstantiationException ie) { // panic("can't instantiate a Token"); // } // catch (IllegalAccessException iae) { // panic("Token class is not accessible"); // } return base.makeToken(t); } public override void match(int c) { var la_1 = LA(1); try { base.match(c); eventSupport.fireMatch(Convert.ToChar(c), inputState.guessing); } catch (MismatchedCharException e) { if (inputState.guessing == 0) eventSupport.fireMismatch(la_1, Convert.ToChar(c), inputState.guessing); throw e; } } public override void match(BitSet b) { var text = this.text.ToString(); var la_1 = LA(1); try { base.match(b); eventSupport.fireMatch(la_1, b, text, inputState.guessing); } catch (MismatchedCharException e) { if (inputState.guessing == 0) eventSupport.fireMismatch(la_1, b, text, inputState.guessing); throw e; } } public override void match(string s) { var la_s = new System.Text.StringBuilder(""); var len = s.Length; // peek at the next len worth of characters try { for (var i = 1; i <= len; i++) { la_s.Append(base.LA(i)); } } catch (System.Exception) { } try { base.match(s); eventSupport.fireMatch(s, inputState.guessing); } catch (MismatchedCharException e) { if (inputState.guessing == 0) eventSupport.fireMismatch(la_s.ToString(), s, inputState.guessing); throw e; } } public override void matchNot(int c) { var la_1 = LA(1); try { base.matchNot(c); eventSupport.fireMatchNot(la_1, Convert.ToChar(c), inputState.guessing); } catch (MismatchedCharException e) { if (inputState.guessing == 0) eventSupport.fireMismatchNot(la_1, Convert.ToChar(c), inputState.guessing); throw e; } } public override void matchRange(int c1, int c2) { var la_1 = LA(1); try { base.matchRange(c1, c2); eventSupport.fireMatch(la_1, "" + c1 + c2, inputState.guessing); } catch (MismatchedCharException e) { if (inputState.guessing == 0) eventSupport.fireMismatch(la_1, "" + c1 + c2, inputState.guessing); throw e; } } public override void newline() { base.newline(); eventSupport.fireNewLine(getLine()); } public virtual void removeMessageListener(MessageListener l) { eventSupport.removeMessageListener(l); } public virtual void removeNewLineListener(NewLineListener l) { eventSupport.removeNewLineListener(l); } public virtual void removeParserListener(ParserListener l) { eventSupport.removeParserListener(l); } public virtual void removeParserMatchListener(ParserMatchListener l) { eventSupport.removeParserMatchListener(l); } public virtual void removeParserTokenListener(ParserTokenListener l) { eventSupport.removeParserTokenListener(l); } public virtual void removeSemanticPredicateListener(SemanticPredicateListener l) { eventSupport.removeSemanticPredicateListener(l); } public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l) { eventSupport.removeSyntacticPredicateListener(l); } public virtual void removeTraceListener(TraceListener l) { eventSupport.removeTraceListener(l); } /// <summary>Report exception errors caught in nextToken() /// </summary> public virtual void reportError(MismatchedCharException e) { eventSupport.fireReportError(e); base.reportError(e); } /// <summary>Parser error-reporting function can be overridden in subclass /// </summary> public override void reportError(string s) { eventSupport.fireReportError(s); base.reportError(s); } /// <summary>Parser warning-reporting function can be overridden in subclass /// </summary> public override void reportWarning(string s) { eventSupport.fireReportWarning(s); base.reportWarning(s); } public virtual void setupDebugging() { } public virtual void wakeUp() { lock(this) { Monitor.Pulse(this); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Management.Automation; using System.Collections.ObjectModel; using System.Security.Cryptography; using System.IO; namespace Microsoft.PowerShell.Commands { /// <summary> /// This class implements Get-FileHash. /// </summary> [Cmdlet(VerbsCommon.Get, "FileHash", DefaultParameterSetName = PathParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=517145")] [OutputType(typeof(FileHashInfo))] public class GetFileHashCommand : HashCmdletBase { /// <summary> /// Path parameter. /// The paths of the files to calculate hash values. /// Resolved wildcards. /// </summary> /// <value></value> [Parameter(Mandatory = true, ParameterSetName = PathParameterSet, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Path { get { return _paths; } set { _paths = value; } } /// <summary> /// LiteralPath parameter. /// The literal paths of the files to calculate a hashs. /// Don't resolved wildcards. /// </summary> /// <value></value> [Parameter(Mandatory = true, ParameterSetName = LiteralPathParameterSet, Position = 0, ValueFromPipelineByPropertyName = true)] [Alias("PSPath", "LP")] public string[] LiteralPath { get { return _paths; } set { _paths = value; } } private string[] _paths; /// <summary> /// InputStream parameter. /// The stream of the file to calculate a hash. /// </summary> /// <value></value> [Parameter(Mandatory = true, ParameterSetName = StreamParameterSet, Position = 0)] public Stream InputStream { get; set; } /// <summary> /// BeginProcessing() override. /// This is for hash function init. /// </summary> protected override void BeginProcessing() { InitHasher(Algorithm); } /// <summary> /// ProcessRecord() override. /// This is for paths collecting from pipe. /// </summary> protected override void ProcessRecord() { List<string> pathsToProcess = new List<string>(); ProviderInfo provider = null; switch (ParameterSetName) { case PathParameterSet: // Resolve paths and check existence foreach (string path in _paths) { try { Collection<string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider); if (newPaths != null) { pathsToProcess.AddRange(newPaths); } } catch (ItemNotFoundException e) { if (!WildcardPattern.ContainsWildcardCharacters(path)) { ErrorRecord errorRecord = new ErrorRecord(e, "FileNotFound", ErrorCategory.ObjectNotFound, path); WriteError(errorRecord); } } } break; case LiteralPathParameterSet: foreach (string path in _paths) { string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path); pathsToProcess.Add(newPath); } break; } foreach (string path in pathsToProcess) { byte[] bytehash = null; string hash = null; Stream openfilestream = null; try { openfilestream = File.OpenRead(path); bytehash = hasher.ComputeHash(openfilestream); hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); WriteHashResult(Algorithm, hash, path); } catch (FileNotFoundException ex) { ErrorRecord errorRecord = new ErrorRecord(ex, "FileNotFound", ErrorCategory.ObjectNotFound, path); WriteError(errorRecord); } finally { openfilestream?.Dispose(); } } } /// <summary> /// Perform common error checks. /// Populate source code. /// </summary> protected override void EndProcessing() { if (ParameterSetName == StreamParameterSet) { byte[] bytehash = null; string hash = null; bytehash = hasher.ComputeHash(InputStream); hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); WriteHashResult(Algorithm, hash, string.Empty); } } /// <summary> /// Create FileHashInfo object and output it. /// </summary> private void WriteHashResult(string Algorithm, string hash, string path) { FileHashInfo result = new FileHashInfo(); result.Algorithm = Algorithm; result.Hash = hash; result.Path = path; WriteObject(result); } /// <summary> /// Parameter set names. /// </summary> private const string PathParameterSet = "Path"; private const string LiteralPathParameterSet = "LiteralPath"; private const string StreamParameterSet = "StreamParameterSet"; } /// <summary> /// Base Cmdlet for cmdlets which deal with crypto hashes. /// </summary> public class HashCmdletBase : PSCmdlet { /// <summary> /// Algorithm parameter. /// The hash algorithm name: "SHA1", "SHA256", "SHA384", "SHA512", "MD5". /// </summary> /// <value></value> [Parameter(Position = 1)] [ValidateSet(HashAlgorithmNames.SHA1, HashAlgorithmNames.SHA256, HashAlgorithmNames.SHA384, HashAlgorithmNames.SHA512, HashAlgorithmNames.MD5)] public string Algorithm { get { return _Algorithm; } set { // A hash algorithm name is case sensitive // and always must be in upper case _Algorithm = value.ToUpper(); } } private string _Algorithm = HashAlgorithmNames.SHA256; /// <summary> /// Hash algorithm is used. /// </summary> protected HashAlgorithm hasher; /// <summary> /// Hash algorithm names. /// </summary> internal static class HashAlgorithmNames { public const string MD5 = "MD5"; public const string SHA1 = "SHA1"; public const string SHA256 = "SHA256"; public const string SHA384 = "SHA384"; public const string SHA512 = "SHA512"; } /// <summary> /// Init a hash algorithm. /// </summary> protected void InitHasher(String Algorithm) { try { switch (Algorithm) { case HashAlgorithmNames.SHA1: hasher = SHA1.Create(); break; case HashAlgorithmNames.SHA256: hasher = SHA256.Create(); break; case HashAlgorithmNames.SHA384: hasher = SHA384.Create(); break; case HashAlgorithmNames.SHA512: hasher = SHA512.Create(); break; case HashAlgorithmNames.MD5: hasher = MD5.Create(); break; } } catch { // Seems it will never throw! Remove? Exception exc = new NotSupportedException(UtilityCommonStrings.AlgorithmTypeNotSupported); ThrowTerminatingError(new ErrorRecord(exc, "AlgorithmTypeNotSupported", ErrorCategory.NotImplemented, null)); } } } /// <summary> /// FileHashInfo class contains information about a file hash. /// </summary> public class FileHashInfo { /// <summary> /// Hash algorithm name. /// </summary> public string Algorithm { get; set; } /// <summary> /// Hash value. /// </summary> public string Hash { get; set; } /// <summary> /// File path. /// </summary> public string Path { get; set; } } }
// 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.Xml; using System.Collections; namespace System.Data.Common { internal sealed class SByteStorage : DataStorage { private const sbyte defaultValue = 0; private sbyte[] _values; public SByteStorage(DataColumn column) : base(column, typeof(sbyte), defaultValue, StorageType.SByte) { } public override object Aggregate(int[] records, AggregateType kind) { bool hasData = false; try { switch (kind) { case AggregateType.Sum: long sum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; checked { sum += _values[record]; } hasData = true; } if (hasData) { return sum; } return _nullValue; case AggregateType.Mean: long meanSum = defaultValue; int meanCount = 0; foreach (int record in records) { if (IsNull(record)) continue; checked { meanSum += _values[record]; } meanCount++; hasData = true; } if (hasData) { sbyte mean; checked { mean = (sbyte)(meanSum / meanCount); } return mean; } return _nullValue; case AggregateType.Var: case AggregateType.StDev: int count = 0; double var = defaultValue; double prec = defaultValue; double dsum = defaultValue; double sqrsum = defaultValue; foreach (int record in records) { if (IsNull(record)) continue; dsum += _values[record]; sqrsum += _values[record] * (double)_values[record]; count++; } if (count > 1) { var = count * sqrsum - (dsum * dsum); prec = var / (dsum * dsum); // we are dealing with the risk of a cancellation error // double is guaranteed only for 15 digits so a difference // with a result less than 1e-15 should be considered as zero if ((prec < 1e-15) || (var < 0)) var = 0; else var = var / (count * (count - 1)); if (kind == AggregateType.StDev) { return Math.Sqrt(var); } return var; } return _nullValue; case AggregateType.Min: sbyte min = sbyte.MaxValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; min = Math.Min(_values[record], min); hasData = true; } if (hasData) { return min; } return _nullValue; case AggregateType.Max: sbyte max = sbyte.MinValue; for (int i = 0; i < records.Length; i++) { int record = records[i]; if (IsNull(record)) continue; max = Math.Max(_values[record], max); hasData = true; } if (hasData) { return max; } return _nullValue; case AggregateType.First: if (records.Length > 0) { return _values[records[0]]; } return null; case AggregateType.Count: return base.Aggregate(records, kind); } } catch (OverflowException) { throw ExprException.Overflow(typeof(sbyte)); } throw ExceptionBuilder.AggregateException(kind, _dataType); } public override int Compare(int recordNo1, int recordNo2) { sbyte valueNo1 = _values[recordNo1]; sbyte valueNo2 = _values[recordNo2]; if (valueNo1.Equals(defaultValue) || valueNo2.Equals(defaultValue)) { int bitCheck = CompareBits(recordNo1, recordNo2); if (0 != bitCheck) return bitCheck; } return valueNo1.CompareTo(valueNo2); //return(valueNo1 - valueNo2); // copied from SByte.CompareTo(SByte) } public override int CompareValueTo(int recordNo, object value) { System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record"); System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { if (IsNull(recordNo)) { return 0; } return 1; } sbyte valueNo1 = _values[recordNo]; if ((defaultValue == valueNo1) && IsNull(recordNo)) { return -1; } return valueNo1.CompareTo((sbyte)value); //return(valueNo1 - valueNo2); // copied from SByte.CompareTo(SByte) } public override object ConvertValue(object value) { if (_nullValue != value) { if (null != value) { value = ((IConvertible)value).ToSByte(FormatProvider); } else { value = _nullValue; } } return value; } public override void Copy(int recordNo1, int recordNo2) { CopyBits(recordNo1, recordNo2); _values[recordNo2] = _values[recordNo1]; } public override object Get(int record) { sbyte value = _values[record]; if (!value.Equals(defaultValue)) { return value; } return GetBits(record); } public override void Set(int record, object value) { System.Diagnostics.Debug.Assert(null != value, "null value"); if (_nullValue == value) { _values[record] = defaultValue; SetNullBit(record, true); } else { _values[record] = ((IConvertible)value).ToSByte(FormatProvider); SetNullBit(record, false); } } public override void SetCapacity(int capacity) { sbyte[] newValues = new sbyte[capacity]; if (null != _values) { Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length)); } _values = newValues; base.SetCapacity(capacity); } public override object ConvertXmlToObject(string s) { return XmlConvert.ToSByte(s); } public override string ConvertObjectToXml(object value) { return XmlConvert.ToString((sbyte)value); } protected override object GetEmptyStorage(int recordCount) { return new sbyte[recordCount]; } protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex) { sbyte[] typedStore = (sbyte[])store; typedStore[storeIndex] = _values[record]; nullbits.Set(storeIndex, IsNull(record)); } protected override void SetStorage(object store, BitArray nullbits) { _values = (sbyte[])store; SetNullStorage(nullbits); } } }
using System; using System.Windows.Forms; using System.Drawing; using System.Collections.Generic; namespace ComputerTimeTracker { /// <summary> /// The form that shows the computer usage time report. /// </summary> public partial class TimeReport: Form, IMainForm { /// <summary> /// Whether the form should be closed when the Close event is received. /// </summary> private bool _close = false; /// <summary> /// Dynamic controls that may be permanently removed when updating the content. /// </summary> private readonly IList<Control> _dynamicControls = new List<Control>(); /// <summary> /// The number of vertical pixels between trackable event labels. /// </summary> private readonly int EVENT_LABEL_HEIGHT; /// <summary> /// Initial height of the form, fitting one trackable event. /// </summary> private readonly int FORM_INITIAL_HEIGHT; /// <summary> /// The color of the last period panel. /// </summary> private Color _lastPeriodPanelColor; /// <summary> /// Time tracker instance. /// </summary> private readonly TimeTracker _timeTracker; /// <summary> /// The current time used in time span calculations. /// </summary> private DateTime _currentTime; /// <summary> /// Creates a new TimeReport instance. /// </summary> /// <param name="tracker">Time tracker instance.</param> public TimeReport(TimeTracker timeTracker) { InitializeComponent(); FormClosing += new FormClosingEventHandler(MainFormClosing); _timeTracker = timeTracker; // The start labels are only used for helping in layout design _lblTimeStart.Visible = false; _lblTextStart.Visible = false; EVENT_LABEL_HEIGHT = _lblTextCurrent.Top - _lblTextStart.Top; FORM_INITIAL_HEIGHT = Height; } /// <summary> /// Actually closes the form. Calling the <see cref="Close"/> method /// only hides the form. /// </summary> public void ForceClose() { _close = true; Close(); } /// <summary> /// Updates the labels that describe tracked events. /// </summary> private void UpdateEventContent() { int timeLeft = _lblTimeStart.Left; int descriptionLeft = _lblTextStart.Left; int top = _lblTextStart.Top; int labelCount = 0; foreach (TrackableEvent trackableEvent in _timeTracker.GetEvents()) { Label timeLabel = new Label(); timeLabel.AutoSize = true; timeLabel.Location = new Point(timeLeft, top); timeLabel.Text = trackableEvent.Time.ToLongTimeString(); ; Controls.Add(timeLabel); _dynamicControls.Add(timeLabel); Label descriptionLabel = new Label(); descriptionLabel.AutoSize = true; descriptionLabel.Location = new Point(descriptionLeft, top); descriptionLabel.Text = trackableEvent.ToString(); Controls.Add(descriptionLabel); _dynamicControls.Add(descriptionLabel); top += EVENT_LABEL_HEIGHT; labelCount++; } // Adjust the height; the initial height can fit one event Height = FORM_INITIAL_HEIGHT + ((labelCount - 1) * EVENT_LABEL_HEIGHT); } /// <summary> /// Updates the components that describe time periods between tracked events. /// </summary> private void UpdateTimePeriodContent() { int panelLeft = _pnlPeriod1.Left; int panelTop = _pnlPeriod1.Top; Size panelSize = _pnlPeriod1.Size; int checkBoxLeft = _chkPeriod1.Left; int checkBoxTop = _chkPeriod1.Top; Size checkBoxSize = _chkPeriod1.Size; foreach (TimePeriod period in _timeTracker.GetPeriods(_currentTime)) { Panel periodPanel = new Panel(); periodPanel.Size = panelSize; periodPanel.Location = new Point(panelLeft, panelTop); periodPanel.BackColor = (period.Type == TimePeriod.PeriodType.Active) ? GetActiveBackColor() : GetInactiveBackColor(); _lastPeriodPanelColor = periodPanel.BackColor; Controls.Add(periodPanel); _dynamicControls.Add(periodPanel); Label periodDurationLabel = new Label(); periodDurationLabel.Size = periodPanel.Size; periodDurationLabel.Location = new Point(0, 0); periodDurationLabel.TextAlign = ContentAlignment.MiddleCenter; periodDurationLabel.ForeColor = (period.Type == TimePeriod.PeriodType.Active) ? GetActiveForeColor() : GetInactiveForeColor(); periodDurationLabel.Text = period.DurationText; periodPanel.Controls.Add(periodDurationLabel); CheckBox periodCheckBox = new CheckBox(); periodCheckBox.Size = checkBoxSize; periodCheckBox.Location = new Point(checkBoxLeft, checkBoxTop); periodCheckBox.Checked = period.IsWorkTime; periodCheckBox.Tag = period; periodCheckBox.CheckedChanged += new EventHandler(periodCheckBox_CheckedChanged); Controls.Add(periodCheckBox); _dynamicControls.Add(periodCheckBox); panelTop += EVENT_LABEL_HEIGHT; checkBoxTop += EVENT_LABEL_HEIGHT; } } /// <summary> /// Occurs when the time period check box state as changed. /// </summary> /// <param name="sender">The changed check box instance.</param> /// <param name="e">Ignored.</param> private void periodCheckBox_CheckedChanged(object sender, EventArgs e) { CheckBox checkBox = sender as CheckBox; TimePeriod period = checkBox.Tag as TimePeriod; period.IsWorkTime = checkBox.Checked; UpdateWorkTimeLabel(); } /// <summary> /// Updates the labels that always appear in the form. /// </summary> private void UpdateStaticContent() { _lblTimeCurrent.Text = _currentTime.ToLongTimeString(); UpdateWorkTimeLabel(); } /// <summary> /// Updates the current work time label content. /// </summary> private void UpdateWorkTimeLabel() { TimeSpan workTime = _timeTracker.GetWorkTime(_currentTime); _lblTimeWork.Text = String.Format("{0:0#}:{1:0#}:{2:0#}", workTime.Hours, workTime.Minutes, workTime.Seconds); } /// <summary> /// Called when the OK button is clicked. /// </summary> /// <param name="sender">Ignored.</param> /// <param name="e">Ignored.</param> private void _btnOk_Click(object sender, EventArgs e) { Close(); } #region IMainForm Members public Color GetActiveBackColor() { return Color.Green; } public Color GetActiveForeColor() { return SystemColors.ControlLightLight; } public Color GetInactiveBackColor() { return Color.YellowGreen; } public Color GetInactiveForeColor() { return SystemColors.ControlDarkDark; } public Color GetLastPeriodPanelColor() { return _lastPeriodPanelColor; } public void UpdateForm(Clock clock) { foreach (Control component in _dynamicControls) { Controls.Remove(component); } _dynamicControls.Clear(); _currentTime = clock.Now; UpdateEventContent(); UpdateTimePeriodContent(); UpdateStaticContent(); } public void MainFormClosing(object sender, FormClosingEventArgs e) { if ((e.CloseReason == CloseReason.UserClosing) && !_close) { e.Cancel = true; Hide(); } } #endregion // IMainForm Members } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// QuickAdjustment /// </summary> [DataContract] public partial class QuickAdjustment : IEquatable<QuickAdjustment> { /// <summary> /// Initializes a new instance of the <see cref="QuickAdjustment" /> class. /// </summary> [JsonConstructorAttribute] protected QuickAdjustment() { } /// <summary> /// Initializes a new instance of the <see cref="QuickAdjustment" /> class. /// </summary> /// <param name="WarehouseId">WarehouseId (required).</param> /// <param name="LocationId">LocationId (required).</param> /// <param name="AdjustmentCode">AdjustmentCode (required).</param> /// <param name="TotalQuantity">TotalQuantity (required).</param> /// <param name="Message">Message.</param> /// <param name="Sku">Sku.</param> public QuickAdjustment(int? WarehouseId = null, int? LocationId = null, string AdjustmentCode = null, int? TotalQuantity = null, string Message = null, string Sku = null) { // to ensure "WarehouseId" is required (not null) if (WarehouseId == null) { throw new InvalidDataException("WarehouseId is a required property for QuickAdjustment and cannot be null"); } else { this.WarehouseId = WarehouseId; } // to ensure "LocationId" is required (not null) if (LocationId == null) { throw new InvalidDataException("LocationId is a required property for QuickAdjustment and cannot be null"); } else { this.LocationId = LocationId; } // to ensure "AdjustmentCode" is required (not null) if (AdjustmentCode == null) { throw new InvalidDataException("AdjustmentCode is a required property for QuickAdjustment and cannot be null"); } else { this.AdjustmentCode = AdjustmentCode; } // to ensure "TotalQuantity" is required (not null) if (TotalQuantity == null) { throw new InvalidDataException("TotalQuantity is a required property for QuickAdjustment and cannot be null"); } else { this.TotalQuantity = TotalQuantity; } this.Message = Message; this.Sku = Sku; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets WarehouseId /// </summary> [DataMember(Name="warehouseId", EmitDefaultValue=false)] public int? WarehouseId { get; set; } /// <summary> /// Gets or Sets LocationId /// </summary> [DataMember(Name="locationId", EmitDefaultValue=false)] public int? LocationId { get; set; } /// <summary> /// Gets or Sets AdjustmentCode /// </summary> [DataMember(Name="adjustmentCode", EmitDefaultValue=false)] public string AdjustmentCode { get; set; } /// <summary> /// Gets or Sets TotalQuantity /// </summary> [DataMember(Name="totalQuantity", EmitDefaultValue=false)] public int? TotalQuantity { get; set; } /// <summary> /// Gets or Sets Message /// </summary> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; set; } /// <summary> /// Gets or Sets Status /// </summary> [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; private set; } /// <summary> /// Gets or Sets Sku /// </summary> [DataMember(Name="sku", EmitDefaultValue=false)] public string Sku { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class QuickAdjustment {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n"); sb.Append(" LocationId: ").Append(LocationId).Append("\n"); sb.Append(" AdjustmentCode: ").Append(AdjustmentCode).Append("\n"); sb.Append(" TotalQuantity: ").Append(TotalQuantity).Append("\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Sku: ").Append(Sku).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as QuickAdjustment); } /// <summary> /// Returns true if QuickAdjustment instances are equal /// </summary> /// <param name="other">Instance of QuickAdjustment to be compared</param> /// <returns>Boolean</returns> public bool Equals(QuickAdjustment other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.WarehouseId == other.WarehouseId || this.WarehouseId != null && this.WarehouseId.Equals(other.WarehouseId) ) && ( this.LocationId == other.LocationId || this.LocationId != null && this.LocationId.Equals(other.LocationId) ) && ( this.AdjustmentCode == other.AdjustmentCode || this.AdjustmentCode != null && this.AdjustmentCode.Equals(other.AdjustmentCode) ) && ( this.TotalQuantity == other.TotalQuantity || this.TotalQuantity != null && this.TotalQuantity.Equals(other.TotalQuantity) ) && ( this.Message == other.Message || this.Message != null && this.Message.Equals(other.Message) ) && ( this.Status == other.Status || this.Status != null && this.Status.Equals(other.Status) ) && ( this.Sku == other.Sku || this.Sku != null && this.Sku.Equals(other.Sku) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.WarehouseId != null) hash = hash * 59 + this.WarehouseId.GetHashCode(); if (this.LocationId != null) hash = hash * 59 + this.LocationId.GetHashCode(); if (this.AdjustmentCode != null) hash = hash * 59 + this.AdjustmentCode.GetHashCode(); if (this.TotalQuantity != null) hash = hash * 59 + this.TotalQuantity.GetHashCode(); if (this.Message != null) hash = hash * 59 + this.Message.GetHashCode(); if (this.Status != null) hash = hash * 59 + this.Status.GetHashCode(); if (this.Sku != null) hash = hash * 59 + this.Sku.GetHashCode(); return hash; } } } }
/* * 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.Data; using System.Data.SqlClient; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.MSSQL { public class MSSQLEstateStore : IEstateDataStore { private const string _migrationStore = "EstateStore"; private static readonly ILog _Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MSSQLManager _Database; private string m_connectionString; private FieldInfo[] _Fields; private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>(); #region Public methods public MSSQLEstateStore() { } public MSSQLEstateStore(string connectionString) { Initialise(connectionString); } /// <summary> /// Initialises the estatedata class. /// </summary> /// <param name="connectionString">connectionString.</param> public void Initialise(string connectionString) { if (!string.IsNullOrEmpty(connectionString)) { m_connectionString = connectionString; _Database = new MSSQLManager(connectionString); } //Migration settings _Database.CheckMigration(_migrationStore); //Interesting way to get parameters! Maybe implement that also with other types Type t = typeof(EstateSettings); _Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in _Fields) { if (f.Name.Substring(0, 2) == "m_") _FieldMap[f.Name.Substring(2)] = f; } } /// <summary> /// Loads the estate settings. /// </summary> /// <param name="regionID">region ID.</param> /// <returns></returns> public EstateSettings LoadEstateSettings(UUID regionID, bool create) { EstateSettings es = new EstateSettings(); string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = @RegionID"; bool insertEstate = false; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { foreach (string name in FieldList) { FieldInfo f = _FieldMap[name]; object v = reader[name]; if (f.FieldType == typeof(bool) ) { f.SetValue(es, Convert.ToInt32(v) != 0); } else if (f.FieldType == typeof(UUID) ) { f.SetValue(es, new UUID((Guid)v)); // uuid); } else if (f.FieldType == typeof(string)) { f.SetValue(es, v.ToString()); } else if (f.FieldType == typeof(UInt32)) { f.SetValue(es, Convert.ToUInt32(v)); } else if (f.FieldType == typeof(Single)) { f.SetValue(es, Convert.ToSingle(v)); } else f.SetValue(es, v); } } else { insertEstate = true; } } } if (insertEstate && create) { List<string> names = new List<string>(FieldList); names.Remove("EstateID"); sql = string.Format("insert into estate_settings ({0}) values ( @{1})", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray())); //_Log.Debug("[DB ESTATE]: SQL: " + sql); using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand insertCommand = new SqlCommand(sql, conn)) { insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()"; foreach (string name in names) { insertCommand.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es))); } SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int); idParameter.Direction = ParameterDirection.Output; insertCommand.Parameters.Add(idParameter); conn.Open(); insertCommand.ExecuteNonQuery(); es.EstateID = Convert.ToUInt32(idParameter.Value); } sql = "INSERT INTO [estate_map] ([RegionID] ,[EstateID]) VALUES (@RegionID, @EstateID)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID)); cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID)); // This will throw on dupe key try { conn.Open(); cmd.ExecuteNonQuery(); } catch (Exception e) { _Log.DebugFormat("[ESTATE DB]: Error inserting regionID and EstateID in estate_map: {0}", e); } } //TODO check if this is needed?? es.Save(); } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); //Set event es.OnSave += StoreEstateSettings; return es; } /// <summary> /// Stores the estate settings. /// </summary> /// <param name="es">estate settings</param> public void StoreEstateSettings(EstateSettings es) { List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = string.Format("UPDATE estate_settings SET "); foreach (string name in names) { sql += name + " = @" + name + ", "; } sql = sql.Remove(sql.LastIndexOf(",")); sql += " WHERE EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { foreach (string name in names) { cmd.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es))); } cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID)); conn.Open(); cmd.ExecuteNonQuery(); } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } #endregion #region Private methods private string[] FieldList { get { return new List<string>(_FieldMap.Keys).ToArray(); } } private void LoadBanList(EstateSettings es) { es.ClearBans(); string sql = "select bannedUUID from estateban where EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int); idParameter.Value = es.EstateID; cmd.Parameters.Add(idParameter); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { EstateBan eb = new EstateBan(); eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } private UUID[] LoadUUIDList(uint estateID, string table) { List<UUID> uuids = new List<UUID>(); string sql = string.Format("select uuid from {0} where EstateID = @EstateID", table); using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { uuids.Add(new UUID((Guid)reader["uuid"])); //uuid); } } } return uuids.ToArray(); } private void SaveBanList(EstateSettings es) { //Delete first using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = @EstateID"; cmd.Parameters.AddWithValue("@EstateID", (int)es.EstateID); cmd.ExecuteNonQuery(); //Insert after cmd.CommandText = "insert into estateban (EstateID, bannedUUID) values ( @EstateID, @bannedUUID )"; cmd.Parameters.AddWithValue("@bannedUUID", Guid.Empty); foreach (EstateBan b in es.EstateBans) { cmd.Parameters["@bannedUUID"].Value = b.BannedUserID.Guid; cmd.ExecuteNonQuery(); } } } } private void SaveUUIDList(uint estateID, string table, UUID[] data) { using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.Parameters.AddWithValue("@EstateID", (int)estateID); cmd.CommandText = string.Format("delete from {0} where EstateID = @EstateID", table); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table); cmd.Parameters.AddWithValue("@uuid", Guid.Empty); foreach (UUID uuid in data) { cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works cmd.ExecuteNonQuery(); } } } } public EstateSettings LoadEstateSettings(int estateID) { return new EstateSettings(); } public List<int> GetEstates(string search) { return new List<int>(); } public bool LinkRegion(UUID regionID, int estateID) { return false; } public List<UUID> GetRegions(int estateID) { return new List<UUID>(); } public bool DeleteEstate(int estateID) { return false; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="HttpHeaderCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Collection of headers with write through to IIS for Set, Add, and Remove * * Copyright (c) 2000 Microsoft Corporation */ namespace System.Web { using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Security.Permissions; using System.Runtime.Serialization; using System.Web.Hosting; using System.Web.Util; [Serializable()] internal class HttpHeaderCollection : HttpValueCollection { private HttpRequest _request; private HttpResponse _response; private IIS7WorkerRequest _iis7WorkerRequest; // This constructor creates the header collection for request headers. // Try to preallocate the base collection with a size that should be sufficient // to store the headers for most requests. internal HttpHeaderCollection(HttpWorkerRequest wr, HttpRequest request, int capacity) : base(capacity) { // if this is an IIS7WorkerRequest, then the collection will be writeable and we will // call into IIS7 to update the header blocks when changes are made. _iis7WorkerRequest = wr as IIS7WorkerRequest; _request = request; } // This constructor creates the header collection for response headers. // Try to preallocate the base collection with a size that should be sufficient // to store the headers for most requests. internal HttpHeaderCollection(HttpWorkerRequest wr, HttpResponse response, int capacity) : base(capacity) { // if this is an IIS7WorkerRequest, then the collection will be writeable and we will // call into IIS7 to update the header blocks when changes are made. _iis7WorkerRequest = wr as IIS7WorkerRequest; _response = response; } // This copy constructor is used by the granular request validation feature. Since these collections are immutable // once created, it's ok for us to have two collections containing the same data. internal HttpHeaderCollection(HttpHeaderCollection col) : base(col) { _request = col._request; _response = col._response; _iis7WorkerRequest = col._iis7WorkerRequest; } [SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { // WOS 127340: Request.Headers and Response.Headers are no longer serializable base.GetObjectData(info, context); // create an instance of HttpValueCollection since HttpHeaderCollection is tied to the request info.SetType(typeof(HttpValueCollection)); } public override void Add(String name, String value) { if (_iis7WorkerRequest == null) { throw new PlatformNotSupportedException(); } // append to existing value SetHeader(name, value, false /*replace*/); } public override void Clear() { throw new NotSupportedException(); } internal void ClearInternal() { // clear is only supported for response headers if (_request != null) { throw new NotSupportedException(); } base.Clear(); } public override void Set(String name, String value) { if (_iis7WorkerRequest == null) { throw new PlatformNotSupportedException(); } // set new value SetHeader(name, value, true /*replace*/); } internal void SetHeader(String name, String value, bool replace) { Debug.Assert(_iis7WorkerRequest != null, "_iis7WorkerRequest != null"); if (name == null) { throw new ArgumentNullException("name"); } if (value == null) { throw new ArgumentNullException("value"); } if (_request != null) { _iis7WorkerRequest.SetRequestHeader(name, value, replace); } else { if (_response.HeadersWritten) { throw new HttpException(SR.GetString(SR.Cannot_append_header_after_headers_sent)); } // IIS7 integrated pipeline mode needs to call the header encoding routine explicitly since it // doesn't go through HttpResponse.WriteHeaders(). string encodedName = name; string encodedValue = value; if (HttpRuntime.EnableHeaderChecking) { HttpEncoder.Current.HeaderNameValueEncode(name, value, out encodedName, out encodedValue); } // set the header encoding to the selected encoding _iis7WorkerRequest.SetHeaderEncoding(_response.HeaderEncoding); _iis7WorkerRequest.SetResponseHeader(encodedName, encodedValue, replace); if (_response.HasCachePolicy && StringUtil.EqualsIgnoreCase("Set-Cookie", name)) { _response.Cache.SetHasSetCookieHeader(); } } // update managed copy of header if (replace) { base.Set(name, value); } else { base.Add(name, value); } if (_request != null) { // update managed copy of server variable string svValue = replace ? value : base.Get(name); HttpServerVarsCollection serverVars = _request.ServerVariables as HttpServerVarsCollection; if (serverVars != null) { serverVars.SynchronizeServerVariable("HTTP_" + name.ToUpper(CultureInfo.InvariantCulture).Replace('-', '_'), svValue, ensurePopulated: false); } // invalidate Params collection _request.InvalidateParams(); } } // updates managed copy of header with current value from native header block internal void SynchronizeHeader(String name, String value) { if (name == null) { throw new ArgumentNullException("name"); } if (value != null) { base.Set(name, value); } else { base.Remove(name); } if (_request != null) { _request.InvalidateParams(); } } public override void Remove(String name) { if (_iis7WorkerRequest == null) { throw new PlatformNotSupportedException(); } if (name == null) { throw new ArgumentNullException("name"); } if (_request != null) { // delete by sending null value _iis7WorkerRequest.SetRequestHeader(name, null /*value*/, false /*replace*/); } else { _iis7WorkerRequest.SetResponseHeader(name, null /*value*/, false /*replace*/); } base.Remove(name); if (_request != null) { // update managed copy of server variable HttpServerVarsCollection serverVars = _request.ServerVariables as HttpServerVarsCollection; if (serverVars != null) { serverVars.SynchronizeServerVariable("HTTP_" + name.ToUpper(CultureInfo.InvariantCulture).Replace('-', '_'), null, ensurePopulated: false); } // invalidate Params collection _request.InvalidateParams(); } } } }
using System; using System.Windows.Forms; namespace Free.Controls.TreeView.Tree { internal class NormalInputState : InputState { private bool _mouseDownFlag=false; public NormalInputState(TreeViewAdv tree) : base(tree) { } public override void KeyDown(KeyEventArgs args) { if(Tree.CurrentNode==null&&Tree.Root.Nodes.Count>0) Tree.CurrentNode=Tree.Root.Nodes[0]; if(Tree.CurrentNode!=null) { switch(args.KeyCode) { case Keys.Right: if(!Tree.CurrentNode.IsExpanded) Tree.CurrentNode.IsExpanded=true; else if(Tree.CurrentNode.Nodes.Count>0) Tree.SelectedNode=Tree.CurrentNode.Nodes[0]; args.Handled=true; break; case Keys.Left: if(Tree.CurrentNode.IsExpanded) Tree.CurrentNode.IsExpanded=false; else if(Tree.CurrentNode.Parent!=Tree.Root) Tree.SelectedNode=Tree.CurrentNode.Parent; args.Handled=true; break; case Keys.Down: NavigateForward(1); args.Handled=true; break; case Keys.Up: NavigateBackward(1); args.Handled=true; break; case Keys.PageDown: NavigateForward(Math.Max(1, Tree.CurrentPageSize-1)); args.Handled=true; break; case Keys.PageUp: NavigateBackward(Math.Max(1, Tree.CurrentPageSize-1)); args.Handled=true; break; case Keys.Home: if(Tree.RowMap.Count>0) FocusRow(Tree.RowMap[0]); args.Handled=true; break; case Keys.End: if(Tree.RowMap.Count>0) FocusRow(Tree.RowMap[Tree.RowMap.Count-1]); args.Handled=true; break; case Keys.Subtract: Tree.CurrentNode.Collapse(); args.Handled=true; args.SuppressKeyPress=true; break; case Keys.Add: Tree.CurrentNode.Expand(); args.Handled=true; args.SuppressKeyPress=true; break; case Keys.Multiply: Tree.CurrentNode.ExpandAll(); args.Handled=true; args.SuppressKeyPress=true; break; case Keys.A: if(args.Modifiers==Keys.Control) Tree.SelectAllNodes(); break; } } } public override void MouseDown(TreeNodeAdvMouseEventArgs args) { if(args.Node!=null) { Tree.ItemDragMode=true; Tree.ItemDragStart=args.Location; if(args.Button==MouseButtons.Left||args.Button==MouseButtons.Right) { Tree.BeginUpdate(); try { Tree.CurrentNode=args.Node; if(args.Node.IsSelected) _mouseDownFlag=true; else { _mouseDownFlag=false; DoMouseOperation(args); } } finally { Tree.EndUpdate(); } } } else { Tree.ItemDragMode=false; MouseDownAtEmptySpace(args); } } public override void MouseUp(TreeNodeAdvMouseEventArgs args) { Tree.ItemDragMode=false; if(_mouseDownFlag&&args.Node!=null) { if(args.Button==MouseButtons.Left) DoMouseOperation(args); else if(args.Button==MouseButtons.Right) Tree.CurrentNode=args.Node; } _mouseDownFlag=false; } private void NavigateBackward(int n) { int row=Math.Max(Tree.CurrentNode.Row-n, 0); if(row!=Tree.CurrentNode.Row) FocusRow(Tree.RowMap[row]); } private void NavigateForward(int n) { int row=Math.Min(Tree.CurrentNode.Row+n, Tree.RowCount-1); if(row!=Tree.CurrentNode.Row) FocusRow(Tree.RowMap[row]); } protected virtual void MouseDownAtEmptySpace(TreeNodeAdvMouseEventArgs args) { Tree.ClearSelection(); } protected virtual void FocusRow(TreeNodeAdv node) { Tree.SuspendSelectionEvent=true; try { Tree.ClearSelectionInternal(); Tree.CurrentNode=node; Tree.SelectionStart=node; node.IsSelected=true; Tree.ScrollTo(node); } finally { Tree.SuspendSelectionEvent=false; } } protected bool CanSelect(TreeNodeAdv node) { if(Tree.SelectionMode==TreeSelectionMode.MultiSameParent) { return (Tree.SelectionStart==null||node.Parent==Tree.SelectionStart.Parent); } else return true; } protected virtual void DoMouseOperation(TreeNodeAdvMouseEventArgs args) { if(Tree.SelectedNodes.Count==1&&args.Node!=null&&args.Node.IsSelected) return; Tree.SuspendSelectionEvent=true; try { Tree.ClearSelectionInternal(); if(args.Node!=null) args.Node.IsSelected=true; Tree.SelectionStart=args.Node; } finally { Tree.SuspendSelectionEvent=false; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Serialization; using Orleans.Streams; namespace Orleans.Providers { /// <summary> /// Pooled cache for memory stream provider /// </summary> public class MemoryPooledCache<TSerializer> : IQueueCache, ICacheDataAdapter where TSerializer : class, IMemoryMessageBodySerializer { private readonly IObjectPool<FixedSizeBuffer> bufferPool; private readonly TSerializer serializer; private readonly IEvictionStrategy evictionStrategy; private readonly PooledQueueCache cache; private FixedSizeBuffer currentBuffer; /// <summary> /// Pooled cache for memory stream provider /// </summary> /// <param name="bufferPool"></param> /// <param name="purgePredicate"></param> /// <param name="logger"></param> /// <param name="serializer"></param> /// <param name="cacheMonitor"></param> /// <param name="monitorWriteInterval">monitor write interval. Only triggered for active caches.</param> public MemoryPooledCache(IObjectPool<FixedSizeBuffer> bufferPool, TimePurgePredicate purgePredicate, ILogger logger, TSerializer serializer, ICacheMonitor cacheMonitor, TimeSpan? monitorWriteInterval) { this.bufferPool = bufferPool; this.serializer = serializer; this.cache = new PooledQueueCache(this, logger, cacheMonitor, monitorWriteInterval); this.evictionStrategy = new ChronologicalEvictionStrategy(logger, purgePredicate, cacheMonitor, monitorWriteInterval) {PurgeObservable = cache}; } private CachedMessage QueueMessageToCachedMessage(MemoryMessageData queueMessage, DateTime dequeueTimeUtc) { StreamPosition streamPosition = GetStreamPosition(queueMessage); return new CachedMessage() { StreamId = streamPosition.StreamId, SequenceNumber = queueMessage.SequenceNumber, EnqueueTimeUtc = queueMessage.EnqueueTimeUtc, DequeueTimeUtc = dequeueTimeUtc, Segment = SerializeMessageIntoPooledSegment(queueMessage) }; } // Placed object message payload into a segment from a buffer pool. When this get's too big, older blocks will be purged private ArraySegment<byte> SerializeMessageIntoPooledSegment(MemoryMessageData queueMessage) { // serialize payload int size = SegmentBuilder.CalculateAppendSize(queueMessage.Payload); // get segment from current block ArraySegment<byte> segment; if (currentBuffer == null || !currentBuffer.TryGetSegment(size, out segment)) { // no block or block full, get new block and try again currentBuffer = bufferPool.Allocate(); //call EvictionStrategy's OnBlockAllocated method this.evictionStrategy.OnBlockAllocated(currentBuffer); // if this fails with clean block, then requested size is too big if (!currentBuffer.TryGetSegment(size, out segment)) { string errmsg = String.Format(CultureInfo.InvariantCulture, "Message size is too big. MessageSize: {0}", size); throw new ArgumentOutOfRangeException(nameof(queueMessage), errmsg); } } // encode namespace, offset, partitionkey, properties and payload into segment int writeOffset = 0; SegmentBuilder.Append(segment, ref writeOffset, queueMessage.Payload); return segment; } private StreamPosition GetStreamPosition(MemoryMessageData queueMessage) { return new StreamPosition(queueMessage.StreamId, new EventSequenceTokenV2(queueMessage.SequenceNumber)); } private class Cursor : IQueueCacheCursor { private readonly PooledQueueCache cache; private readonly object cursor; private IBatchContainer current; public Cursor(PooledQueueCache cache, StreamId streamId, StreamSequenceToken token) { this.cache = cache; cursor = cache.GetCursor(streamId, token); } public void Dispose() { } public IBatchContainer GetCurrent(out Exception exception) { exception = null; return current; } public bool MoveNext() { IBatchContainer next; if (!cache.TryGetNextMessage(cursor, out next)) { return false; } current = next; return true; } public void Refresh(StreamSequenceToken token) { } public void RecordDeliveryFailure() { } } /// <summary> /// The limit of the maximum number of items that can be added /// </summary> public int GetMaxAddCount() { return 100; } /// <summary> /// Add messages to the cache /// </summary> /// <param name="messages"></param> public void AddToCache(IList<IBatchContainer> messages) { DateTime utcNow = DateTime.UtcNow; List<CachedMessage> memoryMessages = messages .Cast<MemoryBatchContainer<TSerializer>>() .Select(container => container.MessageData) .Select(batch => QueueMessageToCachedMessage(batch, utcNow)) .ToList(); cache.Add(memoryMessages, DateTime.UtcNow); } /// <summary> /// Ask the cache if it has items that can be purged from the cache /// (so that they can be subsequently released them the underlying queue). /// </summary> /// <param name="purgedItems"></param> public bool TryPurgeFromCache(out IList<IBatchContainer> purgedItems) { purgedItems = null; this.evictionStrategy.PerformPurge(DateTime.UtcNow); return false; } /// <summary> /// Acquire a stream message cursor. This can be used to retrieve messages from the /// cache starting at the location indicated by the provided token. /// </summary> /// <param name="streamId"></param> /// <param name="token"></param> /// <returns></returns> public IQueueCacheCursor GetCacheCursor(StreamId streamId, StreamSequenceToken token) { return new Cursor(cache, streamId, token); } /// <summary> /// Returns true if this cache is under pressure. /// </summary> public bool IsUnderPressure() { return false; } public IBatchContainer GetBatchContainer(ref CachedMessage cachedMessage) { //Deserialize payload int readOffset = 0; ArraySegment<byte> payload = SegmentBuilder.ReadNextBytes(cachedMessage.Segment, ref readOffset); MemoryMessageData message = MemoryMessageData.Create(cachedMessage.StreamId, new ArraySegment<byte>(payload.ToArray())); message.SequenceNumber = cachedMessage.SequenceNumber; return new MemoryBatchContainer<TSerializer>(message, this.serializer); } public StreamSequenceToken GetSequenceToken(ref CachedMessage cachedMessage) { return new EventSequenceToken(cachedMessage.SequenceNumber); } } }