context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using SIL.Windows.Forms.i18n; using SIL.Windows.Forms.Widgets; using SIL.Windows.Forms.WritingSystems.WSTree; namespace SIL.Windows.Forms.WritingSystems { partial class WritingSystemSetupView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.splitContainer2 = new System.Windows.Forms.SplitContainer(); this._treeView = new SIL.Windows.Forms.WritingSystems.WSTree.WritingSystemTreeView(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this._languageName = new SIL.Windows.Forms.Widgets.BetterLabel(); this._ietfLanguageTag = new SIL.Windows.Forms.Widgets.BetterLabel(); this._propertiesTabControl = new SIL.Windows.Forms.WritingSystems.WSPropertiesTabControl(); this._buttonBar = new SIL.Windows.Forms.WritingSystems.WSAddDuplicateMoreButtonBar(); this.localizationHelper1 = new SIL.Windows.Forms.i18n.LocalizationHelper(this.components); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.Panel2.SuspendLayout(); this.splitContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); this.splitContainer2.Panel1.SuspendLayout(); this.splitContainer2.Panel2.SuspendLayout(); this.splitContainer2.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.localizationHelper1)).BeginInit(); this.SuspendLayout(); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel2; this.splitContainer1.IsSplitterFixed = true; this.splitContainer1.Location = new System.Drawing.Point(0, 0); this.splitContainer1.Name = "splitContainer1"; this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.splitContainer2); // // splitContainer1.Panel2 // this.splitContainer1.Panel2.Controls.Add(this._buttonBar); this.splitContainer1.Size = new System.Drawing.Size(841, 461); this.splitContainer1.SplitterDistance = 422; this.splitContainer1.TabIndex = 2; // // splitContainer2 // this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer2.Location = new System.Drawing.Point(0, 0); this.splitContainer2.Name = "splitContainer2"; // // splitContainer2.Panel1 // this.splitContainer2.Panel1.Controls.Add(this._treeView); // // splitContainer2.Panel2 // this.splitContainer2.Panel2.Controls.Add(this.tableLayoutPanel1); this.splitContainer2.Panel2.Controls.Add(this._propertiesTabControl); this.splitContainer2.Size = new System.Drawing.Size(841, 422); this.splitContainer2.SplitterDistance = 222; this.splitContainer2.SplitterWidth = 10; this.splitContainer2.TabIndex = 0; // // _treeView // this._treeView.BackColor = System.Drawing.Color.White; this._treeView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this._treeView.Dock = System.Windows.Forms.DockStyle.Fill; this._treeView.Location = new System.Drawing.Point(0, 0); this._treeView.Name = "_treeView"; this._treeView.Padding = new System.Windows.Forms.Padding(10, 10, 0, 0); this._treeView.Size = new System.Drawing.Size(222, 422); this._treeView.TabIndex = 1; // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 66.66666F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 33.33333F)); this.tableLayoutPanel1.Controls.Add(this._languageName, 0, 0); this.tableLayoutPanel1.Controls.Add(this._ietfLanguageTag, 1, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3); this.tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(603, 27); this.tableLayoutPanel1.TabIndex = 3; // // _languageName // this._languageName.BorderStyle = System.Windows.Forms.BorderStyle.None; this._languageName.Dock = System.Windows.Forms.DockStyle.Fill; this._languageName.Enabled = false; this._languageName.Font = new System.Drawing.Font("Segoe UI", 9F); this._languageName.ForeColor = System.Drawing.SystemColors.ControlText; this._languageName.Location = new System.Drawing.Point(3, 3); this._languageName.Multiline = true; this._languageName.Name = "_languageName"; this._languageName.ReadOnly = true; this._languageName.Size = new System.Drawing.Size(396, 21); this._languageName.TabIndex = 1; this._languageName.TabStop = false; this._languageName.Text = "Language Name"; // // _ietfLanguageTag // this._ietfLanguageTag.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._ietfLanguageTag.BorderStyle = System.Windows.Forms.BorderStyle.None; this._ietfLanguageTag.Enabled = false; this._ietfLanguageTag.Font = new System.Drawing.Font("Segoe UI", 9F); this._ietfLanguageTag.ForeColor = System.Drawing.SystemColors.ControlText; this._ietfLanguageTag.Location = new System.Drawing.Point(405, 3); this._ietfLanguageTag.Multiline = true; this._ietfLanguageTag.Name = "_ietfLanguageTag"; this._ietfLanguageTag.ReadOnly = true; this._ietfLanguageTag.Size = new System.Drawing.Size(195, 21); this._ietfLanguageTag.TabIndex = 2; this._ietfLanguageTag.TabStop = false; this._ietfLanguageTag.Text = "foo-CN-variant1-a-extend1-x-wadefile"; this._ietfLanguageTag.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // _propertiesTabControl // this._propertiesTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._propertiesTabControl.Location = new System.Drawing.Point(0, 30); this._propertiesTabControl.Name = "_propertiesTabControl"; this._propertiesTabControl.Size = new System.Drawing.Size(609, 392); this._propertiesTabControl.TabIndex = 0; // // _buttonBar // this._buttonBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this._buttonBar.Location = new System.Drawing.Point(0, 4); this._buttonBar.Name = "_buttonBar"; this._buttonBar.Size = new System.Drawing.Size(841, 31); this._buttonBar.TabIndex = 0; // // localizationHelper1 // this.localizationHelper1.Parent = this; // // WritingSystemSetupView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer1); this.Name = "WritingSystemSetupView"; this.Size = new System.Drawing.Size(841, 461); this.splitContainer1.Panel1.ResumeLayout(false); this.splitContainer1.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.splitContainer2.Panel1.ResumeLayout(false); this.splitContainer2.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); this.splitContainer2.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.localizationHelper1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer1; private WSAddDuplicateMoreButtonBar _buttonBar; private System.Windows.Forms.SplitContainer splitContainer2; private WSPropertiesTabControl _propertiesTabControl; private WSTree.WritingSystemTreeView _treeView; private BetterLabel _ietfLanguageTag; private BetterLabel _languageName; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private LocalizationHelper localizationHelper1; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExtractMethod { internal abstract partial class MethodExtractor { protected abstract partial class Analyzer { private readonly SemanticDocument _semanticDocument; protected readonly CancellationToken CancellationToken; protected readonly SelectionResult SelectionResult; protected Analyzer(SelectionResult selectionResult, CancellationToken cancellationToken) { Contract.ThrowIfNull(selectionResult); this.SelectionResult = selectionResult; _semanticDocument = selectionResult.SemanticDocument; this.CancellationToken = cancellationToken; } /// <summary> /// convert text span to node range for the flow analysis API /// </summary> protected abstract Tuple<SyntaxNode, SyntaxNode> GetFlowAnalysisNodeRange(); /// <summary> /// check whether selection contains return statement or not /// </summary> protected abstract bool ContainsReturnStatementInSelectedCode(IEnumerable<SyntaxNode> jumpOutOfRegionStatements); /// <summary> /// create VariableInfo type /// </summary> protected abstract VariableInfo CreateFromSymbol(Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle variableStyle, bool variableDeclared); /// <summary> /// among variables that will be used as parameters at the extracted method, check whether one of the parameter can be used as return /// </summary> protected abstract int GetIndexOfVariableInfoToUseAsReturnValue(IList<VariableInfo> variableInfo); /// <summary> /// get type of the range variable symbol /// </summary> protected abstract ITypeSymbol GetRangeVariableType(SemanticModel model, IRangeVariableSymbol symbol); /// <summary> /// check whether the selection is at the placed where read-only field is allowed to be extracted out /// </summary> /// <returns></returns> protected abstract bool ReadOnlyFieldAllowed(); public async Task<AnalyzerResult> AnalyzeAsync() { // do data flow analysis var model = _semanticDocument.SemanticModel; var dataFlowAnalysisData = GetDataFlowAnalysisData(model); // build symbol map for the identifiers used inside of the selection var symbolMap = GetSymbolMap(model); // gather initial local or parameter variable info var variableInfoMap = GenerateVariableInfoMap(model, dataFlowAnalysisData, symbolMap); // check whether instance member is used inside of the selection var instanceMemberIsUsed = IsInstanceMemberUsedInSelectedCode(dataFlowAnalysisData); // check whether end of selection is reachable var endOfSelectionReachable = IsEndOfSelectionReachable(model); // collects various variable informations // extracted code contains return value var isInExpressionOrHasReturnStatement = IsInExpressionOrHasReturnStatement(model); var signatureTuple = GetSignatureInformation(dataFlowAnalysisData, variableInfoMap, isInExpressionOrHasReturnStatement); var parameters = signatureTuple.Item1; var returnType = signatureTuple.Item2; var variableToUseAsReturnValue = signatureTuple.Item3; var unsafeAddressTakenUsed = signatureTuple.Item4; var returnTypeTuple = AdjustReturnType(model, returnType); returnType = returnTypeTuple.Item1; bool returnTypeHasAnonymousType = returnTypeTuple.Item2; bool awaitTaskReturn = returnTypeTuple.Item3; // create new document var newDocument = await CreateDocumentWithAnnotationsAsync(_semanticDocument, parameters, CancellationToken).ConfigureAwait(false); // collect method type variable used in selected code var sortedMap = new SortedDictionary<int, ITypeParameterSymbol>(); var typeParametersInConstraintList = GetMethodTypeParametersInConstraintList(model, variableInfoMap, symbolMap, sortedMap); var typeParametersInDeclaration = GetMethodTypeParametersInDeclaration(returnType, sortedMap); // check various error cases var operationStatus = GetOperationStatus(model, symbolMap, parameters, unsafeAddressTakenUsed, returnTypeHasAnonymousType); return new AnalyzerResult( newDocument, typeParametersInDeclaration, typeParametersInConstraintList, parameters, variableToUseAsReturnValue, returnType, awaitTaskReturn, instanceMemberIsUsed, endOfSelectionReachable, operationStatus); } private Tuple<ITypeSymbol, bool, bool> AdjustReturnType(SemanticModel model, ITypeSymbol returnType) { // check whether return type contains anonymous type and if it does, fix it up by making it object var returnTypeHasAnonymousType = returnType.ContainsAnonymousType(); returnType = returnTypeHasAnonymousType ? returnType.RemoveAnonymousTypes(model.Compilation) : returnType; // if selection contains await which is not under async lambda or anonymous delegate, // change return type to be wrapped in Task var shouldPutAsyncModifier = this.SelectionResult.ShouldPutAsyncModifier(); if (shouldPutAsyncModifier) { WrapReturnTypeInTask(model, ref returnType, out var awaitTaskReturn); return Tuple.Create(returnType, returnTypeHasAnonymousType, awaitTaskReturn); } // unwrap task if needed UnwrapTaskIfNeeded(model, ref returnType); return Tuple.Create(returnType, returnTypeHasAnonymousType, false); } private void UnwrapTaskIfNeeded(SemanticModel model, ref ITypeSymbol returnType) { // nothing to unwrap if (!this.SelectionResult.ContainingScopeHasAsyncKeyword() || !this.ContainsReturnStatementInSelectedCode(model)) { return; } var originalDefinition = returnType.OriginalDefinition; // see whether it needs to be unwrapped var taskType = model.Compilation.TaskType(); if (originalDefinition.Equals(taskType)) { returnType = model.Compilation.GetSpecialType(SpecialType.System_Void); return; } var genericTaskType = model.Compilation.TaskOfTType(); if (originalDefinition.Equals(genericTaskType)) { returnType = ((INamedTypeSymbol)returnType).TypeArguments[0]; return; } // nothing to unwrap return; } private void WrapReturnTypeInTask(SemanticModel model, ref ITypeSymbol returnType, out bool awaitTaskReturn) { awaitTaskReturn = false; var genericTaskType = model.Compilation.TaskOfTType(); var taskType = model.Compilation.TaskType(); if (returnType.Equals(model.Compilation.GetSpecialType(SpecialType.System_Void))) { // convert void to Task type awaitTaskReturn = true; returnType = taskType; return; } if (this.SelectionResult.SelectionInExpression) { returnType = genericTaskType.Construct(returnType); return; } if (ContainsReturnStatementInSelectedCode(model)) { // check whether we will use return type as it is or not. awaitTaskReturn = returnType.Equals(taskType); return; } // okay, wrap the return type in Task<T> returnType = genericTaskType.Construct(returnType); } private Tuple<IList<VariableInfo>, ITypeSymbol, VariableInfo, bool> GetSignatureInformation( DataFlowAnalysis dataFlowAnalysisData, IDictionary<ISymbol, VariableInfo> variableInfoMap, bool isInExpressionOrHasReturnStatement) { var model = _semanticDocument.SemanticModel; var compilation = model.Compilation; if (isInExpressionOrHasReturnStatement) { // check whether current selection contains return statement var parameters = GetMethodParameters(variableInfoMap.Values); var returnType = SelectionResult.GetContainingScopeType() ?? compilation.GetSpecialType(SpecialType.System_Object); var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys); return Tuple.Create(parameters, returnType, default(VariableInfo), unsafeAddressTakenUsed); } else { // no return statement var parameters = MarkVariableInfoToUseAsReturnValueIfPossible(GetMethodParameters(variableInfoMap.Values)); var variableToUseAsReturnValue = parameters.FirstOrDefault(v => v.UseAsReturnValue); var returnType = variableToUseAsReturnValue != null ? variableToUseAsReturnValue.GetVariableType(_semanticDocument) : compilation.GetSpecialType(SpecialType.System_Void); var unsafeAddressTakenUsed = ContainsVariableUnsafeAddressTaken(dataFlowAnalysisData, variableInfoMap.Keys); return Tuple.Create(parameters, returnType, variableToUseAsReturnValue, unsafeAddressTakenUsed); } } private bool IsInExpressionOrHasReturnStatement(SemanticModel model) { var isInExpressionOrHasReturnStatement = this.SelectionResult.SelectionInExpression; if (!isInExpressionOrHasReturnStatement) { var containsReturnStatement = ContainsReturnStatementInSelectedCode(model); isInExpressionOrHasReturnStatement |= containsReturnStatement; } return isInExpressionOrHasReturnStatement; } private OperationStatus GetOperationStatus( SemanticModel model, Dictionary<ISymbol, List<SyntaxToken>> symbolMap, IList<VariableInfo> parameters, bool unsafeAddressTakenUsed, bool returnTypeHasAnonymousType) { var readonlyFieldStatus = CheckReadOnlyFields(model, symbolMap); var namesWithAnonymousTypes = parameters.Where(v => v.OriginalTypeHadAnonymousTypeOrDelegate).Select(v => v.Name ?? string.Empty); if (returnTypeHasAnonymousType) { namesWithAnonymousTypes = namesWithAnonymousTypes.Concat("return type"); } var anonymousTypeStatus = namesWithAnonymousTypes.Any() ? new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Parameters_type_or_return_type_cannot_be_an_anonymous_type_colon_bracket_0_bracket, string.Join(", ", namesWithAnonymousTypes))) : OperationStatus.Succeeded; var unsafeAddressStatus = unsafeAddressTakenUsed ? OperationStatus.UnsafeAddressTaken : OperationStatus.Succeeded; var asyncRefOutParameterStatue = CheckAsyncMethodRefOutParameters(parameters); return readonlyFieldStatus.With(anonymousTypeStatus).With(unsafeAddressStatus).With(asyncRefOutParameterStatue); } private OperationStatus CheckAsyncMethodRefOutParameters(IList<VariableInfo> parameters) { if (this.SelectionResult.ShouldPutAsyncModifier()) { var names = parameters.Where(v => !v.UseAsReturnValue && (v.ParameterModifier == ParameterBehavior.Out || v.ParameterModifier == ParameterBehavior.Ref)) .Select(p => p.Name ?? string.Empty); if (names.Any()) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Asynchronous_method_cannot_have_ref_out_parameters_colon_bracket_0_bracket, string.Join(", ", names))); } } return OperationStatus.Succeeded; } private Task<SemanticDocument> CreateDocumentWithAnnotationsAsync(SemanticDocument document, IList<VariableInfo> variables, CancellationToken cancellationToken) { var annotations = new List<Tuple<SyntaxToken, SyntaxAnnotation>>(variables.Count); variables.Do(v => v.AddIdentifierTokenAnnotationPair(annotations, cancellationToken)); if (annotations.Count == 0) { return Task.FromResult(document); } return document.WithSyntaxRootAsync(document.Root.AddAnnotations(annotations), cancellationToken); } private Dictionary<ISymbol, List<SyntaxToken>> GetSymbolMap(SemanticModel model) { var syntaxFactsService = _semanticDocument.Document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var context = this.SelectionResult.GetContainingScope(); var symbolMap = SymbolMapBuilder.Build(syntaxFactsService, model, context, this.SelectionResult.FinalSpan, CancellationToken); return symbolMap; } private bool ContainsVariableUnsafeAddressTaken(DataFlowAnalysis dataFlowAnalysisData, IEnumerable<ISymbol> symbols) { // check whether the selection contains "&" over a symbol exist var map = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken); return symbols.Any(s => map.Contains(s)); } private DataFlowAnalysis GetDataFlowAnalysisData(SemanticModel model) { if (this.SelectionResult.SelectionInExpression) { return model.AnalyzeDataFlow(this.SelectionResult.GetContainingScope()); } var pair = GetFlowAnalysisNodeRange(); return model.AnalyzeDataFlow(pair.Item1, pair.Item2); } private bool IsEndOfSelectionReachable(SemanticModel model) { if (this.SelectionResult.SelectionInExpression) { return true; } var pair = GetFlowAnalysisNodeRange(); var analysis = model.AnalyzeControlFlow(pair.Item1, pair.Item2); return analysis.EndPointIsReachable; } private IList<VariableInfo> MarkVariableInfoToUseAsReturnValueIfPossible(IList<VariableInfo> variableInfo) { var variableToUseAsReturnValueIndex = GetIndexOfVariableInfoToUseAsReturnValue(variableInfo); if (variableToUseAsReturnValueIndex >= 0) { variableInfo[variableToUseAsReturnValueIndex] = VariableInfo.CreateReturnValue(variableInfo[variableToUseAsReturnValueIndex]); } return variableInfo; } private IList<VariableInfo> GetMethodParameters(ICollection<VariableInfo> variableInfo) { var list = new List<VariableInfo>(variableInfo); VariableInfo.SortVariables(_semanticDocument.SemanticModel.Compilation, list); return list; } private IDictionary<ISymbol, VariableInfo> GenerateVariableInfoMap( SemanticModel model, DataFlowAnalysis dataFlowAnalysisData, Dictionary<ISymbol, List<SyntaxToken>> symbolMap) { Contract.ThrowIfNull(model); Contract.ThrowIfNull(dataFlowAnalysisData); var variableInfoMap = new Dictionary<ISymbol, VariableInfo>(); // create map of each data var capturedMap = new HashSet<ISymbol>(dataFlowAnalysisData.Captured); var dataFlowInMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsIn); var dataFlowOutMap = new HashSet<ISymbol>(dataFlowAnalysisData.DataFlowsOut); var alwaysAssignedMap = new HashSet<ISymbol>(dataFlowAnalysisData.AlwaysAssigned); var variableDeclaredMap = new HashSet<ISymbol>(dataFlowAnalysisData.VariablesDeclared); var readInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadInside); var writtenInsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenInside); var readOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.ReadOutside); var writtenOutsideMap = new HashSet<ISymbol>(dataFlowAnalysisData.WrittenOutside); var unsafeAddressTakenMap = new HashSet<ISymbol>(dataFlowAnalysisData.UnsafeAddressTaken); // gather all meaningful symbols for the span. var candidates = new HashSet<ISymbol>(readInsideMap); candidates.UnionWith(writtenInsideMap); candidates.UnionWith(variableDeclaredMap); foreach (var symbol in candidates) { if (IsThisParameter(symbol) || IsInteractiveSynthesizedParameter(symbol)) { continue; } var captured = capturedMap.Contains(symbol); var dataFlowIn = dataFlowInMap.Contains(symbol); var dataFlowOut = dataFlowOutMap.Contains(symbol); var alwaysAssigned = alwaysAssignedMap.Contains(symbol); var variableDeclared = variableDeclaredMap.Contains(symbol); var readInside = readInsideMap.Contains(symbol); var writtenInside = writtenInsideMap.Contains(symbol); var readOutside = readOutsideMap.Contains(symbol); var writtenOutside = writtenOutsideMap.Contains(symbol); var unsafeAddressTaken = unsafeAddressTakenMap.Contains(symbol); // if it is static local, make sure it is not defined inside if (symbol.IsStatic) { dataFlowIn = dataFlowIn && !variableDeclared; } // make sure readoutside is true when dataflowout is true (bug #3790) // when a variable is only used inside of loop, a situation where dataflowout == true and readOutside == false // can happen. but for extract method's point of view, this is not an information that would affect output. // so, here we adjust flags to follow predefined assumption. readOutside = readOutside || dataFlowOut; // make sure data flow out is true when declared inside/written inside/read outside/not written outside are true (bug #6277) dataFlowOut = dataFlowOut || (variableDeclared && writtenInside && readOutside && !writtenOutside); // variable that is declared inside but never referenced outside. just ignore it and move to next one. if (variableDeclared && !dataFlowOut && !readOutside && !writtenOutside) { continue; } // parameter defined inside of the selection (such as lambda parameter) will be ignored (bug # 10964) if (symbol is IParameterSymbol && variableDeclared) { continue; } var type = GetSymbolType(model, symbol); if (type == null) { continue; } var variableStyle = GetVariableStyle(symbolMap, symbol, model, type, captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken); AddVariableToMap(variableInfoMap, symbol, CreateFromSymbol(model.Compilation, symbol, type, variableStyle, variableDeclared)); } return variableInfoMap; } private void AddVariableToMap(IDictionary<ISymbol, VariableInfo> variableInfoMap, ISymbol localOrParameter, VariableInfo variableInfo) { variableInfoMap.Add(localOrParameter, variableInfo); } private VariableStyle GetVariableStyle( Dictionary<ISymbol, List<SyntaxToken>> symbolMap, ISymbol symbol, SemanticModel model, ITypeSymbol type, bool captured, bool dataFlowIn, bool dataFlowOut, bool alwaysAssigned, bool variableDeclared, bool readInside, bool writtenInside, bool readOutside, bool writtenOutside, bool unsafeAddressTaken) { Contract.ThrowIfNull(model); Contract.ThrowIfNull(type); var style = ExtractMethodMatrix.GetVariableStyle(captured, dataFlowIn, dataFlowOut, alwaysAssigned, variableDeclared, readInside, writtenInside, readOutside, writtenOutside, unsafeAddressTaken); if (SelectionContainsOnlyIdentifierWithSameType(type)) { return style; } if (UserDefinedValueType(model.Compilation, type) && !this.SelectionResult.DontPutOutOrRefOnStruct) { return AlwaysReturn(style); } // for captured variable, never try to move the decl into extracted method if (captured && (style == VariableStyle.MoveIn)) { return VariableStyle.Out; } // check special value type cases if (type.IsValueType && !IsWrittenInsideForFrameworkValueType(symbolMap, model, symbol, writtenInside)) { return style; } // don't blindly always return. make sure there is a write inside of the selection if (this.SelectionResult.AllowMovingDeclaration || !writtenInside) { return style; } return AlwaysReturn(style); } private bool IsWrittenInsideForFrameworkValueType( Dictionary<ISymbol, List<SyntaxToken>> symbolMap, SemanticModel model, ISymbol symbol, bool writtenInside) { if (!symbolMap.TryGetValue(symbol, out var tokens)) { return writtenInside; } // this relies on the fact that our IsWrittenTo only cares about syntax to figure out whether // something is written to or not. but not semantic. // we probably need to move the API to syntaxFact service not semanticFact. // // if one wants to get result that also considers semantic, he should use data control flow analysis API. var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); return tokens.Any(t => semanticFacts.IsWrittenTo(model, t.Parent, CancellationToken.None)); } private bool SelectionContainsOnlyIdentifierWithSameType(ITypeSymbol type) { if (!this.SelectionResult.SelectionInExpression) { return false; } var firstToken = this.SelectionResult.GetFirstTokenInSelection(); var lastToken = this.SelectionResult.GetLastTokenInSelection(); if (!firstToken.Equals(lastToken)) { return false; } return type.Equals(this.SelectionResult.GetContainingScopeType()); } private bool UserDefinedValueType(Compilation compilation, ITypeSymbol type) { if (!type.IsValueType || type.IsPointerType() || type.IsEnumType()) { return false; } return type.OriginalDefinition.SpecialType == SpecialType.None && !WellKnownFrameworkValueType(compilation, type); } private bool WellKnownFrameworkValueType(Compilation compilation, ITypeSymbol type) { if (!type.IsValueType) { return false; } var cancellationTokenType = compilation.GetTypeByMetadataName(typeof(CancellationToken).FullName); if (cancellationTokenType != null && cancellationTokenType.Equals(type)) { return true; } return false; } private ITypeSymbol GetSymbolType(SemanticModel model, ISymbol symbol) { var local = symbol as ILocalSymbol; if (local != null) { return local.Type; } var parameter = symbol as IParameterSymbol; if (parameter != null) { return parameter.Type; } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { return GetRangeVariableType(model, rangeVariable); } return Contract.FailWithReturn<ITypeSymbol>("Shouldn't reach here"); } protected VariableStyle AlwaysReturn(VariableStyle style) { if (style == VariableStyle.InputOnly) { return VariableStyle.Ref; } if (style == VariableStyle.MoveIn) { return VariableStyle.Out; } if (style == VariableStyle.SplitIn) { return VariableStyle.Out; } if (style == VariableStyle.SplitOut) { return VariableStyle.OutWithMoveOut; } return style; } private bool IsParameterUsedOutside(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.RefKind != RefKind.None; } private bool IsParameterAssigned(ISymbol localOrParameter) { // hack for now. var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.RefKind != RefKind.Out; } private bool IsThisParameter(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.IsThis; } private bool IsInteractiveSynthesizedParameter(ISymbol localOrParameter) { var parameter = localOrParameter as IParameterSymbol; if (parameter == null) { return false; } return parameter.IsImplicitlyDeclared && parameter.ContainingAssembly.IsInteractive && parameter.ContainingSymbol != null && parameter.ContainingSymbol.ContainingType != null && parameter.ContainingSymbol.ContainingType.IsScriptClass; } private bool ContainsReturnStatementInSelectedCode(SemanticModel model) { Contract.ThrowIfTrue(this.SelectionResult.SelectionInExpression); var pair = GetFlowAnalysisNodeRange(); var controlFlowAnalysisData = model.AnalyzeControlFlow(pair.Item1, pair.Item2); return ContainsReturnStatementInSelectedCode(controlFlowAnalysisData.ExitPoints); } private void AddTypeParametersToMap(IEnumerable<ITypeParameterSymbol> typeParameters, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var typeParameter in typeParameters) { AddTypeParameterToMap(typeParameter, sortedMap); } } private void AddTypeParameterToMap(ITypeParameterSymbol typeParameter, IDictionary<int, ITypeParameterSymbol> sortedMap) { if (typeParameter == null || typeParameter.DeclaringMethod == null || sortedMap.ContainsKey(typeParameter.Ordinal)) { return; } sortedMap[typeParameter.Ordinal] = typeParameter; } private void AppendMethodTypeVariableFromDataFlowAnalysis( SemanticModel model, IDictionary<ISymbol, VariableInfo> variableInfoMap, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var symbol in variableInfoMap.Keys) { var parameter = symbol as IParameterSymbol; if (parameter != null) { AddTypeParametersToMap(TypeParameterCollector.Collect(parameter.Type), sortedMap); continue; } var local = symbol as ILocalSymbol; if (local != null) { AddTypeParametersToMap(TypeParameterCollector.Collect(local.Type), sortedMap); continue; } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { var type = GetRangeVariableType(model, rangeVariable); AddTypeParametersToMap(TypeParameterCollector.Collect(type), sortedMap); continue; } Contract.Fail(FeaturesResources.Unknown_symbol_kind); } } private void AppendMethodTypeParameterFromConstraint(SortedDictionary<int, ITypeParameterSymbol> sortedMap) { var typeParametersInConstraint = new List<ITypeParameterSymbol>(); // collect all type parameter appears in constraint foreach (var typeParameter in sortedMap.Values) { var constraintTypes = typeParameter.ConstraintTypes; if (constraintTypes.IsDefaultOrEmpty) { continue; } foreach (var type in constraintTypes) { // constraint itself is type parameter typeParametersInConstraint.AddRange(TypeParameterCollector.Collect(type)); } } // pick up only valid type parameter and add them to the map foreach (var typeParameter in typeParametersInConstraint) { AddTypeParameterToMap(typeParameter, sortedMap); } } private void AppendMethodTypeParameterUsedDirectly(IDictionary<ISymbol, List<SyntaxToken>> symbolMap, IDictionary<int, ITypeParameterSymbol> sortedMap) { foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.TypeParameter)) { var typeParameter = pair.Key as ITypeParameterSymbol; if (typeParameter.DeclaringMethod == null || sortedMap.ContainsKey(typeParameter.Ordinal)) { continue; } sortedMap[typeParameter.Ordinal] = typeParameter; } } private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInConstraintList( SemanticModel model, IDictionary<ISymbol, VariableInfo> variableInfoMap, IDictionary<ISymbol, List<SyntaxToken>> symbolMap, SortedDictionary<int, ITypeParameterSymbol> sortedMap) { // find starting points AppendMethodTypeVariableFromDataFlowAnalysis(model, variableInfoMap, sortedMap); AppendMethodTypeParameterUsedDirectly(symbolMap, sortedMap); // recursively dive into constraints to find all constraints needed AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(sortedMap); return sortedMap.Values.ToList(); } private void AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(SortedDictionary<int, ITypeParameterSymbol> sortedMap) { var visited = new HashSet<ITypeSymbol>(); var candidates = SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); // collect all type parameter appears in constraint foreach (var typeParameter in sortedMap.Values) { var constraintTypes = typeParameter.ConstraintTypes; if (constraintTypes.IsDefaultOrEmpty) { continue; } foreach (var type in constraintTypes) { candidates = candidates.Concat(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(type, visited)); } } // pick up only valid type parameter and add them to the map foreach (var typeParameter in candidates) { AddTypeParameterToMap(typeParameter, sortedMap); } } private IEnumerable<ITypeParameterSymbol> AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints( ITypeSymbol type, HashSet<ITypeSymbol> visited) { if (visited.Contains(type)) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } visited.Add(type); if (type.OriginalDefinition.Equals(type)) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } var constructedType = type as INamedTypeSymbol; if (constructedType == null) { return SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>(); } var parameters = constructedType.GetAllTypeParameters().ToList(); var arguments = constructedType.GetAllTypeArguments().ToList(); Contract.ThrowIfFalse(parameters.Count == arguments.Count); var typeParameters = new List<ITypeParameterSymbol>(); for (int i = 0; i < parameters.Count; i++) { var parameter = parameters[i]; var argument = arguments[i] as ITypeParameterSymbol; if (argument != null) { // no constraint, nothing to do if (!parameter.HasConstructorConstraint && !parameter.HasReferenceTypeConstraint && !parameter.HasValueTypeConstraint && parameter.ConstraintTypes.IsDefaultOrEmpty) { continue; } typeParameters.Add(argument); continue; } var candidate = arguments[i] as INamedTypeSymbol; if (candidate == null) { continue; } typeParameters.AddRange(AppendTypeParametersInConstraintsUsedByConstructedTypeWithItsOwnConstraints(candidate, visited)); } return typeParameters; } private IEnumerable<ITypeParameterSymbol> GetMethodTypeParametersInDeclaration(ITypeSymbol returnType, SortedDictionary<int, ITypeParameterSymbol> sortedMap) { // add return type to the map AddTypeParametersToMap(TypeParameterCollector.Collect(returnType), sortedMap); AppendMethodTypeParameterFromConstraint(sortedMap); return sortedMap.Values.ToList(); } private OperationStatus CheckReadOnlyFields(SemanticModel semanticModel, Dictionary<ISymbol, List<SyntaxToken>> symbolMap) { if (ReadOnlyFieldAllowed()) { return OperationStatus.Succeeded; } List<string> names = null; var semanticFacts = _semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); foreach (var pair in symbolMap.Where(p => p.Key.Kind == SymbolKind.Field)) { var field = (IFieldSymbol)pair.Key; if (!field.IsReadOnly) { continue; } var tokens = pair.Value; if (tokens.All(t => !semanticFacts.IsWrittenTo(semanticModel, t.Parent, CancellationToken))) { continue; } names = names ?? new List<string>(); names.Add(field.Name ?? string.Empty); } if (names != null) { return new OperationStatus(OperationStatusFlag.BestEffort, string.Format(FeaturesResources.Assigning_to_readonly_fields_must_be_done_in_a_constructor_colon_bracket_0_bracket, string.Join(", ", names))); } return OperationStatus.Succeeded; } private bool IsInstanceMemberUsedInSelectedCode(DataFlowAnalysis dataFlowAnalysisData) { Contract.ThrowIfNull(dataFlowAnalysisData); // "this" can be used as a lvalue in a struct, check WrittenInside as well return dataFlowAnalysisData.ReadInside.Any(s => IsThisParameter(s)) || dataFlowAnalysisData.WrittenInside.Any(s => IsThisParameter(s)); } protected VariableInfo CreateFromSymbolCommon<T>( Compilation compilation, ISymbol symbol, ITypeSymbol type, VariableStyle style, HashSet<int> nonNoisySyntaxKindSet) where T : SyntaxNode { var local = symbol as ILocalSymbol; if (local != null) { return new VariableInfo( new LocalVariableSymbol<T>(compilation, local, type, nonNoisySyntaxKindSet), style); } var parameter = symbol as IParameterSymbol; if (parameter != null) { return new VariableInfo(new ParameterVariableSymbol(compilation, parameter, type), style); } var rangeVariable = symbol as IRangeVariableSymbol; if (rangeVariable != null) { return new VariableInfo(new QueryVariableSymbol(compilation, rangeVariable, type), style); } return Contract.FailWithReturn<VariableInfo>(FeaturesResources.Unknown); } } } }
// // DaapService.cs // // Authors: // Alexander Hixon <[email protected]> // // Copyright (C) 2008 Alexander Hixon // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using Mono.Unix; using NativeDaap = Daap; using Daap; using Gtk; using Hyena; using Banshee.Collection; using Banshee.Gui; using Banshee.Sources; using Banshee.ServiceStack; namespace Banshee.Daap { public class DaapService : IExtensionService, IDisposable, IDelayedInitializeService { private ServiceLocator locator; private DateTime locator_started; private static DaapProxyWebServer proxy_server; private DaapContainerSource container; private Dictionary<string, DaapSource> source_map; private uint actions_id; internal static DaapProxyWebServer ProxyServer { get { return proxy_server; } } void IExtensionService.Initialize () { } public void Dispose () { if (locator != null) { locator.Stop (); locator.Found -= OnServiceFound; locator.Removed -= OnServiceRemoved; locator = null; } if (proxy_server != null) { proxy_server.Stop (); proxy_server = null; } var uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service != null) { uia_service.UIManager.RemoveUi (actions_id); uia_service.GlobalActions.Remove ("AddRemoteDaapServerAction"); } // Dispose any remaining child sources if (source_map != null) { foreach (KeyValuePair <string, DaapSource> kv in source_map) { if (kv.Value != null) { kv.Value.Disconnect (true); kv.Value.Dispose (); } } source_map.Clear (); } if (container != null) { ServiceManager.SourceManager.RemoveSource (container, true); container = null; } } private void OnServiceFound (object o, ServiceArgs args) { AddDaapServer (args.Service); } private void AddDaapServer (Service service) { ThreadAssist.ProxyToMain (delegate { DaapSource source = new DaapSource (service); string key = String.Format ("{0}:{1}", service.Name, service.Port); if (source_map.Count == 0) { ServiceManager.SourceManager.AddSource (container); } if (source_map.ContainsKey (key)) { // Received new connection info for service container.RemoveChildSource (source_map [key]); source_map [key] = source; } else { // New service information source_map.Add (key, source); } container.AddChildSource (source); // Don't flash shares we find on startup (well, within 5s of startup) if ((DateTime.Now - locator_started).TotalSeconds > 5) { source.NotifyUser (); } }); } private void OnServiceRemoved (object o, ServiceArgs args) { ThreadAssist.ProxyToMain (delegate { string key = String.Format ("{0}:{1}", args.Service.Name, args.Service.Port); DaapSource source = source_map [key]; source.Disconnect (true); container.RemoveChildSource (source); source_map.Remove (key); if (source_map.Count == 0) { ServiceManager.SourceManager.RemoveSource (container); } }); } public void DelayedInitialize () { ThreadAssist.SpawnFromMain (ThreadedInitialize); } public void ThreadedInitialize () { // Add the source, even though its empty, so that the user sees the // plugin is enabled, just no child sources yet. source_map = new Dictionary<string, DaapSource> (); container = new DaapContainerSource (); try { // Now start looking for services. // We do this after creating the source because if we do it before // there's a race condition where we get a service before the source // is added. locator = new ServiceLocator (); locator.Found += OnServiceFound; locator.Removed += OnServiceRemoved; locator.ShowLocalServices = true; locator_started = DateTime.Now; locator.Start (); proxy_server = new DaapProxyWebServer (); proxy_server.Start (); } catch (Exception e) { Log.Exception ("Failed to start DAAP client", e); } var uia_service = ServiceManager.Get<InterfaceActionService> (); if (uia_service != null) { uia_service.GlobalActions.Add ( new ActionEntry ("AddRemoteDaapServerAction", Stock.Add, Catalog.GetString ("Add Remote DAAP Server"), null, Catalog.GetString ("Add a new remote DAAP server"), OnAddRemoteServer) ); actions_id = uia_service.UIManager.AddUiFromResource ("GlobalUI.xml"); } } private void OnAddRemoteServer (object o, EventArgs args) { ResponseType response; string s_address; ushort port; using (OpenRemoteServer dialog = new OpenRemoteServer ()) { response = (ResponseType) dialog.Run (); s_address = dialog.Address; port = (ushort) dialog.Port; dialog.Destroy (); } if (response != ResponseType.Ok) return; Log.DebugFormat ("Trying to add DAAP server on {0}:{1}", s_address, port); IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry (s_address); } catch (SocketException) { Log.Warning ("Unable to resolve host " + s_address); return; } IPAddress address = hostEntry.AddressList[0]; foreach (IPAddress curAdd in hostEntry.AddressList) { if (curAdd.AddressFamily == AddressFamily.InterNetwork) { address = curAdd; } } Log.DebugFormat (String.Format("Resolved {0} to {1}", s_address, address)); Log.Debug ("Spawning daap resolving thread"); DaapResolverJob job = new DaapResolverJob(s_address, address, port); job.Finished += delegate { Service service = job.DaapService; if (service != null) { AddDaapServer (service); Log.DebugFormat ("Created server {0}", service.Name); } else { Log.DebugFormat ("Unable to create service for {0}", s_address); } }; ServiceManager.JobScheduler.Add (job); } string IService.ServiceName { get { return "DaapService"; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Signum.Engine.Basics; using Signum.Engine.DynamicQuery; using Signum.Engine.Maps; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.DynamicQuery; using Signum.Utilities; using Signum.Utilities.ExpressionTrees; using Signum.Entities.Isolation; using Signum.Entities.Templating; using Signum.Engine.UserAssets; using Signum.Entities.SMS; using System.Globalization; namespace Signum.Engine.SMS { public interface ISMSModel { Entity UntypedEntity { get; } List<Filter> GetFilters(QueryDescription qd); Pagination GetPagination(); List<Order> GetOrders(QueryDescription queryDescription); } public abstract class SMSModel<T> : ISMSModel where T : Entity { public SMSModel(T entity) { this.Entity = entity; } public T Entity { get; set; } Entity ISMSModel.UntypedEntity { get { return Entity; } } public virtual List<Filter> GetFilters(QueryDescription qd) { var imp = qd.Columns.SingleEx(a => a.IsEntity).Implementations!.Value; if (imp.IsByAll && typeof(Entity).IsAssignableFrom(typeof(T)) || imp.Types.Contains(typeof(T))) return new List<Filter> { new FilterCondition(QueryUtils.Parse("Entity", qd, 0), FilterOperation.EqualTo, Entity.ToLite()) }; throw new InvalidOperationException($"Since {typeof(T).Name} is not in {imp}, it's necessary to override ${nameof(GetFilters)} in ${this.GetType().Name}"); } public virtual List<Order> GetOrders(QueryDescription queryDescription) { return new List<Order>(); } public virtual Pagination GetPagination() { return new Pagination.All(); } } public static class SMSModelLogic { class SMSModelInfo { public object QueryName; public Func<SMSTemplateEntity>? DefaultTemplateConstructor; public SMSModelInfo(object queryName) { QueryName = queryName; } } static ResetLazy<Dictionary<Lite<SMSModelEntity>, List<SMSTemplateEntity>>> SMSModelToTemplates = null!; static Dictionary<Type, SMSModelInfo> registeredModels = new Dictionary<Type, SMSModelInfo>(); static ResetLazy<Dictionary<Type, SMSModelEntity>> typeToEntity = null!; static ResetLazy<Dictionary<SMSModelEntity, Type>> entityToType = null!; public static void Start(SchemaBuilder sb) { if (sb.NotDefined(MethodInfo.GetCurrentMethod())) { sb.Schema.Generating += Schema_Generating; sb.Schema.Synchronizing += Schema_Synchronizing; sb.Include<SMSModelEntity>() .WithQuery(() => model => new { Entity = model, model.Id, model.FullClassName, }); new Graph<SMSTemplateEntity>.ConstructFrom<SMSModelEntity>(SMSTemplateOperation.CreateSMSTemplateFromModel) { Construct = (model, _) => CreateDefaultTemplate(model) }.Register(); SMSModelToTemplates = sb.GlobalLazy(() => ( from et in Database.Query<SMSTemplateEntity>() where et.Model != null select KeyValuePair.Create(et.Model!.ToLite(), et)) .GroupToDictionary(), new InvalidateWith(typeof(SMSTemplateEntity), typeof(SMSModelEntity))); typeToEntity = sb.GlobalLazy(() => { var dbModels = Database.RetrieveAll<SMSModelEntity>(); return EnumerableExtensions.JoinRelaxed( dbModels, registeredModels.Keys, entity => entity.FullClassName, type => type.FullName, (entity, type) => KeyValuePair.Create(type, entity), "caching " + nameof(SMSModelEntity)) .ToDictionary(); }, new InvalidateWith(typeof(SMSModelEntity))); sb.Schema.Initializing += () => typeToEntity.Load(); entityToType = sb.GlobalLazy(() => typeToEntity.Value.Inverse(), new InvalidateWith(typeof(SMSModelEntity))); } } static readonly string SMSModelReplacementKey = "SMSModel"; static SqlPreCommand? Schema_Synchronizing(Replacements replacements) { Table table = Schema.Current.Table<SMSModelEntity>(); Dictionary<string, SMSModelEntity> should = GenerateSMSModelEntities().ToDictionary(s => s.FullClassName); Dictionary<string, SMSModelEntity> old = Administrator.TryRetrieveAll<SMSModelEntity>(replacements).ToDictionary(c => c.FullClassName); replacements.AskForReplacements( old.Keys.ToHashSet(), should.Keys.ToHashSet(), SMSModelReplacementKey); Dictionary<string, SMSModelEntity> current = replacements.ApplyReplacementsToOld(old, SMSModelReplacementKey); using (replacements.WithReplacedDatabaseName()) return Synchronizer.SynchronizeScript(Spacing.Double, should, current, createNew: (tn, s) => table.InsertSqlSync(s), removeOld: (tn, c) => table.DeleteSqlSync(c, se => se.FullClassName == c.FullClassName), mergeBoth: (tn, s, c) => { var oldClassName = c.FullClassName; c.FullClassName = s.FullClassName; return table.UpdateSqlSync(c, se => se.FullClassName == c.FullClassName, comment: oldClassName); }); } public static void RegisterSMSModel<T>(Func<SMSTemplateEntity> defaultTemplateConstructor, object? queryName = null) where T : ISMSModel { RegisterSMSModel(typeof(T), defaultTemplateConstructor, queryName); } public static void RegisterSMSModel(Type model, Func<SMSTemplateEntity> defaultTemplateConstructor, object? queryName = null) { if (defaultTemplateConstructor == null) throw new ArgumentNullException(nameof(defaultTemplateConstructor)); registeredModels[model] = new SMSModelInfo(queryName ?? GetEntityType(model)) { DefaultTemplateConstructor = defaultTemplateConstructor, }; } public static Type GetEntityType(Type model) { var baseType = model.Follow(a => a.BaseType).FirstOrDefault(b => b.IsInstantiationOf(typeof(SMSModel<>))); if (baseType != null) { return baseType.GetGenericArguments()[0]; } throw new InvalidOperationException("Unknown queryName from {0}, set the argument queryName in RegisterSMSModel".FormatWith(model.TypeName())); } internal static List<SMSModelEntity> GenerateSMSModelEntities() { var list = (from type in registeredModels.Keys select new SMSModelEntity { FullClassName = type.FullName! }).ToList(); return list; } static SqlPreCommand? Schema_Generating() { Table table = Schema.Current.Table<SMSModelEntity>(); return (from ei in GenerateSMSModelEntities() select table.InsertSqlSync(ei)).Combine(Spacing.Simple); } public static SMSModelEntity GetSMSModelEntity<T>() where T : ISMSModel { return ToSMSModelEntity(typeof(T)); } public static SMSModelEntity GetSMSModelEntity(string fullClassName) { return typeToEntity.Value.Where(x => x.Key.FullName == fullClassName).FirstOrDefault().Value; } public static SMSModelEntity ToSMSModelEntity(Type smsModelType) { return typeToEntity.Value.GetOrThrow(smsModelType, "The SMSModel {0} was not registered"); } public static Type ToType(this SMSModelEntity smsModelEntity) { return entityToType.Value.GetOrThrow(smsModelEntity, "The SMSModel {0} was not registered"); } public static void SendSMS(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { var result = smsModel.CreateSMSMessage(forceCultureInfo); SMSLogic.SendSMS(result); } public static void SendAsyncSMS(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { var result = smsModel.CreateSMSMessage(forceCultureInfo); SMSLogic.SendAsyncSMS(result); } public static SMSMessageEntity CreateSMSMessage(this ISMSModel smsModel, CultureInfo? forceCultureInfo = null) { if (smsModel.UntypedEntity == null) throw new InvalidOperationException("Entity property not set on SMSModel"); using (IsolationEntity.Override((smsModel.UntypedEntity as Entity)?.TryIsolation())) { var smsModelEntity = ToSMSModelEntity(smsModel.GetType()); var template = GetDefaultTemplate(smsModelEntity); return SMSLogic.CreateSMSMessage(template.ToLite(), smsModel.UntypedEntity, smsModel, forceCultureInfo); } } private static SMSTemplateEntity GetDefaultTemplate(SMSModelEntity smsModelEntity) { var isAllowed = Schema.Current.GetInMemoryFilter<SMSTemplateEntity>(userInterface: false); var templates = SMSModelToTemplates.Value.TryGetC(smsModelEntity.ToLite()).EmptyIfNull(); if (templates.IsNullOrEmpty()) { using (ExecutionMode.Global()) using (OperationLogic.AllowSave<SMSTemplateEntity>()) using (Transaction tr = Transaction.ForceNew()) { var template = CreateDefaultTemplate(smsModelEntity); template.Save(); return tr.Commit(template); } } templates = templates.Where(isAllowed); return templates.Where(t => t.IsActive).SingleEx(() => "Active EmailTemplates for SystemEmail {0}".FormatWith(smsModelEntity)); } internal static SMSTemplateEntity CreateDefaultTemplate(SMSModelEntity smsModel) { SMSModelInfo info = registeredModels.GetOrThrow(entityToType.Value.GetOrThrow(smsModel)); if (info.DefaultTemplateConstructor == null) throw new InvalidOperationException($"No EmailTemplate for {smsModel} found and DefaultTemplateConstructor = null"); SMSTemplateEntity template = info.DefaultTemplateConstructor.Invoke(); if (template.Name == null) template.Name = smsModel.FullClassName; template.Model = smsModel; template.Query = QueryLogic.GetQueryEntity(info.QueryName); template.ParseData(QueryLogic.Queries.QueryDescription(info.QueryName)); return template; } public static void GenerateAllTemplates() { foreach (var smsModelType in registeredModels.Keys) { var smsModelEntity = ToSMSModelEntity(smsModelType); var template = Database.Query<SMSTemplateEntity>().SingleOrDefaultEx(t => t.Model == smsModelEntity); if (template == null) { template = CreateDefaultTemplate(smsModelEntity); using (ExecutionMode.Global()) using (OperationLogic.AllowSave<SMSTemplateEntity>()) template.Save(); } } } public static bool RequiresExtraParameters(SMSModelEntity smsModelEntity) { return GetEntityConstructor(entityToType.Value.GetOrThrow(smsModelEntity)) == null; } internal static bool HasDefaultTemplateConstructor(SMSModelEntity smsModelEntity) { SMSModelInfo info = registeredModels.GetOrThrow(smsModelEntity.ToType()); return info.DefaultTemplateConstructor != null; } public static ISMSModel CreateModel(SMSModelEntity model, ModifiableEntity? entity) { return (ISMSModel)SMSModelLogic.GetEntityConstructor(model.ToType())!.Invoke(new[] { entity }); } public static ConstructorInfo? GetEntityConstructor(Type smsModel) { var entityType = GetEntityType(smsModel); return (from ci in smsModel.GetConstructors() let pi = ci.GetParameters().Only() where pi != null && pi.ParameterType == entityType select ci).SingleOrDefaultEx(); } } }
using System; using System.Collections.Generic; using Content.Client.UserInterface.Stylesheets; using Content.Shared.AI; using Robust.Client.Interfaces.Graphics.ClientEye; using Robust.Client.Interfaces.UserInterface; using Robust.Client.UserInterface; using Robust.Client.UserInterface.Controls; using Robust.Shared.GameObjects.Systems; using Robust.Shared.Interfaces.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Maths; namespace Content.Client.GameObjects.EntitySystems.AI { #if DEBUG public class ClientAiDebugSystem : EntitySystem { [Dependency] private readonly IEyeManager _eyeManager = default!; private AiDebugMode _tooltips = AiDebugMode.None; private readonly Dictionary<IEntity, PanelContainer> _aiBoxes = new Dictionary<IEntity,PanelContainer>(); public override void Update(float frameTime) { base.Update(frameTime); if (_tooltips == 0) { if (_aiBoxes.Count > 0) { foreach (var (_, panel) in _aiBoxes) { panel.Dispose(); } _aiBoxes.Clear(); } return; } var deletedEntities = new List<IEntity>(0); foreach (var (entity, panel) in _aiBoxes) { if (entity.Deleted) { deletedEntities.Add(entity); continue; } if (!_eyeManager.GetWorldViewport().Contains(entity.Transform.WorldPosition)) { panel.Visible = false; continue; } var (x, y) = _eyeManager.CoordinatesToScreen(entity.Transform.Coordinates).Position; var offsetPosition = new Vector2(x - panel.Width / 2, y - panel.Height - 50f); panel.Visible = true; LayoutContainer.SetPosition(panel, offsetPosition); } foreach (var entity in deletedEntities) { _aiBoxes.Remove(entity); } } public override void Initialize() { base.Initialize(); SubscribeNetworkEvent<SharedAiDebug.UtilityAiDebugMessage>(HandleUtilityAiDebugMessage); SubscribeNetworkEvent<SharedAiDebug.AStarRouteMessage>(HandleAStarRouteMessage); SubscribeNetworkEvent<SharedAiDebug.JpsRouteMessage>(HandleJpsRouteMessage); } private void HandleUtilityAiDebugMessage(SharedAiDebug.UtilityAiDebugMessage message) { if ((_tooltips & AiDebugMode.Thonk) != 0) { // I guess if it's out of range we don't know about it? var entityManager = IoCManager.Resolve<IEntityManager>(); var entity = entityManager.GetEntity(message.EntityUid); TryCreatePanel(entity); // Probably shouldn't access by index but it's a debugging tool so eh var label = (Label) _aiBoxes[entity].GetChild(0).GetChild(0); label.Text = $"Current Task: {message.FoundTask}\n" + $"Task score: {message.ActionScore}\n" + $"Planning time (ms): {message.PlanningTime * 1000:0.0000}\n" + $"Considered {message.ConsideredTaskCount} tasks"; } } private void HandleAStarRouteMessage(SharedAiDebug.AStarRouteMessage message) { if ((_tooltips & AiDebugMode.Paths) != 0) { var entityManager = IoCManager.Resolve<IEntityManager>(); var entity = entityManager.GetEntity(message.EntityUid); TryCreatePanel(entity); var label = (Label) _aiBoxes[entity].GetChild(0).GetChild(1); label.Text = $"Pathfinding time (ms): {message.TimeTaken * 1000:0.0000}\n" + $"Nodes traversed: {message.CameFrom.Count}\n" + $"Nodes per ms: {message.CameFrom.Count / (message.TimeTaken * 1000)}"; } } private void HandleJpsRouteMessage(SharedAiDebug.JpsRouteMessage message) { if ((_tooltips & AiDebugMode.Paths) != 0) { var entityManager = IoCManager.Resolve<IEntityManager>(); var entity = entityManager.GetEntity(message.EntityUid); TryCreatePanel(entity); var label = (Label) _aiBoxes[entity].GetChild(0).GetChild(1); label.Text = $"Pathfinding time (ms): {message.TimeTaken * 1000:0.0000}\n" + $"Jump Nodes: {message.JumpNodes.Count}\n" + $"Jump Nodes per ms: {message.JumpNodes.Count / (message.TimeTaken * 1000)}"; } } public void Disable() { foreach (var tooltip in _aiBoxes.Values) { tooltip.Dispose(); } _aiBoxes.Clear(); _tooltips = AiDebugMode.None; } private void EnableTooltip(AiDebugMode tooltip) { _tooltips |= tooltip; } private void DisableTooltip(AiDebugMode tooltip) { _tooltips &= ~tooltip; } public void ToggleTooltip(AiDebugMode tooltip) { if ((_tooltips & tooltip) != 0) { DisableTooltip(tooltip); } else { EnableTooltip(tooltip); } } private bool TryCreatePanel(IEntity entity) { if (!_aiBoxes.ContainsKey(entity)) { var userInterfaceManager = IoCManager.Resolve<IUserInterfaceManager>(); var actionLabel = new Label { MouseFilter = Control.MouseFilterMode.Ignore, }; var pathfindingLabel = new Label { MouseFilter = Control.MouseFilterMode.Ignore, }; var vBox = new VBoxContainer() { SeparationOverride = 15, Children = {actionLabel, pathfindingLabel}, }; var panel = new PanelContainer { StyleClasses = { StyleNano.StyleClassTooltipPanel }, Children = {vBox}, MouseFilter = Control.MouseFilterMode.Ignore, ModulateSelfOverride = Color.White.WithAlpha(0.75f), }; userInterfaceManager.StateRoot.AddChild(panel); _aiBoxes[entity] = panel; return true; } return false; } } [Flags] public enum AiDebugMode : byte { None = 0, Paths = 1 << 1, Thonk = 1 << 2, } #endif }
namespace AutoMapper { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; #if !PORTABLE using System.Reflection.Emit; #endif internal static class TypeExtensions { public static Expression ToObject(this Expression expression) { return expression.Type == typeof (object) ? expression : Expression.Convert(expression, typeof (object)); } public static Expression ToType(this Expression expression, Type type) { return expression.Type == type ? expression : Expression.Convert(expression, type); } /// <param name="type">The type to construct.</param> /// <param name="getClosedGenericInterfaceType"> /// For generic interfaces, the only way to reliably determine the implementing type's generic type arguments /// is to know the closed type of the desired interface implementation since there may be multiple implementations /// of the same generic interface on this type. /// </param> public static Func<ResolutionContext, TServiceType> BuildCtor<TServiceType>(this Type type, Func<ResolutionContext, Type> getClosedGenericInterfaceType = null) { return context => { // Warning: do not mutate the parameter @type. It's in a shared closure and will be remembered in subsequent calls to this function. // Otherwise all ctors for the same generic type definition will return whatever closed type then first one calculates. var concreteType = type; if (type.IsGenericTypeDefinition()) { if (getClosedGenericInterfaceType == null) throw new ArgumentNullException(nameof(getClosedGenericInterfaceType), "For generic interfaces, the desired closed interface type must be known."); var closedInterfaceType = getClosedGenericInterfaceType.Invoke(context); var implementationTypeArguments = type.GetImplementedInterface(closedInterfaceType.GetGenericTypeDefinition(), closedInterfaceType.GenericTypeArguments).GenericTypeArguments; var genericParameters = type.GetTypeInfo().GenericTypeParameters; var deducedTypeArguments = new Type[genericParameters.Length]; DeduceGenericArguments(genericParameters, deducedTypeArguments, implementationTypeArguments[0], context.SourceType); DeduceGenericArguments(genericParameters, deducedTypeArguments, implementationTypeArguments[1], context.DestinationType); if (deducedTypeArguments.Any(_ => _ == null)) throw new InvalidOperationException($"One or more type arguments to {type.Name} cannot be determined."); concreteType = type.MakeGenericType(deducedTypeArguments); } var obj = context.Options.ServiceCtor.Invoke(concreteType); return (TServiceType)obj; }; } private static void DeduceGenericArguments(Type[] genericParameters, Type[] deducedGenericArguments, Type typeUsingParameters, Type typeUsingArguments) { if (typeUsingParameters.IsByRef) { DeduceGenericArguments(genericParameters, deducedGenericArguments, typeUsingParameters.GetElementType(), typeUsingArguments.GetElementType()); return; } var index = Array.IndexOf(genericParameters, typeUsingParameters); if (index != -1) { if (deducedGenericArguments[index] == null) deducedGenericArguments[index] = typeUsingArguments; else if (deducedGenericArguments[index] != typeUsingArguments) throw new NotImplementedException("Generic variance is not implemented."); } else if (typeUsingParameters.IsGenericType() && typeUsingArguments.IsGenericType()) { var childArgumentsUsingParameters = typeUsingParameters.GenericTypeArguments; var childArgumentsUsingArguments = typeUsingArguments.GenericTypeArguments; for (var i = 0; i < childArgumentsUsingParameters.Length; i++) DeduceGenericArguments(genericParameters, deducedGenericArguments, childArgumentsUsingParameters[i], childArgumentsUsingArguments[i]); } } private static Type GetImplementedInterface(this Type implementation, Type interfaceDefinition, params Type[] interfaceGenericArguments) { return implementation.GetTypeInfo().ImplementedInterfaces.Single(implementedInterface => { if (implementedInterface.GetGenericTypeDefinition() != interfaceDefinition) return false; var implementedInterfaceArguments = implementedInterface.GenericTypeArguments; for (var i = 0; i < interfaceGenericArguments.Length; i++) { // This assumes the interface type parameters are not covariant or contravariant if (implementedInterfaceArguments[i].GetGenericTypeDefinitionIfGeneric() != interfaceGenericArguments[i].GetGenericTypeDefinitionIfGeneric()) return false; } return true; }); } public static Type GetGenericTypeDefinitionIfGeneric(this Type type) { return type.IsGenericType() ? type.GetGenericTypeDefinition() : type; } public static Type[] GetGenericParameters(this Type type) { return type.GetGenericTypeDefinition().GetTypeInfo().GenericTypeParameters; } public static IEnumerable<ConstructorInfo> GetDeclaredConstructors(this Type type) { return type.GetTypeInfo().DeclaredConstructors; } #if !PORTABLE public static Type CreateType(this TypeBuilder type) { return type.CreateTypeInfo().AsType(); } #endif public static IEnumerable<MemberInfo> GetDeclaredMembers(this Type type) { return type.GetTypeInfo().DeclaredMembers; } #if PORTABLE public static IEnumerable<MemberInfo> GetAllMembers(this Type type) { while (true) { foreach (var memberInfo in type.GetTypeInfo().DeclaredMembers) { yield return memberInfo; } type = type.BaseType(); if (type == null) { yield break; } } } public static MemberInfo[] GetMember(this Type type, string name) { return type.GetAllMembers().Where(mi => mi.Name == name).ToArray(); } #endif public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type) { return type.GetTypeInfo().DeclaredMethods; } #if PORTABLE public static MethodInfo GetMethod(this Type type, string name) { return type.GetAllMethods().FirstOrDefault(mi => mi.Name == name); } public static MethodInfo GetMethod(this Type type, string name, Type[] parameters) { return type .GetAllMethods() .Where(mi => mi.Name == name) .Where(mi => mi.GetParameters().Length == parameters.Length) .FirstOrDefault(mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameters)); } #endif public static IEnumerable<MethodInfo> GetAllMethods(this Type type) { return type.GetRuntimeMethods(); } public static IEnumerable<PropertyInfo> GetDeclaredProperties(this Type type) { return type.GetTypeInfo().DeclaredProperties; } #if PORTABLE public static PropertyInfo GetProperty(this Type type, string name) { return type.GetTypeInfo().DeclaredProperties.FirstOrDefault(mi => mi.Name == name); } #endif public static object[] GetCustomAttributes(this Type type, Type attributeType, bool inherit) { return type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).ToArray(); } public static bool IsStatic(this FieldInfo fieldInfo) { return fieldInfo?.IsStatic ?? false; } public static bool IsStatic(this PropertyInfo propertyInfo) { return propertyInfo?.GetGetMethod(true)?.IsStatic ?? propertyInfo?.GetSetMethod(true)?.IsStatic ?? false; } public static bool IsStatic(this MemberInfo memberInfo) { return (memberInfo as FieldInfo).IsStatic() || (memberInfo as PropertyInfo).IsStatic() || ((memberInfo as MethodInfo)?.IsStatic ?? false); } public static bool IsPublic(this PropertyInfo propertyInfo) { return (propertyInfo?.GetGetMethod(true)?.IsPublic ?? false) || (propertyInfo?.GetSetMethod(true)?.IsPublic ?? false); } public static bool HasAnInaccessibleSetter(this PropertyInfo property) { var setMethod = property.GetSetMethod(true); return setMethod == null || setMethod.IsPrivate || setMethod.IsFamily; } public static bool IsPublic(this MemberInfo memberInfo) { return (memberInfo as FieldInfo)?.IsPublic ?? (memberInfo as PropertyInfo).IsPublic(); } public static bool IsNotPublic(this ConstructorInfo constructorInfo) { return constructorInfo.IsPrivate || constructorInfo.IsFamilyAndAssembly || constructorInfo.IsFamilyOrAssembly || constructorInfo.IsFamily; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } #if PORTABLE public static bool IsAssignableFrom(this Type type, Type other) { return type.GetTypeInfo().IsAssignableFrom(other.GetTypeInfo()); } #endif public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsClass(this Type type) { return type.GetTypeInfo().IsClass; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsPrimitive(this Type type) { return type.GetTypeInfo().IsPrimitive; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsInstanceOfType(this Type type, object o) { return o != null && type.IsAssignableFrom(o.GetType()); } public static ConstructorInfo[] GetConstructors(this Type type) { return type.GetTypeInfo().DeclaredConstructors.ToArray(); } public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool ignored) { return propertyInfo.GetMethod; } public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool ignored) { return propertyInfo.SetMethod; } public static FieldInfo GetField(this Type type, string name) { return type.GetRuntimeField(name); } } }
// 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. // File System.ServiceModel.Channels.LocalClientSecuritySettings.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Channels { sealed public partial class LocalClientSecuritySettings { #region Methods and constructors public System.ServiceModel.Channels.LocalClientSecuritySettings Clone() { Contract.Ensures(Contract.Result<System.ServiceModel.Channels.LocalClientSecuritySettings>() != null); return default(System.ServiceModel.Channels.LocalClientSecuritySettings); } public LocalClientSecuritySettings() { Contract.Ensures(this.CookieRenewalThresholdPercentage == 60); Contract.Ensures(this.ReconnectTransportOnFailure == true); Contract.Ensures(this.ReplayCacheSize == 900000); } #endregion #region Properties and indexers public bool CacheCookies { get { return default(bool); } set { } } public int CookieRenewalThresholdPercentage { get { Contract.Ensures(0 <= Contract.Result<int>()); Contract.Ensures(Contract.Result<int>() <= 100); return default(int); } set { Contract.Requires(0 <= value); Contract.Requires(value <= 100); } } public bool DetectReplays { get { return default(bool); } set { } } public System.ServiceModel.Security.IdentityVerifier IdentityVerifier { get { return default(System.ServiceModel.Security.IdentityVerifier); } set { } } public TimeSpan MaxClockSkew { get { Contract.Ensures(0 <= Contract.Result<int>()); return default(TimeSpan); } set { Contract.Requires(TimeSpan.Zero <= value); } } public TimeSpan MaxCookieCachingTime { get { Contract.Ensures(0 <= Contract.Result<int>()); return default(TimeSpan); } set { Contract.Requires(TimeSpan.Zero <= value); } } public bool ReconnectTransportOnFailure { get { return default(bool); } set { } } public int ReplayCacheSize { get { Contract.Ensures(0 <= Contract.Result<int>()); return default(int); } set { Contract.Requires(0 <= value); } } public TimeSpan ReplayWindow { get { return default(TimeSpan); } set { } } public TimeSpan SessionKeyRenewalInterval { get { Contract.Ensures(TimeSpan.Zero <= Contract.Result<TimeSpan>()); return default(TimeSpan); } set { Contract.Requires(TimeSpan.Zero <= value); } } public TimeSpan SessionKeyRolloverInterval { get { Contract.Ensures(TimeSpan.Zero <= Contract.Result<TimeSpan>()); return default(TimeSpan); } set { Contract.Requires(TimeSpan.Zero <= value); } } public TimeSpan TimestampValidityDuration { get { Contract.Ensures(TimeSpan.Zero <= Contract.Result<TimeSpan>()); return default(TimeSpan); } set { Contract.Requires(TimeSpan.Zero <= value); } } #endregion } }
// 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; using Xunit; namespace System.Collections.Tests { public class StackBasicTests { [Fact] public static void EmptyStackSizeIsZero() { Stack stack = new Stack(); Assert.Equal(0, stack.Count); } [Fact] public static void DefaultStackIsNotSynchronized() { Stack stack = new Stack(); Assert.False(stack.IsSynchronized); } [Fact] public static void NumberOfElementsAddedIsEqualToStackSize() { int iNumElementsAdded = 1975; Stack stack = new Stack(); for (int i = 0; i < iNumElementsAdded; i++) { stack.Push(new Object()); } Assert.Equal(stack.Count, iNumElementsAdded); } [Fact] public static void ClearResetsNumberOfElementsToZero() { int iNumElementsAdded = 2; Stack stack = new Stack(); for (int i = 0; i < iNumElementsAdded; i++) { stack.Push(new Object()); } stack.Clear(); Assert.Equal(0, stack.Count); } [Fact] public static void PopDecrementsStackSize() { int iNumElementsAdded = 25; Stack stack = new Stack(); for (int i = 0; i < iNumElementsAdded; i++) { stack.Push(i); } for (int i = 0; i < iNumElementsAdded; i++) { Assert.Equal(stack.Count, iNumElementsAdded - i); Object objTop = stack.Pop(); Assert.Equal(stack.Count, iNumElementsAdded - i - 1); } } [Fact] public static void PeekingEmptyStackThrows() { Stack stack = new Stack(); Assert.Throws<InvalidOperationException>(() => { var x = stack.Peek(); }); } [Fact] public static void PeekingEmptyStackAfterRemovingElementsThrows() { object objRet; Stack stack = new Stack(); for (int i = 0; i < 1000; i++) { stack.Push(i); } for (int i = 0; i < 1000; i++) { objRet = stack.Pop(); } Assert.Throws<InvalidOperationException>(() => { objRet = stack.Peek(); }); } [Fact] public static void ICollectionCanBeGivenToStack() { int iNumElements = 10000; var objArr = new Object[iNumElements]; for (int i = 0; i < iNumElements; i++) { objArr[i] = i; } Stack stack = new Stack(objArr); for (int i = 0; i < iNumElements; i++) { var objRet = stack.Pop(); Assert.True(objRet.Equals(iNumElements - i - 1)); } } [Fact] public static void PeekingAtElementTwiceGivesSameResults() { Stack stack = new Stack(); stack.Push(1); Assert.True(stack.Peek().Equals(stack.Peek())); } [Fact] public static void PushAndPopWorkOnNullElements() { Stack stack = new Stack(); stack.Push(null); stack.Push(-1); stack.Push(null); Assert.Equal(stack.Pop(), null); Assert.True((-1).Equals(stack.Pop())); Assert.Equal(stack.Pop(), null); } [Fact] public static void CopyingToNullArrayThrows() { Stack stack = new Stack(); stack.Push("hey"); Assert.Throws<ArgumentNullException>(() => stack.CopyTo(null, 0)); } [Fact] public static void CopyingToMultiDimArrayThrows() { Stack stack = new Stack(); stack.Push("hey"); Assert.Throws<ArgumentException>(() => stack.CopyTo(new Object[8, 8], 0)); } [Fact] public static void CopyingOutOfRangeThrows_1() { Stack stack = new Stack(); var objArr = new Object[0]; Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, 1)); stack = new Stack(); Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, Int32.MaxValue)); stack = new Stack(); Assert.Throws<ArgumentOutOfRangeException>(() => stack.CopyTo(objArr, Int32.MinValue)); stack = new Stack(); Assert.Throws<ArgumentOutOfRangeException>(() => stack.CopyTo(objArr, -1)); } [Fact] public static void CopyingOutOfRangeThrows_2() { Stack stack = new Stack(); stack.Push("MyString"); var objArr = new Object[0]; Assert.Throws<ArgumentException>(() => stack.CopyTo(objArr, 0)); } [Fact] public static void GettingEnumeratorAndLoopingThroughWorks() { Stack stack = new Stack(); stack.Push("hey"); stack.Push("hello"); IEnumerator ienum = stack.GetEnumerator(); int iCounter = 0; while (ienum.MoveNext()) { iCounter++; } Assert.Equal(iCounter, stack.Count); } [Fact] public static void GetBeforeStartingEnumerator() { // NOTE: The docs say this behaviour is undefined so if test fails it might be ok Stack stack = new Stack(); stack.Push("a"); stack.Push("b"); IEnumerator ienum = stack.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { Object obj = ienum.Current; }); } [Fact] public static void EnumeratingBeyondEndOfListThenGetObject() { Stack stack = new Stack(); stack.Push(new Object()); stack.Push(stack); IEnumerator ienum = stack.GetEnumerator(); Assert.True(ienum.MoveNext()); for (int i = 0; i < 100; i++) { Object objTemp1 = ienum.Current; Assert.True(objTemp1.Equals(stack)); } Assert.True(ienum.MoveNext()); for (int i = 0; i < 100; i++) { Assert.False(ienum.MoveNext()); } Assert.Throws<InvalidOperationException>(() => { var o = ienum.Current; }); } [Fact] public static void PassingNegativeCapacityThrows() { Assert.Throws<ArgumentOutOfRangeException>(() => { Stack stack = new Stack(Int32.MinValue); }); } [Fact] public static void CreatingStackWithZeroCapacityDoesntThrow() { Stack stack = new Stack(0); } [Fact] public static void PassingValidCapacityCreatesZeroElementsStack() { Stack stack = new Stack(1); Assert.Equal(0, stack.Count); } [Fact] public static void SynchronizedStacksIsSynchronizedPropertyReturnsTrue() { Stack stack = Stack.Synchronized(new Stack()); Assert.True(stack.IsSynchronized); } [Fact] public static void SynchronizingNullStackThrows() { Assert.Throws<ArgumentNullException>(() => { Stack stack = Stack.Synchronized(null); }); } [Fact] public static void TestingAllMethodsOfSynchronizedStack() { Stack q1 = new Stack(); for (int i = 0; i < 10; i++) { q1.Push("String_" + i); } Stack q2 = Stack.Synchronized(q1); Assert.Equal(q2.Count, q1.Count); q2.Clear(); Assert.Equal(0, q2.Count); for (int i = 0; i < 10; i++) { q2.Push("String_" + i); } for (int i = 0, j = 9; i < 10; i++, j--) { Assert.True(((String)q2.Peek()).Equals("String_" + j)); Assert.True(((String)q2.Pop()).Equals("String_" + j)); } Assert.Equal(0, q2.Count); Assert.True(q2.IsSynchronized); for (int i = 0; i < 10; i++) q2.Push("String_" + i); Stack q3 = Stack.Synchronized(q2); Assert.True(q3.IsSynchronized); Assert.Equal(q2.Count, q3.Count); var strArr = new String[10]; q2.CopyTo(strArr, 0); for (int i = 0, j = 9; i < 10; i++, j--) { Assert.True(strArr[i].Equals("String_" + j)); } strArr = new String[10 + 10]; q2.CopyTo(strArr, 10); for (int i = 0, j = 9; i < 10; i++, j--) { Assert.True(strArr[i + 10].Equals("String_" + j)); } Assert.Throws<ArgumentNullException>(() => q2.CopyTo(null, 0)); var oArr = q2.ToArray(); for (int i = 0, j = 9; i < 10; i++, j--) { Assert.True(((String)oArr[i]).Equals("String_" + j)); } var ienm1 = q2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => { var oValue = ienm1.Current; }); var iCount = 9; while (ienm1.MoveNext()) { Assert.True(((String)ienm1.Current).Equals("String_" + iCount)); iCount--; } ienm1.Reset(); iCount = 9; while (ienm1.MoveNext()) { Assert.True(((String)ienm1.Current).Equals("String_" + iCount)); iCount--; } ienm1.Reset(); q2.Pop(); Assert.Throws<InvalidOperationException>(() => { var oValue = ienm1.Current; }); Assert.Throws<InvalidOperationException>(() => ienm1.MoveNext()); Assert.Throws<InvalidOperationException>(() => ienm1.Reset()); } [Fact] public static void PassingNullCollectionToConstructorThrows() { Assert.Throws<ArgumentNullException>(() => { Stack stack = new Stack(null); }); } [Fact] public void DebuggerAttributeTests() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Stack()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(new Stack()); } } }
using IntuiLab.Kinect.Utils; using System; using System.Collections.Generic; using System.Linq; namespace IntuiLab.Kinect.GestureRecognizer { internal class GestureChecker : IDisposable { /// <summary> /// List of gesture parts</summary> private List<Condition> conditions; /// <summary> /// Gesture state: Points to current gesture part (Condition)</summary> private IEnumerator<Condition> index; /// <summary> /// How long a full gesture can take in maximum</summary> private long timeout; /// <summary> /// Time keeper: Points to the time when the gesture (re)started</summary> private long _startTime; /// <summary> /// Taking a list of conditions, which are gesture parts to be checked in order /// and a timeout indicating how long a full gesture can take in maximum. /// </summary> /// <param name="gestureConditions"> /// List of condition which are to fullfill for a successful gesture</param> /// <param name="timeout"> /// Maximum time a gesture is allowed to run for.</param> public GestureChecker(IEnumerable<Condition> gestureConditions, int timeout) { this.timeout = timeout; conditions = gestureConditions.ToList(); conditions.ForEach(delegate(Condition c) { c.OnCheck += ConditionChecked; c.Succeeded += ConditionComplete; c.Failed += ConditionFailed; c.GestureBegining += OnGestureBegining; c.GestureEnded += OnGestureEnded; c.GestureProgressed += OnGestureProgressed; }); index = conditions.GetEnumerator(); index.MoveNext(); Reset(); } /// <summary> /// Reset state machine. Includes timeouts and condition list.</summary> public void Reset() { _startTime = CurrentMillis.Millis; /* * Disable all conditions although there should be only one enabled: the last on index.Current * But since it can be NULL and there could occurr Exceptions in user code, * we invest a bit performance to securely save gesture checking performance. */ foreach (Condition c in conditions) { c.Disable(); } index.Reset(); index.MoveNext(); index.Current.Enable(); } #region Events /// <summary> /// Called when a gesture was recognized. That means that all gesture /// parts were sucessfully recognized.</summary> public virtual event EventHandler<GesturesEventArgs> Successful; /// <summary> /// Called when at least one gesture part failed.</summary> public virtual event EventHandler<FailedGestureEventArgs> Failed; public virtual event EventHandler<BeginGestureEventArgs> GestureBegin; public virtual event EventHandler<EndGestureEventArgs> GestureEnd; public virtual event EventHandler<ProgressGestureEventArgs> GestureProgress; /// <summary> /// Every time when a condition is checked, we check if its in time.</summary> /// <param name="src"> /// The checked Condition</param> /// <param name="e"> /// Probably empty</param> private void ConditionChecked(Object src, EventArgs e) { if (_startTime <= CurrentMillis.Millis - timeout) { ConditionFailed(this, new FailedGestureEventArgs { refCondition = (Condition)src }); } } /// <summary> /// A gesture part failed. Lets start from the beginning.</summary> /// <param name="src"> /// The checked Condition</param> /// <param name="e"> /// Details about the fail</param> private void ConditionFailed(Object src, FailedGestureEventArgs e) { Reset(); FireFailed(this, e); } /// <summary> /// Current gesture part was sucessful. Continue with next.</summary> /// <param name="src"> /// The checked condition</param> /// <param name="e"> /// Details about the success</param> private void ConditionComplete(Object src, GesturesEventArgs e) { Condition previous = index.Current; Boolean hasNext = index.MoveNext(); Condition next = index.Current; if (hasNext) // no further gesture parts -> success! { previous.Disable(); next.Enable(); } else { Reset(); FireSucessful(this, e); } } private void OnGestureBegining(Object src, BeginGestureEventArgs e) { RaiseGestureBegin(src, e); } private void OnGestureEnded(Object src, EndGestureEventArgs e) { RaiseGestureEnd(src, e); } private void OnGestureProgressed(Object src, ProgressGestureEventArgs e) { RaiseGestureProgress(src, e); } protected virtual void FireSucessful(Object sender, GesturesEventArgs e) { if (Successful != null) { Successful(this, e); } } protected virtual void FireFailed(Object sender, FailedGestureEventArgs e) { if (Failed != null) { Failed(this, e); } } protected virtual void RaiseGestureBegin(Object sender, BeginGestureEventArgs e) { if (GestureBegin != null) { GestureBegin(this, e); } } protected virtual void RaiseGestureEnd(Object sender, EndGestureEventArgs e) { if (GestureEnd != null) { GestureEnd(this, e); } } protected virtual void RaiseGestureProgress(Object sender, ProgressGestureEventArgs e) { if (GestureProgress != null) { GestureProgress(this, e); } } #endregion #region IDisposable's members /// <summary> /// Dispose this instance. /// </summary> public void Dispose() { foreach(Condition c in conditions) { c.OnCheck -= ConditionChecked; c.Succeeded -= ConditionComplete; c.Failed -= ConditionFailed; c.GestureBegining -= OnGestureBegining; c.GestureEnded -= OnGestureEnded; c.GestureProgressed -= OnGestureProgressed; c.Disable(); } } #endregion } }
#pragma warning disable 1634, 1691 namespace System.Workflow.ComponentModel.Compiler { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.CodeDom; using System.Diagnostics; using System.Text; internal sealed class DesignTimeType : Type, ICloneable { #region Members and Constructors private static readonly char[] nameSeparators = new char[] { '.', '+' }; private static readonly char[] elementDecorators = new char[] { '[', '*', '&' }; private Type declaringType; private string fullName; private TypeAttributes typeAttributes; private ITypeProvider typeProvider; private Attribute[] attributes = null; private ConstructorInfo[] constructors = null; private FieldInfo[] fields = null; private EventInfo[] events = null; private PropertyInfo[] properties = null; private MethodInfo[] methods = null; private Type[] nestedTypes = new Type[0]; private List<CodeTypeDeclaration> codeDomTypes = null; // accounting for partial types private CodeNamespaceImportCollection codeNamespaceImports = null; private Guid guid = Guid.Empty; internal DesignTimeType(Type declaringType, string typeName, CodeNamespaceImportCollection codeNamespaceImports, string namespaceName, ITypeProvider typeProvider) { if (typeName == null) throw new ArgumentNullException("typeName"); if (codeNamespaceImports == null) throw new ArgumentNullException("codeNamespaceImports"); if (typeProvider == null) throw new ArgumentNullException("typeProvider"); if (namespaceName == null && declaringType == null) throw new InvalidOperationException(SR.GetString(SR.NamespaceAndDeclaringTypeCannotBeNull)); typeName = Helper.EnsureTypeName(typeName); namespaceName = Helper.EnsureTypeName(namespaceName); if (declaringType == null) { if (namespaceName.Length == 0) this.fullName = typeName; else this.fullName = namespaceName + "." + typeName; } else { this.fullName = declaringType.FullName + "+" + typeName; } this.codeDomTypes = new List<CodeTypeDeclaration>(); this.codeNamespaceImports = codeNamespaceImports; this.typeProvider = typeProvider; this.declaringType = declaringType; this.typeAttributes = default(TypeAttributes); } internal DesignTimeType(Type declaringType, string elementTypeFullName, ITypeProvider typeProvider) { // constructor for declaring types with element (Arrays, Pointers, ByRef). if (typeProvider == null) throw new ArgumentNullException("typeProvider"); if (elementTypeFullName.LastIndexOfAny(elementDecorators) == -1) throw new ArgumentException(SR.GetString(SR.NotElementType), "elementTypeFullName"); if (elementTypeFullName == null) throw new ArgumentNullException("FullName"); this.fullName = Helper.EnsureTypeName(elementTypeFullName); this.codeDomTypes = null; this.nestedTypes = new Type[0]; this.codeNamespaceImports = null; this.typeProvider = typeProvider; this.declaringType = declaringType; // Set Attributes according to the element type attributes Type elementType = GetElementType(); if (elementType == null) throw new ArgumentException(SR.GetString(SR.NotElementType), "elementTypeFullName"); if (IsArray) { this.typeAttributes = elementType.Attributes & TypeAttributes.VisibilityMask | TypeAttributes.Class | TypeAttributes.Sealed | TypeAttributes.Serializable; } else { // Pointer/ByRef attributes // this.typeAttributes = TypeAttributes.AnsiClass; } } #endregion internal ITypeProvider Provider { get { return this.typeProvider; } } internal void AddCodeTypeDeclaration(CodeTypeDeclaration codeDomType) { if (codeDomType == null) throw new ArgumentNullException("codeDomType"); // this.typeAttributes |= codeDomType.TypeAttributes & ~TypeAttributes.Public; this.typeAttributes |= Helper.ConvertToTypeAttributes(codeDomType.Attributes, this.declaringType); foreach (CodeAttributeDeclaration attribute in codeDomType.CustomAttributes) { if (string.Equals(attribute.Name, "System.SerializableAttribute", StringComparison.Ordinal) || string.Equals(attribute.Name, "System.Serializable", StringComparison.Ordinal) || string.Equals(attribute.Name, "SerializableAttribute", StringComparison.Ordinal) || string.Equals(attribute.Name, "Serializable", StringComparison.Ordinal)) { this.typeAttributes |= TypeAttributes.Serializable; break; } } codeDomTypes.Add(codeDomType); this.attributes = null; this.constructors = null; this.fields = null; this.events = null; this.properties = null; this.methods = null; LoadNestedTypes(codeDomType); } #region Properties public override Assembly Assembly { get { // We can't provide an assembly. This is a design time only type return null; } } public override string AssemblyQualifiedName { get { // We can't provide an assembly. This is a design time only type return this.FullName; } } public override Type BaseType { get { Type type = null; if (this.codeDomTypes != null) { foreach (CodeTypeDeclaration codeDomType in this.codeDomTypes) { // Look for candidates in the type foreach (CodeTypeReference codeBaseType in codeDomType.BaseTypes) { Type typeCandidate = ResolveType(GetTypeNameFromCodeTypeReference(codeBaseType, this)); if ((typeCandidate != null) && (!typeCandidate.IsInterface)) { type = typeCandidate; break; } } if (type != null && !type.Equals(ResolveType("System.Object"))) break; } } if (type == null) { // Look for implicit base class if (IsArray) type = ResolveType("System.Array"); else if (codeDomTypes != null && codeDomTypes.Count > 0) { if (codeDomTypes[0].IsStruct) type = ResolveType("System.ValueType"); else if (codeDomTypes[0].IsEnum) type = ResolveType("System.Enum"); else if ((codeDomTypes[0].IsClass) && (!IsByRef) && (!IsPointer)) type = ResolveType("System.Object"); else if (codeDomTypes[0] is CodeTypeDelegate) type = ResolveType("System.Delegate"); } } return type; } } public Type GetEnumType() { if (this.codeDomTypes != null) { foreach (CodeTypeDeclaration declaration in this.codeDomTypes) { Type enumBaseType = declaration.UserData[typeof(Enum)] as Type; if (enumBaseType != null) { return enumBaseType; } else { if (declaration.BaseTypes.Count > 1) { CodeTypeReference reference = declaration.BaseTypes[1]; //the first one would be Enum Type enumBaseType2 = reference.UserData[typeof(Enum)] as Type; if (enumBaseType2 != null) return enumBaseType2; } } } } return typeof(int); //default } public override Type DeclaringType { get { return this.declaringType; } } public override string FullName { get { return this.fullName; } } public override Guid GUID { get { if (this.guid == Guid.Empty) // Set a GUID // this.guid = Guid.NewGuid(); return this.guid; } } public override Module Module { get { // We can't provide this. This is a design time only type return null; } } public override string Name { get { string name = this.fullName; // detect first bracket, any name seperators after it are part of a generic parameter... int idx = name.IndexOf('['); // Get the name after the last dot if (idx != -1) idx = name.Substring(0, idx).LastIndexOfAny(nameSeparators); else idx = name.LastIndexOfAny(nameSeparators); if (idx != -1) name = this.fullName.Substring(idx + 1); return name; } } public override string Namespace { get { if (this.fullName == Name) return string.Empty; if (this.declaringType != null) { return this.declaringType.Namespace; } return this.fullName.Substring(0, this.fullName.Length - Name.Length - 1); } } public override RuntimeTypeHandle TypeHandle { get { // no runtime context to our type #pragma warning suppress 56503 throw new NotImplementedException(TypeSystemSR.GetString("Error_RuntimeNotSupported")); } } public override Type UnderlyingSystemType { get { return this; } } #endregion #region public methods public override object[] GetCustomAttributes(bool inherit) { return GetCustomAttributes(typeof(object), inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); // Ensure attributes if (this.codeDomTypes != null && this.attributes == null) { CodeAttributeDeclarationCollection attributeDecls = new CodeAttributeDeclarationCollection(); foreach (CodeTypeDeclaration codeType in this.codeDomTypes) attributeDecls.AddRange(codeType.CustomAttributes); this.attributes = Helper.LoadCustomAttributes(attributeDecls, this); } // It is possible both this.codeDomTypes and this.attributes are null. // For example, when constructing type with element (Array, ByRef, Pointer), we don't // set the typedecl because the base type is a system type. We don't set this.attributes // either because we don't actually create a type of the base type. We simply do // new DesignTimeType(null, name, typeProvider). In such cases, we loose the custom attributes // on the base type. if (this.attributes != null) return Helper.GetCustomAttributes(attributeType, inherit, this.attributes, this); else return new object[0]; } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return GetMembersHelper<ConstructorInfo>(bindingAttr, ref this.constructors, false); } public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { return GetMemberHelper<EventInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.events); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return GetMembersHelper<EventInfo>(bindingAttr, ref this.events, true); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { return GetMemberHelper<FieldInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.fields); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return GetMembersHelper<FieldInfo>(bindingAttr, ref this.fields, true); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return GetMembersHelper<MethodInfo>(bindingAttr, ref this.methods, true); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return GetMembersHelper<PropertyInfo>(bindingAttr, ref this.properties, true); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { // verify arguments VerifyGetMemberArguments(name, bindingAttr); List<MemberInfo> members = new List<MemberInfo>(); // Methods if ((type & MemberTypes.Method) != 0) members.AddRange(GetMembersHelper<MethodInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.methods)); // Constructors if ((type & MemberTypes.Constructor) != 0) members.AddRange(GetMembersHelper<ConstructorInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.constructors)); // Properties if ((type & MemberTypes.Property) != 0) members.AddRange(GetMembersHelper<PropertyInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.properties)); // Events if ((type & MemberTypes.Event) != 0) members.AddRange(GetMembersHelper<EventInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.events)); // Fields if ((type & MemberTypes.Field) != 0) members.AddRange(GetMembersHelper<FieldInfo>(bindingAttr, new MemberSignature(name, null, null), ref this.fields)); // Nested types if ((type & MemberTypes.NestedType) != 0) members.AddRange(GetMembersHelper<Type>(bindingAttr, new MemberSignature(name, null, null), ref this.nestedTypes)); return members.ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { // verify arguments VerifyGetMemberArguments(bindingAttr); ArrayList members = new ArrayList(); // members.AddRange(GetMethods(bindingAttr)); members.AddRange(GetProperties(bindingAttr)); members.AddRange(GetEvents(bindingAttr)); members.AddRange(GetFields(bindingAttr)); members.AddRange(GetNestedTypes(bindingAttr)); return (MemberInfo[])members.ToArray(typeof(MemberInfo)); } public override MemberInfo[] GetDefaultMembers() { // Get all of the custom attributes DefaultMemberAttribute attr = null; for (Type t = this; t != null; t = t.BaseType) { object[] attrs = GetCustomAttributes(typeof(DefaultMemberAttribute), false); if (attrs != null && attrs.Length > 0) attr = attrs[0] as DefaultMemberAttribute; if (attr != null) break; } if (attr == null) return new MemberInfo[0]; String defaultMember = attr.MemberName; MemberInfo[] members = GetMember(defaultMember); if (members == null) members = new MemberInfo[0]; return members; } public override Type GetNestedType(string name, BindingFlags bindingAttr) { return GetMemberHelper<Type>(bindingAttr, new MemberSignature(name, null, null), ref this.nestedTypes); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return GetMembersHelper<Type>(bindingAttr, ref this.nestedTypes, false); } public override Type GetInterface(string name, bool ignoreCase) { if (this.codeDomTypes != null) { StringComparison compare = (ignoreCase) ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; // search in the type foreach (CodeTypeDeclaration codeDomType in this.codeDomTypes) { foreach (CodeTypeReference codeBaseType in codeDomType.BaseTypes) { Type interfaceCandidate = ResolveType(GetTypeNameFromCodeTypeReference(codeBaseType, this)); if (interfaceCandidate != null) { if ((interfaceCandidate.IsInterface == true) && (string.Equals(interfaceCandidate.FullName, name, compare))) return interfaceCandidate; // look in base class/intefaces Type baseInterfaceCandidate = interfaceCandidate.GetInterface(name, ignoreCase); if (baseInterfaceCandidate != null) return baseInterfaceCandidate; } } } } return null; } public override Type[] GetInterfaces() { ArrayList types = new ArrayList(); if (this.codeDomTypes != null) { // search in the type foreach (CodeTypeDeclaration codeDomType in this.codeDomTypes) { foreach (CodeTypeReference codeBaseType in codeDomType.BaseTypes) { Type interfaceCandidate = ResolveType(GetTypeNameFromCodeTypeReference(codeBaseType, this)); if (interfaceCandidate != null) { if ((interfaceCandidate.IsInterface == true) && (!types.Contains(interfaceCandidate))) types.Add(interfaceCandidate); // look in base class/intefaces Type[] baseInterfaces = interfaceCandidate.GetInterfaces(); foreach (Type baseInterfaceCandidate in baseInterfaces) { if ((baseInterfaceCandidate != null) && (!types.Contains(baseInterfaceCandidate))) types.Add(baseInterfaceCandidate); } } } } } return (Type[])types.ToArray(typeof(Type)); } public override object InvokeMember(string name, BindingFlags bindingFlags, Binder binder, object target, object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParams) { throw new NotImplementedException(TypeSystemSR.GetString("Error_RuntimeNotSupported")); } public override string ToString() { return fullName; } public override int GetHashCode() { return base.GetHashCode(); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); // this.GetCustomAttributes(true); if (Helper.IsDefined(attributeType, inherit, attributes, this)) return true; return false; } public override Type GetElementType() { Type elementType = null; int elementCharPosition = fullName.LastIndexOfAny(elementDecorators); if (elementCharPosition >= 0) elementType = ResolveType(fullName.Substring(0, elementCharPosition)); return elementType; } public override int GetArrayRank() { if (!IsArray) throw new ArgumentException(TypeSystemSR.GetString("Error_TypeIsNotArray")); int position = Name.LastIndexOf('['); int rank = 1; while (Name[position] != ']') { if (Name[position] == ',') rank++; position++; } return rank; } public override bool IsAssignableFrom(Type c) { return TypeProvider.IsAssignable(this, c); } public override bool IsSubclassOf(Type c) { if (c == null) return false; return TypeProvider.IsSubclassOf(this, c); } public override Type MakeArrayType() { return this.typeProvider.GetType(String.Format(CultureInfo.InvariantCulture, "{0}[]", this.FullName)); } #endregion #region Helpers private void VerifyGetMemberArguments(string name, BindingFlags bindingAttr) { if (name == null) throw new ArgumentNullException("name"); VerifyGetMemberArguments(bindingAttr); } private void VerifyGetMemberArguments(BindingFlags bindingAttr) { // We only support public based constructors on DesignTime type BindingFlags supported = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase; if ((bindingAttr & ~supported) != 0) throw new ArgumentException(TypeSystemSR.GetString("Error_GetMemberBindingOptions")); } internal Type ResolveType(string name) { Type type = null; //first assume full name was provided type = typeProvider.GetType(name); if (type == null && !string.IsNullOrEmpty(Namespace)) // prefixing the namespace type = typeProvider.GetType(Namespace + "." + name); // maybe it is nested type on the current type if (type == null) type = typeProvider.GetType(fullName + "+" + name); // prefixing imported namespaces if ((type == null) && (this.codeNamespaceImports != null)) { foreach (CodeNamespaceImport codeNamespaceImport in this.codeNamespaceImports) { type = typeProvider.GetType(codeNamespaceImport.Namespace + "." + name); if (type != null) break; } } // maybe it is a fullname of a nested class if (type == null) { string nestedName = name; int indexOfFirstDot = name.IndexOf('.'); int indexOfLastDot = -1; while (((indexOfLastDot = nestedName.LastIndexOf('.')) != indexOfFirstDot) && (type == null)) { nestedName = nestedName.Substring(0, indexOfLastDot) + "+" + nestedName.Substring(indexOfLastDot + 1); type = typeProvider.GetType(nestedName); } } // return type; } private bool FilterMember(MemberInfo memberInfo, BindingFlags bindingFlags) { bool isPublic = false; bool isStatic = false; if (this.IsInterface) { isPublic = true; isStatic = false; } else if (memberInfo is MethodBase) { isPublic = (memberInfo as MethodBase).IsPublic; isStatic = (memberInfo as MethodBase).IsStatic; } else if (memberInfo is DesignTimeEventInfo) { isPublic = (memberInfo as DesignTimeEventInfo).IsPublic; isStatic = (memberInfo as DesignTimeEventInfo).IsStatic; } else if (memberInfo is FieldInfo) { isPublic = (memberInfo as FieldInfo).IsPublic; isStatic = (memberInfo as FieldInfo).IsStatic; } else if (memberInfo is PropertyInfo) { // Property public\static attributes can be fetched using the accessors PropertyInfo propertyInfo = memberInfo as PropertyInfo; MethodInfo accessorMethod = null; if (propertyInfo.CanRead) accessorMethod = propertyInfo.GetGetMethod(true); else accessorMethod = propertyInfo.GetSetMethod(true); if (accessorMethod != null) { isPublic = accessorMethod.IsPublic; isStatic = accessorMethod.IsStatic; } } else if (memberInfo is Type) { isPublic = (memberInfo as Type).IsPublic || (memberInfo as Type).IsNestedPublic; // No static check. return ((((isPublic) && ((bindingFlags & BindingFlags.Public) != 0)) || ((!isPublic) && ((bindingFlags & BindingFlags.NonPublic) != 0)))); } return ((((isPublic) && ((bindingFlags & BindingFlags.Public) != 0)) || ((!isPublic) && ((bindingFlags & BindingFlags.NonPublic) != 0))) && (((isStatic) && ((bindingFlags & BindingFlags.Static) != 0)) || ((!isStatic) && ((bindingFlags & BindingFlags.Instance) != 0)))); } // generic method that implements all GetXXXs methods private T[] GetMembersHelper<T>(BindingFlags bindingAttr, ref T[] members, bool searchBase) where T : MemberInfo { // verify arguments VerifyGetMemberArguments(bindingAttr); EnsureMembers(typeof(T)); Dictionary<MemberSignature, T> membersDictionary = new Dictionary<MemberSignature, T>(); // get local properties foreach (T memberInfo in members) { MemberSignature memberSignature = new MemberSignature(memberInfo); if ((FilterMember(memberInfo, bindingAttr)) && (!membersDictionary.ContainsKey(memberSignature))) membersDictionary.Add(new MemberSignature(memberInfo), memberInfo); } if (searchBase && (bindingAttr & BindingFlags.DeclaredOnly) == 0) { // FlattenHierarchy is required to return static members from base classes. if ((bindingAttr & BindingFlags.FlattenHierarchy) == 0) bindingAttr &= ~BindingFlags.Static; Type baseType = BaseType; if (baseType != null) { T[] baseMembers = GetBaseMembers(typeof(T), baseType, bindingAttr) as T[]; foreach (T memberInfo in baseMembers) { // We should not return private members from base classes. Note: Generics requires us to use "as". if ((memberInfo is FieldInfo && (memberInfo as FieldInfo).IsPrivate) || (memberInfo is MethodBase && (memberInfo as MethodBase).IsPrivate) || (memberInfo is Type && (memberInfo as Type).IsNestedPrivate)) continue; // verify a member with this signature was not already created MemberSignature memberSignature = new MemberSignature(memberInfo); if (!membersDictionary.ContainsKey(memberSignature)) membersDictionary.Add(memberSignature, memberInfo); } } } List<T> memberCollection = new List<T>(membersDictionary.Values); return memberCollection.ToArray(); } private MemberInfo[] GetBaseMembers(Type type, Type baseType, BindingFlags bindingAttr) { MemberInfo[] members = null; if (type == typeof(PropertyInfo)) members = baseType.GetProperties(bindingAttr); else if (type == typeof(EventInfo)) members = baseType.GetEvents(bindingAttr); else if (type == typeof(ConstructorInfo)) members = baseType.GetConstructors(bindingAttr); else if (type == typeof(MethodInfo)) members = baseType.GetMethods(bindingAttr); else if (type == typeof(FieldInfo)) members = baseType.GetFields(bindingAttr); else if (type == typeof(Type)) members = baseType.GetNestedTypes(bindingAttr); return members; } private T[] GetMembersHelper<T>(BindingFlags bindingAttr, MemberSignature memberSignature, ref T[] members) where T : MemberInfo { List<T> memberCandidates = new List<T>(); foreach (T memberInfo in this.GetMembersHelper<T>(bindingAttr, ref members, true)) { MemberSignature candididateMemberSignature = new MemberSignature(memberInfo); if (candididateMemberSignature.FilterSignature(memberSignature)) memberCandidates.Add(memberInfo); } return memberCandidates.ToArray(); } // generic method that implements all GetXXX methods private T GetMemberHelper<T>(BindingFlags bindingAttr, MemberSignature memberSignature, ref T[] members) where T : MemberInfo { // verify arguments VerifyGetMemberArguments(bindingAttr); EnsureMembers(typeof(T)); // search the local type foreach (T memberInfo in members) { MemberSignature candididateMemberSignature = new MemberSignature(memberInfo); if (candididateMemberSignature.FilterSignature(memberSignature) && FilterMember(memberInfo, bindingAttr)) return memberInfo; } if ((bindingAttr & BindingFlags.DeclaredOnly) == 0) { // serach base types // FlattenHierarchy is required to return static members from base classes. if ((bindingAttr & BindingFlags.FlattenHierarchy) == 0) bindingAttr &= ~BindingFlags.Static; Type baseType = BaseType; if (baseType != null) { T memberInfo = (T)GetBaseMember(typeof(T), baseType, bindingAttr, memberSignature); if (memberInfo != null) { // We should not return private members from base classes. Note: Generics requires us to use "as". if ((memberInfo is FieldInfo && (memberInfo as FieldInfo).IsPrivate) || (memberInfo is MethodBase && (memberInfo as MethodBase).IsPrivate) || (memberInfo is Type && (memberInfo as Type).IsNestedPrivate)) return null; return memberInfo; } } } return null; } internal MemberInfo GetBaseMember(Type type, Type baseType, BindingFlags bindingAttr, MemberSignature memberSignature) { if (memberSignature == null) throw new ArgumentNullException("memberSignature"); if (baseType == null) return null; MemberInfo member = null; if (typeof(PropertyInfo).IsAssignableFrom(type)) { if (memberSignature.Parameters != null) member = baseType.GetProperty(memberSignature.Name, bindingAttr, null, memberSignature.ReturnType, memberSignature.Parameters, null); else member = baseType.GetProperty(memberSignature.Name, bindingAttr); } else if (typeof(EventInfo).IsAssignableFrom(type)) member = baseType.GetEvent(memberSignature.Name, bindingAttr); else if (typeof(ConstructorInfo).IsAssignableFrom(type)) member = baseType.GetConstructor(bindingAttr, null, memberSignature.Parameters, null); else if (typeof(MethodInfo).IsAssignableFrom(type)) { if (memberSignature.Parameters != null) member = baseType.GetMethod(memberSignature.Name, bindingAttr, null, memberSignature.Parameters, null); else member = baseType.GetMethod(memberSignature.Name, bindingAttr); } else if (typeof(FieldInfo).IsAssignableFrom(type)) member = baseType.GetField(memberSignature.Name, bindingAttr); else if (typeof(Type).IsAssignableFrom(type)) member = baseType.GetNestedType(memberSignature.Name, bindingAttr); return member; } internal static string GetTypeNameFromCodeTypeReference(CodeTypeReference codeTypeReference, DesignTimeType declaringType) { StringBuilder typeName = new StringBuilder(); if (codeTypeReference.ArrayRank == 0) { Type resolvedType = null; if (declaringType != null) resolvedType = declaringType.ResolveType(codeTypeReference.BaseType); if (resolvedType != null) typeName.Append(resolvedType.FullName); else typeName.Append(codeTypeReference.BaseType); if ((codeTypeReference.TypeArguments != null) && (codeTypeReference.TypeArguments.Count > 0)) { if (codeTypeReference.BaseType.IndexOf('`') == -1) typeName.Append(string.Format(CultureInfo.InvariantCulture, "`{0}", new object[] { codeTypeReference.TypeArguments.Count })); typeName.Append("["); foreach (CodeTypeReference typeArgument in codeTypeReference.TypeArguments) { typeName.Append("["); typeName.Append(GetTypeNameFromCodeTypeReference(typeArgument, declaringType)); typeName.Append("],"); } typeName.Length = typeName.Length - 1; //remove the last comma typeName.Append("]"); } } else { typeName.Append(GetTypeNameFromCodeTypeReference(codeTypeReference.ArrayElementType, declaringType)); // Build array decoration (ByRefs and Pointers are part of the the BaseType) typeName.Append("["); for (int loop = 0; loop < codeTypeReference.ArrayRank - 1; loop++) typeName.Append(','); typeName.Append("]"); } return typeName.ToString(); } #endregion #region implementation overrides protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMemberHelper<ConstructorInfo>(bindingAttr, new MemberSignature(null, types, null), ref this.constructors); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return GetMemberHelper<MethodInfo>(bindingAttr, new MemberSignature(name, types, null), ref this.methods); } protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { return GetMemberHelper<PropertyInfo>(bindingAttr, new MemberSignature(name, types, null), ref this.properties); } protected override TypeAttributes GetAttributeFlagsImpl() { return typeAttributes; } protected override bool HasElementTypeImpl() { int elementCharPosition = Name.LastIndexOfAny(elementDecorators); return (elementCharPosition != -1); } protected override bool IsArrayImpl() { int elementCharPosition = Name.LastIndexOfAny(elementDecorators); if ((elementCharPosition != -1) && (Name[elementCharPosition] == '[')) return true; return false; } protected override bool IsByRefImpl() { return (this.fullName[this.fullName.Length - 1] == '&'); } public override Type MakeByRefType() { return this.ResolveType(this.fullName + "&"); } protected override bool IsCOMObjectImpl() { // return false; } protected override bool IsContextfulImpl() { // return false; } protected override bool IsMarshalByRefImpl() { // return false; } protected override bool IsPointerImpl() { return (this.fullName[this.fullName.Length - 1] == '*'); } protected override bool IsPrimitiveImpl() { return false; } #endregion #region Loaders private void EnsureMembers(Type type) { if ((type == typeof(PropertyInfo)) && (this.properties == null)) this.properties = GetCodeDomMembers<PropertyInfo>().ToArray(); else if ((type == typeof(FieldInfo)) && (this.fields == null)) this.fields = GetCodeDomMembers<FieldInfo>().ToArray(); else if ((type == typeof(ConstructorInfo)) && (this.constructors == null)) this.constructors = GetCodeDomConstructors().ToArray(); else if ((type == typeof(EventInfo)) && (this.events == null)) this.events = GetCodeDomMembers<EventInfo>().ToArray(); else if ((type == typeof(MethodInfo)) && (this.methods == null)) { EnsureMembers(typeof(PropertyInfo)); EnsureMembers(typeof(EventInfo)); List<MethodInfo> methodCollection = GetCodeDomMembers<MethodInfo>(); MethodInfo methodInfo = null; foreach (PropertyInfo propertyInfo in this.properties) { if ((methodInfo = propertyInfo.GetGetMethod()) != null) methodCollection.Add(methodInfo); if ((methodInfo = propertyInfo.GetSetMethod()) != null) methodCollection.Add(methodInfo); } foreach (EventInfo eventInfo in this.events) { if ((methodInfo = eventInfo.GetAddMethod()) != null) methodCollection.Add(methodInfo); if ((methodInfo = eventInfo.GetRemoveMethod()) != null) methodCollection.Add(methodInfo); if ((methodInfo = eventInfo.GetRaiseMethod()) != null) methodCollection.Add(methodInfo); } this.methods = methodCollection.ToArray(); } } private List<T> GetCodeDomMembers<T>() where T : MemberInfo { List<T> memberCollection = new List<T>(); if (this.codeDomTypes != null) { foreach (CodeTypeDeclaration codeDomType in codeDomTypes) { //!!! Work around for supporting delegates if (codeDomType is CodeTypeDelegate && typeof(T) == typeof(MethodInfo)) { CodeMemberMethod invokeMethod = new CodeMemberMethod(); invokeMethod.Name = "Invoke"; invokeMethod.Attributes = MemberAttributes.Public; foreach (CodeParameterDeclarationExpression parameterDecl in ((CodeTypeDelegate)codeDomType).Parameters) invokeMethod.Parameters.Add(parameterDecl); invokeMethod.ReturnType = ((CodeTypeDelegate)codeDomType).ReturnType; memberCollection.Add((T)CreateMemberInfo(typeof(MethodInfo), invokeMethod)); } foreach (CodeTypeMember member in codeDomType.Members) { T memberInfo = (T)CreateMemberInfo(typeof(T), member); if (memberInfo != null) memberCollection.Add(memberInfo); } } } return memberCollection; } // CFx bug 461 // The code dom being generated by VsCodeDomParser.cs does not // add default constructors for classes unless they // exist in the source code. Unfortunately, this cannot be easily // fixed in the CodeDomParser because the code dom returned by that // class is expected to kept in [....] with the real source code. // So we cannot "fabricate" a default constructor there without // breaking lots of assumptions elsewhere in the code. // Instead, we add a default constructor here, if necessary. private List<ConstructorInfo> GetCodeDomConstructors() { List<ConstructorInfo> constructors = GetCodeDomMembers<ConstructorInfo>(); // we only add a default constructor if // this is a struct or is a non-static\non-abstract class and it doesn't have any // constructors // * Note - static classes are represented as Abstract and Sealed // abstract classes are represented as Abstract; thus we will check just for that flag if (this.IsValueType || ((constructors.Count == 0) && !this.IsAbstract)) { CodeConstructor codeConstructor = new CodeConstructor(); codeConstructor.Attributes = MemberAttributes.Public; ConstructorInfo constructorInfo = new DesignTimeConstructorInfo(this, codeConstructor); constructors.Add(constructorInfo); } return constructors; } private void LoadNestedTypes(CodeTypeDeclaration codeDomType) { List<Type> localMembers = new List<Type>(); foreach (Type t in this.nestedTypes) localMembers.Add(t); foreach (CodeTypeMember member in codeDomType.Members) { if (!(member is CodeTypeDeclaration)) continue; CodeTypeDeclaration codeType = member as CodeTypeDeclaration; Type partialType = null; foreach (Type nestedType in localMembers) { if (nestedType.Name.Equals(Helper.EnsureTypeName(codeType.Name))) { partialType = nestedType; break; } } if (partialType == null) { partialType = new DesignTimeType(this, codeType.Name, this.codeNamespaceImports, this.fullName, this.typeProvider); localMembers.Add(partialType); ((TypeProvider)this.typeProvider).AddType(partialType); } ((DesignTimeType)partialType).AddCodeTypeDeclaration(codeType); } this.nestedTypes = localMembers.ToArray(); } private MemberInfo CreateMemberInfo(Type memberInfoType, CodeTypeMember member) { MemberInfo memberInfo = null; if ((memberInfoType == typeof(PropertyInfo)) && (member is CodeMemberProperty)) memberInfo = new DesignTimePropertyInfo(this, member as CodeMemberProperty); else if ((memberInfoType == typeof(EventInfo)) && (member is CodeMemberEvent)) memberInfo = new DesignTimeEventInfo(this, member as CodeMemberEvent); else if ((memberInfoType == typeof(FieldInfo)) && (member is CodeMemberField)) memberInfo = new DesignTimeFieldInfo(this, member as CodeMemberField); else if ((memberInfoType == typeof(ConstructorInfo)) && ((member is CodeConstructor) || (member is CodeTypeConstructor))) memberInfo = new DesignTimeConstructorInfo(this, member as CodeMemberMethod); else if ((memberInfoType == typeof(MethodInfo)) && (member.GetType() == typeof(CodeMemberMethod))) memberInfo = new DesignTimeMethodInfo(this, member as CodeMemberMethod); return memberInfo; } #endregion #region MemberSignature class // Uniquely identify a memberInfo internal class MemberSignature { #region Members and Constructors private string name = null; private Type[] parameters = null; private Type returnType = null; readonly int hashCode; internal MemberSignature(MemberInfo memberInfo) { this.name = memberInfo.Name; if (memberInfo is MethodBase) { List<Type> typeCollection = new List<Type>(); // method/constructor arguments foreach (ParameterInfo parameterInfo in (memberInfo as MethodBase).GetParameters()) typeCollection.Add(parameterInfo.ParameterType); this.parameters = typeCollection.ToArray(); if (memberInfo is MethodInfo) this.returnType = ((MethodInfo)memberInfo).ReturnType; } else if (memberInfo is PropertyInfo) { PropertyInfo propertyInfo = memberInfo as PropertyInfo; List<Type> typeCollection = new List<Type>(); // indexer arguments foreach (ParameterInfo parameterInfo in propertyInfo.GetIndexParameters()) typeCollection.Add(parameterInfo.ParameterType); this.parameters = typeCollection.ToArray(); // return type for property this.returnType = propertyInfo.PropertyType; } this.hashCode = this.GetHashCodeImpl(); } internal MemberSignature(string name, Type[] parameters, Type returnType) { this.name = name; this.returnType = returnType; if (parameters != null) this.parameters = (Type[])parameters.Clone(); this.hashCode = this.GetHashCodeImpl(); } #endregion #region properties public string Name { get { return name; } } public Type ReturnType { get { return returnType; } } public Type[] Parameters { get { if (parameters == null) return null; return (Type[])parameters.Clone(); } } #endregion #region Comparison public override bool Equals(object obj) { MemberSignature memberSignature = obj as MemberSignature; if ((memberSignature == null) || (this.name != memberSignature.name) || (this.returnType != memberSignature.returnType)) return false; if ((this.Parameters == null) && (memberSignature.Parameters != null) || (this.Parameters != null) && (memberSignature.Parameters == null)) return false; if (this.Parameters != null) { if (this.parameters.Length != memberSignature.parameters.Length) return false; for (int loop = 0; loop < this.parameters.Length; loop++) { if (this.parameters[loop] != memberSignature.parameters[loop]) return false; } } return true; } // this method will filter using a mask signautre. only non-null mask members are used to filter // the signature, the rest are ignored public bool FilterSignature(MemberSignature maskSignature) { if (maskSignature == null) throw new ArgumentNullException("maskSignature"); if (((maskSignature.Name != null) && (this.name != maskSignature.name)) || ((maskSignature.returnType != null) && (this.returnType != maskSignature.returnType))) return false; if (maskSignature.parameters != null) { if (this.parameters == null) return false; if (this.parameters.Length != maskSignature.parameters.Length) return false; for (int loop = 0; loop < this.parameters.Length; loop++) { if (!this.parameters[loop].Equals(maskSignature.parameters[loop])) return false; } } return true; } public override string ToString() { string str = string.Empty; if (returnType != null) str = returnType.FullName + " "; if (name != null && name.Length != 0) str += name; if (parameters != null && parameters.Length > 0) { str += "("; for (int i = 0; i < parameters.Length; i++) { if (i > 0) str += ", "; if (parameters[i] != null) { if (parameters[i].GetType() != null && parameters[i].GetType().IsByRef) str += "ref "; str += parameters[i].FullName; } } str += ")"; } return str; } public override int GetHashCode() { return this.hashCode; } int GetHashCodeImpl() { int hashCode = 0; if (this.name != null) { hashCode = name.GetHashCode(); } if (this.parameters != null && this.parameters.Length > 0) { for (int i = 0; i < this.parameters.Length; i++) { if (this.parameters[i] != null) { hashCode ^= this.parameters[i].GetHashCode(); } } } if (this.returnType != null) { hashCode ^= this.returnType.GetHashCode(); } return hashCode; } #endregion } #endregion #region ICloneable Members public object Clone() { return this; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Reflection; using Cradiator.Extensions; using log4net; namespace Cradiator.Config { /// <summary> /// configuration settings /// </summary> public class ConfigSettings : INotifyPropertyChanged, IConfigSettings { const int DefaultPollingFrequency = 30; const string PollFrequencyKey = "PollFrequency"; const string UrlKey = "URL"; const string UsernameKey = "Username"; const string PasswordKey = "Password"; const string SkinKey = "Skin"; const string ProjectNameRegexKey = "ProjectNameRegEx"; const string CategoryRegexKey = "CategoryRegEx"; const string ShowCountdownKey = "ShowCountdown"; const string ShowProgressKey = "ShowProgress"; const string PlaySoundsKey = "PlaySounds"; const string BrokenBuildSoundKey = "BrokenBuildSound"; const string FixedBuildSoundKey = "FixedBuildSound"; const string BrokenBuildTextKey = "BrokenBuildText"; const string FixedBuildTextKey = "FixedBuildText"; const string PlaySpeechKey = "PlaySpeech"; const string SpeechVoiceNameKey = "SpeechVoiceName"; const string BreakerGuiltStrategyKey = "BreakerGuiltStrategy"; readonly IList<IConfigObserver> _configObservers = new List<IConfigObserver>(); static readonly ILog _log = LogManager.GetLogger(typeof(ConfigSettings).Name); IDictionary<string, string> _usernameMap = new Dictionary<string, string>(); readonly UserNameMappingReader _userNameMappingReader = new UserNameMappingReader(new ConfigLocation()); private string _url; public string URL { get { return _url; } set { if (_url == value) return; _url = value; Notify("URL"); } } private string _username; public string Username { get { return _username; } set { if (_username == value) return; _username = value; Notify("UsernameKey"); } } private string _password; public string Password { get { return _password; } set { if (_password == value) return; _password = value; Notify("PasswordKey"); } } private string _skinName; public string SkinName { get { return _skinName; } set { if (_skinName == value) return; _skinName = value; Notify("SkinName"); } } /// <summary> interval at which to poll (in seconds) </summary> private int _pollFrequency; public int PollFrequency { get { return _pollFrequency; } set { if (_pollFrequency == value) return; _pollFrequency = value; Notify("PollFrequency"); } } private string _projectNameRegEx; public string ProjectNameRegEx { get { return _projectNameRegEx.GetRegEx(); } set { if (_projectNameRegEx == value) return; _projectNameRegEx = value; Notify("ProjectNameRegEx"); } } private string _categoryRegEx; public string CategoryRegEx { get { return _categoryRegEx.GetRegEx(); } set { if (_categoryRegEx == value) return; _categoryRegEx = value; Notify("CategoryRegEx"); } } private bool _showCountdown; public bool ShowCountdown { get { return _showCountdown; } set { if (_showCountdown == value) return; _showCountdown = value; Notify("ShowCountdown"); } } private bool _showProgress; public bool ShowProgress { get { return _showProgress; } set { if (_showProgress == value) return; _showProgress = value; Notify("ShowProgress"); } } public IDictionary<string, string> UsernameMap { get { return _usernameMap; } set { _usernameMap = value; } } private string _brokenBuildSound; public string BrokenBuildSound { get { return _brokenBuildSound; } set { if (_brokenBuildSound == value) return; _brokenBuildSound = value; Notify("BrokenBuildSound"); } } private string _fixedBuildSound; public string FixedBuildSound { get { return _fixedBuildSound; } set { if (_fixedBuildSound == value) return; _fixedBuildSound = value; Notify("FixedBuildSound"); } } private string _brokenBuildText; public string BrokenBuildText { get { return _brokenBuildText; } set { if (_brokenBuildText == value) return; _brokenBuildText = value; Notify("BrokenBuildText"); } } private string _fixedBuildText; public string FixedBuildText { get { return _fixedBuildText; } set { if (_fixedBuildText == value) return; _fixedBuildText = value; Notify("FixedBuildText"); } } private bool _playSounds; public bool PlaySounds { get { return _playSounds; } set { if (_playSounds == value) return; _playSounds = value; Notify("PlaySounds"); } } private bool _playSpeech; public bool PlaySpeech { get { return _playSpeech; } set { if (_playSpeech == value) return; _playSpeech = value; Notify("PlaySpeech"); } } private string _speechVoiceName; public string SpeechVoiceName { get { return _speechVoiceName; } set { if (_speechVoiceName == value) return; _speechVoiceName = value; Notify("SpeechVoiceName"); } } private string _breakerGuiltStrategy; public GuiltStrategyType BreakerGuiltStrategy { get { return _breakerGuiltStrategy == "First" ? GuiltStrategyType.First : GuiltStrategyType.Last; } } public TimeSpan PollFrequencyTimeSpan { get { return TimeSpan.FromSeconds(PollFrequency); } } public void Save() { try { var config = OpenExeConfiguration(); config.AppSettings.Settings[UrlKey].Value = URL; config.AppSettings.Settings[UsernameKey].Value = Username; config.AppSettings.Settings[PasswordKey].Value = Password; config.AppSettings.Settings[SkinKey].Value = SkinName; config.AppSettings.Settings[PollFrequencyKey].Value = PollFrequency.ToString(); config.AppSettings.Settings[ProjectNameRegexKey].Value = ProjectNameRegEx; config.AppSettings.Settings[CategoryRegexKey].Value = CategoryRegEx; config.AppSettings.Settings[ShowCountdownKey].Value = ShowCountdown.ToString(); config.AppSettings.Settings[ShowProgressKey].Value = ShowProgress.ToString(); config.AppSettings.Settings[PlaySoundsKey].Value = PlaySounds.ToString(); config.AppSettings.Settings[PlaySpeechKey].Value = PlaySpeech.ToString(); config.AppSettings.Settings[BrokenBuildSoundKey].Value = BrokenBuildSound; config.AppSettings.Settings[FixedBuildSoundKey].Value = FixedBuildSound; config.AppSettings.Settings[BrokenBuildTextKey].Value = BrokenBuildText; config.AppSettings.Settings[FixedBuildTextKey].Value = FixedBuildText; config.AppSettings.Settings[SpeechVoiceNameKey].Value = SpeechVoiceName; config.AppSettings.Settings[BreakerGuiltStrategyKey].Value = _breakerGuiltStrategy; config.Save(ConfigurationSaveMode.Minimal); } catch (Exception ex) { // config may be edited in the file (manually) - we cannot show an error dialog here // because it's entirely reasonable that the user doesn't have access to the machine running the exe to close it _log.Error(ex.Message, ex); } } public void Load() { var config = OpenExeConfiguration(); URL = config.GetProperty(UrlKey).Value; Username = config.GetProperty(UsernameKey).Value; Password = config.GetProperty(PasswordKey).Value; SkinName = config.GetProperty(SkinKey).Value; PollFrequency = config.GetIntProperty(PollFrequencyKey, DefaultPollingFrequency); ProjectNameRegEx = config.GetProperty(ProjectNameRegexKey).Value; CategoryRegEx = config.GetProperty(CategoryRegexKey).Value; ShowCountdown = config.GetBoolProperty(ShowCountdownKey); ShowProgress = config.GetBoolProperty(ShowProgressKey); PlaySounds = config.GetBoolProperty(PlaySoundsKey); PlaySpeech = config.GetBoolProperty(PlaySpeechKey); BrokenBuildSound = config.GetProperty(BrokenBuildSoundKey).Value; FixedBuildSound = config.GetProperty(FixedBuildSoundKey).Value; BrokenBuildText = config.GetProperty(BrokenBuildTextKey).Value; FixedBuildText = config.GetProperty(FixedBuildTextKey).Value; SpeechVoiceName = config.GetProperty(SpeechVoiceNameKey).Value; _breakerGuiltStrategy = config.GetProperty(BreakerGuiltStrategyKey).Value; _usernameMap = _userNameMappingReader.Read(); } private static Configuration OpenExeConfiguration() { return ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location); } public void AddObserver(IConfigObserver observer) { _configObservers.Add(observer); } public void NotifyObservers() { foreach (var observer in _configObservers) { observer.ConfigUpdated(this); } } public event PropertyChangedEventHandler PropertyChanged; void Notify(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public override string ToString() { return string.Format("Url={0}, SkinName={1}, PollFrequency={2}, ProjectNameRegEx={3}, ShowCountdown={4}, ShowCountdown={5}, PlaySounds={6}, PlaySpeech={7}, BrokenBuildSound={8}, BrokenBuildText={9}, FixedBuildSound={10}, FixedBuildText={11}, SpeechVoiceName={12}, CategoryRegEx={13}, BreakerGuiltStrategy={14}", _url, _skinName, _pollFrequency, _projectNameRegEx, _showCountdown, _showProgress, _playSounds, _playSpeech, _brokenBuildSound, _brokenBuildText, _fixedBuildSound, _fixedBuildText, _speechVoiceName, _categoryRegEx, _breakerGuiltStrategy); } } public enum GuiltStrategyType { First, Last } public class ConfigSettingsException : Exception { public ConfigSettingsException(string key) : base(string.Format("Configuration setting missing: '{0}'", key)) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Globalization; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Xml.Xsl.Runtime; namespace System.Xml.Xsl.IlGen { /// <summary> /// Type of location in which iterator items are stored. /// </summary> internal enum ItemLocation { None = 0, Stack, // Each value is stored as the top value on the IL stack Parameter, // Each value is stored as a parameter to the current method Local, // Each value is stored as a local variable in the current method Current, // Each value is stored as an iterator's Current property Global, // Each value is stored as a global variable }; /// <summary> /// None--Not in a branching context /// True--Branch if boolean expression evaluates to true /// False--Branch if boolean expression evaluates to false /// </summary> internal enum BranchingContext { None, OnTrue, OnFalse }; /// <summary> /// Describes the Clr type and location of items returned by an iterator. /// This struct is meant to be immutable. /// </summary> internal struct StorageDescriptor { private ItemLocation _location; private object _locationObject; private Type _itemStorageType; private bool _isCached; //----------------------------------------------- // Create Methods //----------------------------------------------- /// <summary> /// Create default, empty StorageDescriptor. /// </summary> public static StorageDescriptor None() { return new StorageDescriptor(); } /// <summary> /// Create a StorageDescriptor for an item located on the stack. /// </summary> public static StorageDescriptor Stack(Type itemStorageType, bool isCached) { StorageDescriptor storage = new StorageDescriptor(); storage._location = ItemLocation.Stack; storage._itemStorageType = itemStorageType; storage._isCached = isCached; return storage; } /// <summary> /// Create a StorageDescriptor for an item which is a parameter to the current method. /// </summary> public static StorageDescriptor Parameter(int paramIndex, Type itemStorageType, bool isCached) { StorageDescriptor storage = new StorageDescriptor(); storage._location = ItemLocation.Parameter; storage._locationObject = paramIndex; storage._itemStorageType = itemStorageType; storage._isCached = isCached; return storage; } /// <summary> /// Create a StorageDescriptor for an item located in a local variable. /// </summary> public static StorageDescriptor Local(LocalBuilder loc, Type itemStorageType, bool isCached) { Debug.Assert(loc.LocalType == itemStorageType || typeof(IList<>).MakeGenericType(itemStorageType).IsAssignableFrom(loc.LocalType), "Type " + itemStorageType + " does not match the local variable's type"); StorageDescriptor storage = new StorageDescriptor(); storage._location = ItemLocation.Local; storage._locationObject = loc; storage._itemStorageType = itemStorageType; storage._isCached = isCached; return storage; } /// <summary> /// Create a StorageDescriptor for an item which is the Current item in an iterator. /// </summary> public static StorageDescriptor Current(LocalBuilder locIter, Type itemStorageType) { Debug.Assert(locIter.LocalType.GetMethod("get_Current").ReturnType == itemStorageType, "Type " + itemStorageType + " does not match type of Current property."); StorageDescriptor storage = new StorageDescriptor(); storage._location = ItemLocation.Current; storage._locationObject = locIter; storage._itemStorageType = itemStorageType; return storage; } /// <summary> /// Create a StorageDescriptor for an item located in a global variable. /// </summary> public static StorageDescriptor Global(MethodInfo methGlobal, Type itemStorageType, bool isCached) { Debug.Assert(methGlobal.ReturnType == itemStorageType || typeof(IList<>).MakeGenericType(itemStorageType).IsAssignableFrom(methGlobal.ReturnType), "Type " + itemStorageType + " does not match the global method's return type"); StorageDescriptor storage = new StorageDescriptor(); storage._location = ItemLocation.Global; storage._locationObject = methGlobal; storage._itemStorageType = itemStorageType; storage._isCached = isCached; return storage; } //----------------------------------------------- // Accessor Methods //----------------------------------------------- /// <summary> /// Return copy of current descriptor, but change item's location to the stack. /// </summary> public StorageDescriptor ToStack() { return Stack(_itemStorageType, _isCached); } /// <summary> /// Create a StorageDescriptor for an item located in a local variable. /// </summary> public StorageDescriptor ToLocal(LocalBuilder loc) { return Local(loc, _itemStorageType, _isCached); } /// <summary> /// Create a StorageDescriptor which is the same as this one, except for the item storage type. /// </summary> public StorageDescriptor ToStorageType(Type itemStorageType) { StorageDescriptor storage = this; storage._itemStorageType = itemStorageType; return storage; } /// <summary> /// Return an enumeration specifying where the value is located. /// </summary> public ItemLocation Location { get { return _location; } } /// <summary> /// Return the index of the parameter that stores this iterator's values. /// </summary> public int ParameterLocation { get { return (int)_locationObject; } } /// <summary> /// Return the LocalBuilder that stores this iterator's values. /// </summary> public LocalBuilder LocalLocation { get { return _locationObject as LocalBuilder; } } /// <summary> /// Return the LocalBuilder that will store this iterator's helper class. The Current property /// on this iterator can be accessed to get the current iteration value. /// </summary> public LocalBuilder CurrentLocation { get { return _locationObject as LocalBuilder; } } /// <summary> /// Return the MethodInfo for the method that computes this global value. /// </summary> public MethodInfo GlobalLocation { get { return _locationObject as MethodInfo; } } /// <summary> /// Return true if this iterator's values are cached. /// </summary> public bool IsCached { get { return _isCached; } } /// <summary> /// Return the Clr type of an individual item in the storage location (never an IList<> type). /// </summary> public Type ItemStorageType { get { return _itemStorageType; } } } /// <summary> /// Iterators are joined together, are nested within each other, and reference each other. This internal class /// contains detailed information about iteration next labels, caching, iterator item location, etc. /// </summary> internal class IteratorDescriptor { private GenerateHelper _helper; // Related iterators private IteratorDescriptor _iterParent; // Iteration private Label _lblNext; private bool _hasNext; private LocalBuilder _locPos; // Branching private BranchingContext _brctxt; private Label _lblBranch; // Storage private StorageDescriptor _storage; //----------------------------------------------- // Initialize //----------------------------------------------- /// <summary> /// Create a "root" IteratorDescriptor which has no parent iterator. /// </summary> public IteratorDescriptor(GenerateHelper helper) { Init(null, helper); } /// <summary> /// Create an IteratorDescriptor that is nested in a parent iterator. /// </summary> public IteratorDescriptor(IteratorDescriptor iterParent) { Init(iterParent, iterParent._helper); } /// <summary> /// Internal helper initializor. /// </summary> private void Init(IteratorDescriptor iterParent, GenerateHelper helper) { _helper = helper; _iterParent = iterParent; } //----------------------------------------------- // Related Iterators //----------------------------------------------- /// <summary> /// Return the iterator in which this iterator is nested. /// </summary> public IteratorDescriptor ParentIterator { get { return _iterParent; } } //----------------------------------------------- // Iteration //----------------------------------------------- /// <summary> /// Returns true if LabelNext is currently defined. If not, then this iterator will return /// exactly one result (iterator is cardinality one). /// </summary> public bool HasLabelNext { get { return _hasNext; } } /// <summary> /// Return the label that is anchored to this code iterator's MoveNext code. /// </summary> public Label GetLabelNext() { Debug.Assert(_hasNext); return _lblNext; } /// <summary> /// Set this iterator's next label and storage. This iterator will range over a set of values located in /// "storage". To get the next value, jump to "lblNext". /// </summary> public void SetIterator(Label lblNext, StorageDescriptor storage) { _lblNext = lblNext; _hasNext = true; _storage = storage; } /// <summary> /// Set this iterator to be the same as the specified iterator. /// </summary> public void SetIterator(IteratorDescriptor iterInfo) { if (iterInfo.HasLabelNext) { _lblNext = iterInfo.GetLabelNext(); _hasNext = true; } _storage = iterInfo.Storage; } /// <summary> /// Continue iteration until it is complete. Branch to "lblOnEnd" when iteration is complete. /// </summary> /// <remarks> /// goto LabelNextCtxt; /// LabelOnEnd: /// </remarks> public void LoopToEnd(Label lblOnEnd) { if (_hasNext) { _helper.BranchAndMark(_lblNext, lblOnEnd); _hasNext = false; } // After looping is finished, storage is N/A _storage = StorageDescriptor.None(); } /// <summary> /// Storage location containing the position of the current item as an integer. /// This location is only defined on iterators, and then only if they might be /// referenced by a PositionOf operator. /// </summary> public LocalBuilder LocalPosition { get { return _locPos; } set { _locPos = value; } } //----------------------------------------------- // Caching //----------------------------------------------- /// <summary> /// Push the count of items in the cache onto the stack. /// </summary> public void CacheCount() { Debug.Assert(_storage.IsCached); PushValue(); _helper.CallCacheCount(_storage.ItemStorageType); } /// <summary> /// If the iterator has been fully cached, then iterate the values one-by-one. /// </summary> public void EnsureNoCache() { if (_storage.IsCached) { if (!HasLabelNext) { // If no Next label, this must be a singleton cache EnsureStack(); _helper.LoadInteger(0); _helper.CallCacheItem(_storage.ItemStorageType); _storage = StorageDescriptor.Stack(_storage.ItemStorageType, false); } else { // int idx; LocalBuilder locIdx = _helper.DeclareLocal("$$$idx", typeof(int)); Label lblNext; // Make sure cache is not on the stack EnsureNoStack("$$$cache"); // idx = -1; _helper.LoadInteger(-1); _helper.Emit(OpCodes.Stloc, locIdx); // LabelNext: lblNext = _helper.DefineLabel(); _helper.MarkLabel(lblNext); // idx++; _helper.Emit(OpCodes.Ldloc, locIdx); _helper.LoadInteger(1); _helper.Emit(OpCodes.Add); _helper.Emit(OpCodes.Stloc, locIdx); // if (idx >= cache.Count) goto LabelNextCtxt; _helper.Emit(OpCodes.Ldloc, locIdx); CacheCount(); _helper.Emit(OpCodes.Bge, GetLabelNext()); // item = cache[idx]; PushValue(); _helper.Emit(OpCodes.Ldloc, locIdx); _helper.CallCacheItem(_storage.ItemStorageType); SetIterator(lblNext, StorageDescriptor.Stack(_storage.ItemStorageType, false)); } } } //----------------------------------------------- // If-then-else branching //----------------------------------------------- /// <summary> /// Setup a branching context. All nested iterators compiled in this context must evaluate /// to a single boolean value. However, these expressions must not push the result as a boolean /// onto the stack. Instead, if brctxt is BranchType.True, then the expression should /// jump to lblBranch if it evaluates to true. If brctxt is BranchType.False, then the /// branch should happen if the evaluation result is false. /// </summary> public void SetBranching(BranchingContext brctxt, Label lblBranch) { Debug.Assert(brctxt != BranchingContext.None); _brctxt = brctxt; _lblBranch = lblBranch; } /// <summary> /// True if within a branching context. /// </summary> public bool IsBranching { get { return _brctxt != BranchingContext.None; } } /// <summary> /// Returns the label to which conditionals should branch. /// </summary> public Label LabelBranch { get { return _lblBranch; } } /// <summary> /// If BranchingContext.OnTrue, branch on true. Otherwise, branch on false. /// </summary> public BranchingContext CurrentBranchingContext { get { return _brctxt; } } //----------------------------------------------- // Storage //----------------------------------------------- /// <summary> /// Returns information about how and where iterator values are stored. /// </summary> public StorageDescriptor Storage { get { return _storage; } set { _storage = value; } } /// <summary> /// Push current item onto the stack without affecting Location. /// </summary> public void PushValue() { switch (_storage.Location) { case ItemLocation.Stack: _helper.Emit(OpCodes.Dup); break; case ItemLocation.Parameter: _helper.LoadParameter(_storage.ParameterLocation); break; case ItemLocation.Local: _helper.Emit(OpCodes.Ldloc, _storage.LocalLocation); break; case ItemLocation.Current: _helper.Emit(OpCodes.Ldloca, _storage.CurrentLocation); _helper.Call(_storage.CurrentLocation.LocalType.GetMethod("get_Current")); break; default: Debug.Assert(false, "Invalid location: " + _storage.Location); break; } } /// <summary> /// Ensure that the current item is pushed onto the stack. /// </summary> public void EnsureStack() { switch (_storage.Location) { case ItemLocation.Stack: // Already on the stack return; case ItemLocation.Parameter: case ItemLocation.Local: case ItemLocation.Current: PushValue(); break; case ItemLocation.Global: // Call method that computes the value of this global value _helper.LoadQueryRuntime(); _helper.Call(_storage.GlobalLocation); break; default: Debug.Assert(false, "Invalid location: " + _storage.Location); break; } _storage = _storage.ToStack(); } /// <summary> /// If the current item is on the stack, move it to a local variable. /// </summary> public void EnsureNoStack(string locName) { if (_storage.Location == ItemLocation.Stack) EnsureLocal(locName); } /// <summary> /// If current item is not already in a local variable, then move it to a local variable of the specified name. /// </summary> public void EnsureLocal(string locName) { if (_storage.Location != ItemLocation.Local) { if (_storage.IsCached) EnsureLocal(_helper.DeclareLocal(locName, typeof(IList<>).MakeGenericType(_storage.ItemStorageType))); else EnsureLocal(_helper.DeclareLocal(locName, _storage.ItemStorageType)); } } /// <summary> /// Ensure that current item is saved to the specified local variable. /// </summary> public void EnsureLocal(LocalBuilder bldr) { if (_storage.LocalLocation != bldr) { // Push value onto stack and then save to bldr EnsureStack(); _helper.Emit(OpCodes.Stloc, bldr); _storage = _storage.ToLocal(bldr); } } /// <summary> /// Discard the current item if it is pushed onto the stack. /// </summary> public void DiscardStack() { if (_storage.Location == ItemLocation.Stack) { _helper.Emit(OpCodes.Pop); _storage = StorageDescriptor.None(); } } /// <summary> /// Ensure that the iterator's items are not cached, and that the current item is pushed onto the stack. /// </summary> public void EnsureStackNoCache() { EnsureNoCache(); EnsureStack(); } /// <summary> /// Ensure that the iterator's items are not cached, and that if the current item is pushed onto the stack, /// that it is moved to a local variable. /// </summary> public void EnsureNoStackNoCache(string locName) { EnsureNoCache(); EnsureNoStack(locName); } /// <summary> /// Ensure that the iterator's items are not cached, and that if the current item is not already in a local, /// variable, that it is moved to a local variable of the specified name. /// </summary> public void EnsureLocalNoCache(string locName) { EnsureNoCache(); EnsureLocal(locName); } /// <summary> /// Ensure that the iterator's items are not cached and that the current item is saved to the specified local variable. /// </summary> public void EnsureLocalNoCache(LocalBuilder bldr) { EnsureNoCache(); EnsureLocal(bldr); } /// <summary> /// Each XmlQueryType has multiple legal CLR representations. Ensure that all items returned by this iterator are in /// the Clr representation specified by "storageTypeDest". /// </summary> public void EnsureItemStorageType(XmlQueryType xmlType, Type storageTypeDest) { // If source type = destination type, then done if (_storage.ItemStorageType == storageTypeDest) goto SetStorageType; Debug.Assert(_storage.ItemStorageType == typeof(XPathItem) || storageTypeDest == typeof(XPathItem), "EnsureItemStorageType must convert to or from Item"); // If items are cached, if (_storage.IsCached) { // Check for special case of IList<XPathNavigator> -> IList<XPathItem> if (_storage.ItemStorageType == typeof(XPathNavigator)) { EnsureStack(); _helper.Call(XmlILMethods.NavsToItems); goto SetStorageType; } // Check for special case of IList<XPathItem> -> IList<XPathNavigator> if (storageTypeDest == typeof(XPathNavigator)) { EnsureStack(); _helper.Call(XmlILMethods.ItemsToNavs); goto SetStorageType; } } // Iterate over each item, and convert each to the destination type EnsureStackNoCache(); // If source type is Item, if (_storage.ItemStorageType == typeof(XPathItem)) { // Then downcast to Navigator if (storageTypeDest == typeof(XPathNavigator)) { _helper.Emit(OpCodes.Castclass, typeof(XPathNavigator)); } else { // Call ValueAs methods for atomic types _helper.CallValueAs(storageTypeDest); } goto SetStorageType; } else if (_storage.ItemStorageType == typeof(XPathNavigator)) { // No-op if converting from XPathNavigator to XPathItem Debug.Assert(storageTypeDest == typeof(XPathItem), "Must be converting from XPathNavigator to XPathItem"); goto SetStorageType; } // Destination type must be item, so generate code to create an XmlAtomicValue _helper.LoadInteger(_helper.StaticData.DeclareXmlType(xmlType)); _helper.LoadQueryRuntime(); _helper.Call(XmlILMethods.StorageMethods[_storage.ItemStorageType].ToAtomicValue); SetStorageType: _storage = _storage.ToStorageType(storageTypeDest); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using OmniSharp.Models; using OmniSharp.Roslyn.CSharp.Services.Highlighting; using OmniSharp.Tests; using Xunit; namespace OmniSharp.Roslyn.CSharp.Tests { public class HighlightFacts { [Fact] public async Task HighlightSingleLine() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", Lines = new[] { 4 } }); AssertSyntax(regions.Highlights, code, 3, Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("int", "keyword"), Token("n", "identifier"), Token("=", "operator"), Token("true", "keyword"), Token(";", "punctuation"), Token("}", "punctuation")); } [Fact] public async Task HighlightEntireFile() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs" }); AssertSyntax(regions.Highlights, code, 0, Token("namespace", "keyword"), Token("N1", "identifier"), Token("{", "punctuation"), Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("int", "keyword"), Token("n", "identifier"), Token("=", "operator"), Token("true", "keyword"), Token(";", "punctuation"), Token("}", "punctuation"), Token("}", "punctuation")); } [Fact] public async Task HighlightStringInterpolation() { var code = @" class C1 { string s = $""{5}""; } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs" }); AssertSyntax(regions.Highlights, code, 0, Token("class", "keyword"), Token("C1", "class name"), Token("{", "punctuation"), Token("string", "keyword"), Token("s", "identifier"), Token("=", "operator"), Token("$\"", "string"), Token("{", "punctuation"), Token("5", "number"), Token("}", "punctuation"), Token("\"", "string"), Token(";", "punctuation"), Token("}", "punctuation")); } private void AssertSyntax(IEnumerable<HighlightSpan> regions, string code, int startLine, params TokenSpec[] expected) { var arr = regions.ToArray(); var lineNo = startLine; var lastIndex = 0; var lines = Microsoft.CodeAnalysis.Text.SourceText.From(code).Lines; for (var i = 0; i < arr.Length; i++) { var tokenSpec = expected[i]; var region = arr[i]; string line; int start, end; do { line = lines[lineNo].ToString(); start = line.IndexOf(tokenSpec.Text, lastIndex); if (start == -1) { if(++lineNo >= lines.Count) { throw new Exception($"Could not find token {tokenSpec.Text} in the code"); } lastIndex = 0; } } while (start == -1); end = start + tokenSpec.Text.Length; lastIndex = end; Assert.Equal(tokenSpec.Kind, region.Kind); Assert.Equal(lineNo, region.StartLine - 1); Assert.Equal(lineNo, region.EndLine - 1); Assert.Equal(start, region.StartColumn - 1); Assert.Equal(end, region.EndColumn - 1); } Assert.Equal(expected.Length, arr.Length); } [Fact] public async Task HighlightExcludesUnwantedKeywords() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Keyword } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "keyword"); } [Fact] public async Task HighlightExcludesUnwantedPunctuation() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Punctuation } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "punctuation"); } [Fact] public async Task HighlightExcludesUnwantedOperators() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Operator } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "operator"); } [Fact] public async Task HighlightExcludesUnwantedIdentifiers() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Identifier } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind == "identifier"); } [Fact] public async Task HighlightExcludesUnwantedNames() { var code = @" namespace N1 { class C1 { int n = true; } } "; var workspace = await TestHelpers.CreateSimpleWorkspace(new Dictionary<string, string> { { "a.cs", code } }); var controller = new HighlightingService(workspace); var regions = await controller.Handle(new HighlightRequest() { FileName = "a.cs", ExcludeClassifications = new [] { HighlightClassification.Name } }); Assert.DoesNotContain(regions.Highlights, x => x.Kind.EndsWith(" name")); } private TokenSpec Token(string text, string kind) { return new TokenSpec(kind, text); } private class TokenSpec { public string Text { get; } public string Kind { get; } public TokenSpec(string kind, string text) { Kind = kind; Text = text; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: conformance.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Conformance { /// <summary>Holder for reflection information generated from conformance.proto</summary> public static partial class ConformanceReflection { #region Descriptor /// <summary>File descriptor for conformance.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ConformanceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChFjb25mb3JtYW5jZS5wcm90bxILY29uZm9ybWFuY2UiowEKEkNvbmZvcm1h", "bmNlUmVxdWVzdBIaChBwcm90b2J1Zl9wYXlsb2FkGAEgASgMSAASFgoManNv", "bl9wYXlsb2FkGAIgASgJSAASOAoXcmVxdWVzdGVkX291dHB1dF9mb3JtYXQY", "AyABKA4yFy5jb25mb3JtYW5jZS5XaXJlRm9ybWF0EhQKDG1lc3NhZ2VfdHlw", "ZRgEIAEoCUIJCgdwYXlsb2FkIrEBChNDb25mb3JtYW5jZVJlc3BvbnNlEhUK", "C3BhcnNlX2Vycm9yGAEgASgJSAASGQoPc2VyaWFsaXplX2Vycm9yGAYgASgJ", "SAASFwoNcnVudGltZV9lcnJvchgCIAEoCUgAEhoKEHByb3RvYnVmX3BheWxv", "YWQYAyABKAxIABIWCgxqc29uX3BheWxvYWQYBCABKAlIABIRCgdza2lwcGVk", "GAUgASgJSABCCAoGcmVzdWx0KjUKCldpcmVGb3JtYXQSDwoLVU5TUEVDSUZJ", "RUQQABIMCghQUk9UT0JVRhABEggKBEpTT04QAkIhCh9jb20uZ29vZ2xlLnBy", "b3RvYnVmLmNvbmZvcm1hbmNlYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::Conformance.WireFormat), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceRequest), global::Conformance.ConformanceRequest.Parser, new[]{ "ProtobufPayload", "JsonPayload", "RequestedOutputFormat", "MessageType" }, new[]{ "Payload" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Conformance.ConformanceResponse), global::Conformance.ConformanceResponse.Parser, new[]{ "ParseError", "SerializeError", "RuntimeError", "ProtobufPayload", "JsonPayload", "Skipped" }, new[]{ "Result" }, null, null) })); } #endregion } #region Enums public enum WireFormat { [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, [pbr::OriginalName("PROTOBUF")] Protobuf = 1, [pbr::OriginalName("JSON")] Json = 2, } #endregion #region Messages /// <summary> /// Represents a single test case's input. The testee should: /// /// 1. parse this proto (which should always succeed) /// 2. parse the protobuf or JSON payload in "payload" (which may fail) /// 3. if the parse succeeded, serialize the message in the requested format. /// </summary> public sealed partial class ConformanceRequest : pb::IMessage<ConformanceRequest> { private static readonly pb::MessageParser<ConformanceRequest> _parser = new pb::MessageParser<ConformanceRequest>(() => new ConformanceRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConformanceRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Conformance.ConformanceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest(ConformanceRequest other) : this() { requestedOutputFormat_ = other.requestedOutputFormat_; messageType_ = other.messageType_; switch (other.PayloadCase) { case PayloadOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case PayloadOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceRequest Clone() { return new ConformanceRequest(this); } /// <summary>Field number for the "protobuf_payload" field.</summary> public const int ProtobufPayloadFieldNumber = 1; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString ProtobufPayload { get { return payloadCase_ == PayloadOneofCase.ProtobufPayload ? (pb::ByteString) payload_ : pb::ByteString.Empty; } set { payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); payloadCase_ = PayloadOneofCase.ProtobufPayload; } } /// <summary>Field number for the "json_payload" field.</summary> public const int JsonPayloadFieldNumber = 2; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JsonPayload { get { return payloadCase_ == PayloadOneofCase.JsonPayload ? (string) payload_ : ""; } set { payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); payloadCase_ = PayloadOneofCase.JsonPayload; } } /// <summary>Field number for the "requested_output_format" field.</summary> public const int RequestedOutputFormatFieldNumber = 3; private global::Conformance.WireFormat requestedOutputFormat_ = 0; /// <summary> /// Which format should the testee serialize its message to? /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Conformance.WireFormat RequestedOutputFormat { get { return requestedOutputFormat_; } set { requestedOutputFormat_ = value; } } /// <summary>Field number for the "message_type" field.</summary> public const int MessageTypeFieldNumber = 4; private string messageType_ = ""; /// <summary> /// The full name for the test message to use; for the moment, either: /// protobuf_test_messages.proto3.TestAllTypesProto3 or /// protobuf_test_messages.proto2.TestAllTypesProto2. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string MessageType { get { return messageType_; } set { messageType_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } private object payload_; /// <summary>Enum of possible cases for the "payload" oneof.</summary> public enum PayloadOneofCase { None = 0, ProtobufPayload = 1, JsonPayload = 2, } private PayloadOneofCase payloadCase_ = PayloadOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public PayloadOneofCase PayloadCase { get { return payloadCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearPayload() { payloadCase_ = PayloadOneofCase.None; payload_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConformanceRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConformanceRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ProtobufPayload != other.ProtobufPayload) return false; if (JsonPayload != other.JsonPayload) return false; if (RequestedOutputFormat != other.RequestedOutputFormat) return false; if (MessageType != other.MessageType) return false; if (PayloadCase != other.PayloadCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (payloadCase_ == PayloadOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); if (payloadCase_ == PayloadOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); if (RequestedOutputFormat != 0) hash ^= RequestedOutputFormat.GetHashCode(); if (MessageType.Length != 0) hash ^= MessageType.GetHashCode(); hash ^= (int) payloadCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (payloadCase_ == PayloadOneofCase.ProtobufPayload) { output.WriteRawTag(10); output.WriteBytes(ProtobufPayload); } if (payloadCase_ == PayloadOneofCase.JsonPayload) { output.WriteRawTag(18); output.WriteString(JsonPayload); } if (RequestedOutputFormat != 0) { output.WriteRawTag(24); output.WriteEnum((int) RequestedOutputFormat); } if (MessageType.Length != 0) { output.WriteRawTag(34); output.WriteString(MessageType); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (payloadCase_ == PayloadOneofCase.ProtobufPayload) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); } if (payloadCase_ == PayloadOneofCase.JsonPayload) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); } if (RequestedOutputFormat != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) RequestedOutputFormat); } if (MessageType.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(MessageType); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConformanceRequest other) { if (other == null) { return; } if (other.RequestedOutputFormat != 0) { RequestedOutputFormat = other.RequestedOutputFormat; } if (other.MessageType.Length != 0) { MessageType = other.MessageType; } switch (other.PayloadCase) { case PayloadOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case PayloadOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ProtobufPayload = input.ReadBytes(); break; } case 18: { JsonPayload = input.ReadString(); break; } case 24: { requestedOutputFormat_ = (global::Conformance.WireFormat) input.ReadEnum(); break; } case 34: { MessageType = input.ReadString(); break; } } } } } /// <summary> /// Represents a single test case's output. /// </summary> public sealed partial class ConformanceResponse : pb::IMessage<ConformanceResponse> { private static readonly pb::MessageParser<ConformanceResponse> _parser = new pb::MessageParser<ConformanceResponse>(() => new ConformanceResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConformanceResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Conformance.ConformanceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse(ConformanceResponse other) : this() { switch (other.ResultCase) { case ResultOneofCase.ParseError: ParseError = other.ParseError; break; case ResultOneofCase.SerializeError: SerializeError = other.SerializeError; break; case ResultOneofCase.RuntimeError: RuntimeError = other.RuntimeError; break; case ResultOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case ResultOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; case ResultOneofCase.Skipped: Skipped = other.Skipped; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConformanceResponse Clone() { return new ConformanceResponse(this); } /// <summary>Field number for the "parse_error" field.</summary> public const int ParseErrorFieldNumber = 1; /// <summary> /// This string should be set to indicate parsing failed. The string can /// provide more information about the parse error if it is available. /// /// Setting this string does not necessarily mean the testee failed the /// test. Some of the test cases are intentionally invalid input. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ParseError { get { return resultCase_ == ResultOneofCase.ParseError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.ParseError; } } /// <summary>Field number for the "serialize_error" field.</summary> public const int SerializeErrorFieldNumber = 6; /// <summary> /// If the input was successfully parsed but errors occurred when /// serializing it to the requested output format, set the error message in /// this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string SerializeError { get { return resultCase_ == ResultOneofCase.SerializeError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.SerializeError; } } /// <summary>Field number for the "runtime_error" field.</summary> public const int RuntimeErrorFieldNumber = 2; /// <summary> /// This should be set if some other error occurred. This will always /// indicate that the test failed. The string can provide more information /// about the failure. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string RuntimeError { get { return resultCase_ == ResultOneofCase.RuntimeError ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.RuntimeError; } } /// <summary>Field number for the "protobuf_payload" field.</summary> public const int ProtobufPayloadFieldNumber = 3; /// <summary> /// If the input was successfully parsed and the requested output was /// protobuf, serialize it to protobuf and set it in this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString ProtobufPayload { get { return resultCase_ == ResultOneofCase.ProtobufPayload ? (pb::ByteString) result_ : pb::ByteString.Empty; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.ProtobufPayload; } } /// <summary>Field number for the "json_payload" field.</summary> public const int JsonPayloadFieldNumber = 4; /// <summary> /// If the input was successfully parsed and the requested output was JSON, /// serialize to JSON and set it in this field. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string JsonPayload { get { return resultCase_ == ResultOneofCase.JsonPayload ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.JsonPayload; } } /// <summary>Field number for the "skipped" field.</summary> public const int SkippedFieldNumber = 5; /// <summary> /// For when the testee skipped the test, likely because a certain feature /// wasn't supported, like JSON input/output. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Skipped { get { return resultCase_ == ResultOneofCase.Skipped ? (string) result_ : ""; } set { result_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); resultCase_ = ResultOneofCase.Skipped; } } private object result_; /// <summary>Enum of possible cases for the "result" oneof.</summary> public enum ResultOneofCase { None = 0, ParseError = 1, SerializeError = 6, RuntimeError = 2, ProtobufPayload = 3, JsonPayload = 4, Skipped = 5, } private ResultOneofCase resultCase_ = ResultOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ResultOneofCase ResultCase { get { return resultCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearResult() { resultCase_ = ResultOneofCase.None; result_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConformanceResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConformanceResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ParseError != other.ParseError) return false; if (SerializeError != other.SerializeError) return false; if (RuntimeError != other.RuntimeError) return false; if (ProtobufPayload != other.ProtobufPayload) return false; if (JsonPayload != other.JsonPayload) return false; if (Skipped != other.Skipped) return false; if (ResultCase != other.ResultCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (resultCase_ == ResultOneofCase.ParseError) hash ^= ParseError.GetHashCode(); if (resultCase_ == ResultOneofCase.SerializeError) hash ^= SerializeError.GetHashCode(); if (resultCase_ == ResultOneofCase.RuntimeError) hash ^= RuntimeError.GetHashCode(); if (resultCase_ == ResultOneofCase.ProtobufPayload) hash ^= ProtobufPayload.GetHashCode(); if (resultCase_ == ResultOneofCase.JsonPayload) hash ^= JsonPayload.GetHashCode(); if (resultCase_ == ResultOneofCase.Skipped) hash ^= Skipped.GetHashCode(); hash ^= (int) resultCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (resultCase_ == ResultOneofCase.ParseError) { output.WriteRawTag(10); output.WriteString(ParseError); } if (resultCase_ == ResultOneofCase.RuntimeError) { output.WriteRawTag(18); output.WriteString(RuntimeError); } if (resultCase_ == ResultOneofCase.ProtobufPayload) { output.WriteRawTag(26); output.WriteBytes(ProtobufPayload); } if (resultCase_ == ResultOneofCase.JsonPayload) { output.WriteRawTag(34); output.WriteString(JsonPayload); } if (resultCase_ == ResultOneofCase.Skipped) { output.WriteRawTag(42); output.WriteString(Skipped); } if (resultCase_ == ResultOneofCase.SerializeError) { output.WriteRawTag(50); output.WriteString(SerializeError); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (resultCase_ == ResultOneofCase.ParseError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ParseError); } if (resultCase_ == ResultOneofCase.SerializeError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(SerializeError); } if (resultCase_ == ResultOneofCase.RuntimeError) { size += 1 + pb::CodedOutputStream.ComputeStringSize(RuntimeError); } if (resultCase_ == ResultOneofCase.ProtobufPayload) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(ProtobufPayload); } if (resultCase_ == ResultOneofCase.JsonPayload) { size += 1 + pb::CodedOutputStream.ComputeStringSize(JsonPayload); } if (resultCase_ == ResultOneofCase.Skipped) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Skipped); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConformanceResponse other) { if (other == null) { return; } switch (other.ResultCase) { case ResultOneofCase.ParseError: ParseError = other.ParseError; break; case ResultOneofCase.SerializeError: SerializeError = other.SerializeError; break; case ResultOneofCase.RuntimeError: RuntimeError = other.RuntimeError; break; case ResultOneofCase.ProtobufPayload: ProtobufPayload = other.ProtobufPayload; break; case ResultOneofCase.JsonPayload: JsonPayload = other.JsonPayload; break; case ResultOneofCase.Skipped: Skipped = other.Skipped; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { ParseError = input.ReadString(); break; } case 18: { RuntimeError = input.ReadString(); break; } case 26: { ProtobufPayload = input.ReadBytes(); break; } case 34: { JsonPayload = input.ReadString(); break; } case 42: { Skipped = input.ReadString(); break; } case 50: { SerializeError = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.InteropServices; using Microsoft.DotNet.Cli.Build; using Microsoft.DotNet.Cli.Build.Framework; using Microsoft.DotNet.InternalAbstractions; using static Microsoft.DotNet.Cli.Build.Framework.BuildHelpers; namespace Microsoft.DotNet.Host.Build { public class DebTargets { [Target(nameof(GenerateSharedHostDeb), nameof(GenerateHostFxrDeb), nameof(GenerateSharedFrameworkDeb))] [BuildPlatforms(BuildPlatform.Ubuntu, BuildPlatform.Debian)] [BuildArchitectures(BuildArchitecture.x64)] public static BuildTargetResult GenerateDebs(BuildTargetContext c) { return c.Success(); } [Target] [BuildPlatforms(BuildPlatform.Ubuntu, BuildPlatform.Debian)] public static BuildTargetResult GenerateSharedHostDeb(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(GenerateSharedHostDeb)}"); return c.Success(); } var packageName = Monikers.GetDebianSharedHostPackageName(c); var version = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostVersion.ToString(); var inputRoot = c.BuildContext.Get<string>("SharedHostPublishRoot"); var debFile = c.BuildContext.Get<string>("SharedHostInstallerFile"); var manPagesDir = Path.Combine(Dirs.RepoRoot, "Documentation", "manpages"); var debianConfigFile = Path.Combine(Dirs.DebPackagingConfig, "dotnet-sharedhost-debian_config.json"); var debianConfigVariables = new Dictionary<string, string>() { { "SHARED_HOST_BRAND_NAME", Monikers.GetSharedHostBrandName(c) } }; var debCreator = new DebPackageCreator( DotNetCli.Stage0, Dirs.Intermediate, dotnetDebToolPackageSource: Dirs.Packages); debCreator.CreateDeb( debianConfigFile, packageName, version, inputRoot, debianConfigVariables, debFile, manPagesDir); return c.Success(); } [Target] [BuildPlatforms(BuildPlatform.Ubuntu, BuildPlatform.Debian)] public static BuildTargetResult GenerateHostFxrDeb(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(GenerateHostFxrDeb)}"); return c.Success(); } var hostFxrVersion = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostFxrVersion.ToString(); var packageName = Monikers.GetDebianHostFxrPackageName(hostFxrVersion); var sharedHostVersion = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostVersion.ToString(); var inputRoot = c.BuildContext.Get<string>("HostFxrPublishRoot"); var debFile = c.BuildContext.Get<string>("HostFxrInstallerFile"); var debianConfigFile = Path.Combine(Dirs.DebPackagingConfig, "dotnet-hostfxr-debian_config.json"); var debianConfigVariables = new Dictionary<string, string>() { { "HOSTFXR_BRAND_NAME", Monikers.GetHostFxrBrandName(c) }, { "SHARED_HOST_DEBIAN_VERSION", sharedHostVersion }, { "HOSTFXR_NUGET_VERSION", hostFxrVersion }, { "HOSTFXR_DEBIAN_PACKAGE_NAME", packageName } }; var debCreator = new DebPackageCreator( DotNetCli.Stage0, Dirs.Intermediate, dotnetDebToolPackageSource: Dirs.Packages); debCreator.CreateDeb( debianConfigFile, packageName, hostFxrVersion, inputRoot, debianConfigVariables, debFile); return c.Success(); } [Target(nameof(InstallSharedHost))] [BuildPlatforms(BuildPlatform.Ubuntu, BuildPlatform.Debian)] public static BuildTargetResult GenerateSharedFrameworkDeb(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(GenerateSharedFrameworkDeb)}"); return c.Success(); } var sharedFrameworkNugetVersion = c.BuildContext.Get<string>("SharedFrameworkNugetVersion"); var packageName = Monikers.GetDebianSharedFrameworkPackageName(sharedFrameworkNugetVersion); var sharedHostVersion = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostVersion.ToString(); var hostFxrVersion = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostFxrVersion.ToString(); var hostfxrDebianPackageName = Monikers.GetDebianHostFxrPackageName(hostFxrVersion); var version = c.BuildContext.Get<string>("SharedFrameworkNugetVersion"); var inputRoot = c.BuildContext.Get<string>("SharedFrameworkPublishRoot"); var debFile = c.BuildContext.Get<string>("SharedFrameworkInstallerFile"); var debianConfigFile = Path.Combine(Dirs.DebPackagingConfig, "dotnet-sharedframework-debian_config.json"); var debianConfigVariables = new Dictionary<string, string>() { { "SHARED_HOST_DEBIAN_VERSION", sharedHostVersion }, { "HOSTFXR_DEBIAN_PACKAGE_NAME", hostfxrDebianPackageName}, { "HOSTFXR_DEBIAN_VERSION", hostFxrVersion }, { "SHARED_FRAMEWORK_DEBIAN_PACKAGE_NAME", packageName }, { "SHARED_FRAMEWORK_NUGET_NAME", Monikers.SharedFrameworkName }, { "SHARED_FRAMEWORK_NUGET_VERSION", c.BuildContext.Get<string>("SharedFrameworkNugetVersion")}, { "SHARED_FRAMEWORK_BRAND_NAME", Monikers.GetSharedFxBrandName(c) } }; var debCreator = new DebPackageCreator( DotNetCli.Stage0, Dirs.Intermediate, dotnetDebToolPackageSource: Dirs.Packages); debCreator.CreateDeb( debianConfigFile, packageName, version, inputRoot, debianConfigVariables, debFile); return c.Success(); } [Target(nameof(InstallSharedFramework), nameof(RemovePackages))] [BuildPlatforms(BuildPlatform.Ubuntu, BuildPlatform.Debian)] [BuildArchitectures(BuildArchitecture.x64)] public static BuildTargetResult TestDebInstaller(BuildTargetContext c) { return c.Success(); } [Target] public static BuildTargetResult InstallSharedHost(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(InstallSharedHost)}"); return c.Success(); } InstallPackage(c.BuildContext.Get<string>("SharedHostInstallerFile")); return c.Success(); } [Target(nameof(InstallSharedHost))] public static BuildTargetResult InstallHostFxr(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(InstallHostFxr)}"); return c.Success(); } InstallPackage(c.BuildContext.Get<string>("HostFxrInstallerFile")); return c.Success(); } [Target(nameof(InstallHostFxr))] public static BuildTargetResult InstallSharedFramework(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(InstallSharedFramework)}"); return c.Success(); } InstallPackage(c.BuildContext.Get<string>("SharedFrameworkInstallerFile")); return c.Success(); } [Target] public static BuildTargetResult RemovePackages(BuildTargetContext c) { // Ubuntu 16.04 Jenkins Machines don't have docker or debian package build tools // So we need to skip this target if the tools aren't present. // https://github.com/dotnet/core-setup/issues/167 if (ShouldSkipBuildDebPackages() || DebuildNotPresent()) { c.Info("Debuild not present, skipping target: {nameof(RemovePackages)}"); return c.Success(); } var sharedFrameworkNugetVersion = c.BuildContext.Get<string>("SharedFrameworkNugetVersion"); var hostFxrVersion = c.BuildContext.Get<HostVersion>("HostVersion").LockedHostFxrVersion.ToString(); IEnumerable<string> orderedPackageNames = new List<string>() { Monikers.GetDebianSharedFrameworkPackageName(sharedFrameworkNugetVersion), Monikers.GetDebianHostFxrPackageName(hostFxrVersion), Monikers.GetDebianSharedHostPackageName(c) }; foreach(var packageName in orderedPackageNames) { RemovePackage(packageName); } return c.Success(); } private static void InstallPackage(string packagePath) { Cmd("sudo", "dpkg", "-i", packagePath) .Execute() .EnsureSuccessful(); } private static void RemovePackage(string packageName) { Cmd("sudo", "dpkg", "-r", packageName) .Execute() .EnsureSuccessful(); } private static bool DebuildNotPresent() { return Cmd("/usr/bin/env", "debuild", "-h").Execute().ExitCode != 0; } private static bool ShouldSkipBuildDebPackages() { return Environment.GetEnvironmentVariable("DOTNET_BUILD_SKIP_DEB_PACKAGING") == "1"; } } }
// ZipStorer, by Jaime Olivares // Website: zipstorer.codeplex.com // Version: 2.35 (March 14, 2010) using System.Collections.Generic; using System.Text; namespace System.IO.Compression { /// <summary> /// Unique class for compression/decompression file. Represents a Zip file. /// </summary> public class ZipStorer : IDisposable { /// <summary> /// Compression method enumeration /// </summary> public enum Compression : ushort { /// <summary>Uncompressed storage</summary> Store = 0, /// <summary>Deflate compression method</summary> Deflate = 8 } /// <summary> /// Represents an entry in Zip file directory /// </summary> public struct ZipFileEntry { /// <summary>Compression method</summary> public Compression Method; /// <summary>Full path and filename as stored in Zip</summary> public string FilenameInZip; /// <summary>Original file size</summary> public uint FileSize; /// <summary>Compressed file size</summary> public uint CompressedSize; /// <summary>Offset of header information inside Zip storage</summary> public uint HeaderOffset; /// <summary>Offset of file inside Zip storage</summary> public uint FileOffset; /// <summary>Size of header information</summary> public uint HeaderSize; /// <summary>32-bit checksum of entire file</summary> public uint Crc32; /// <summary>Last modification time of file</summary> public DateTime ModifyTime; /// <summary>User comment for file</summary> public string Comment; /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary> public bool EncodeUTF8; /// <summary>Overriden method</summary> /// <returns>Filename in Zip</returns> public override string ToString() { return this.FilenameInZip; } } #region Public fields /// <summary>True if UTF8 encoding for filename and comments, false if default (CP 437)</summary> public bool EncodeUTF8 = false; /// <summary>Force deflate algotithm even if it inflates the stored file. Off by default.</summary> public bool ForceDeflating = false; #endregion #region Private fields // List of files to store private List<ZipFileEntry> Files = new List<ZipFileEntry>(); // Filename of storage file private string FileName; // Stream object of storage file private Stream ZipFileStream; // General comment private string Comment = ""; // Central dir image private byte[] CentralDirImage = null; // Existing files in zip private ushort ExistingFiles = 0; // File access for Open method private FileAccess Access; // Static CRC32 Table private static UInt32[] CrcTable = null; // Default filename encoder private static Encoding DefaultEncoding = Encoding.GetEncoding(437); #endregion #region Public methods // Static constructor. Just invoked once in order to create the CRC32 lookup table. static ZipStorer() { // Generate CRC32 table CrcTable = new UInt32[256]; for (int i = 0; i < CrcTable.Length; i++) { UInt32 c = (UInt32)i; for (int j = 0; j < 8; j++) { if ((c & 1) != 0) c = 3988292384 ^ (c >> 1); else c >>= 1; } CrcTable[i] = c; } } /// <summary> /// Method to create a new storage file /// </summary> /// <param name="_filename">Full path of Zip file to create</param> /// <param name="_comment">General comment for Zip file</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Create(string _filename, string _comment) { Stream stream = new FileStream(_filename, FileMode.Create, FileAccess.ReadWrite); ZipStorer zip = Create(stream, _comment); zip.Comment = _comment; zip.FileName = _filename; return zip; } /// <summary> /// Method to create a new zip storage in a stream /// </summary> /// <param name="_stream"></param> /// <param name="_comment"></param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Create(Stream _stream, string _comment) { ZipStorer zip = new ZipStorer(); zip.Comment = _comment; zip.ZipFileStream = _stream; zip.Access = FileAccess.Write; return zip; } /// <summary> /// Method to open an existing storage file /// </summary> /// <param name="_filename">Full path of Zip file to open</param> /// <param name="_access">File access mode as used in FileStream constructor</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Open(string _filename, FileAccess _access) { Stream stream = (Stream)new FileStream(_filename, FileMode.Open, _access == FileAccess.Read ? FileAccess.Read : FileAccess.ReadWrite); ZipStorer zip = Open(stream, _access); zip.FileName = _filename; return zip; } /// <summary> /// Method to open an existing storage from stream /// </summary> /// <param name="_stream">Already opened stream with zip contents</param> /// <param name="_access">File access mode for stream operations</param> /// <returns>A valid ZipStorer object</returns> public static ZipStorer Open(Stream _stream, FileAccess _access) { if (!_stream.CanSeek && _access != FileAccess.Read) throw new InvalidOperationException("Stream cannot seek"); ZipStorer zip = new ZipStorer(); //zip.FileName = _filename; zip.ZipFileStream = _stream; zip.Access = _access; if (zip.ReadFileInfo()) return zip; throw new System.IO.InvalidDataException(); } /// <summary> /// Add full contents of a file into the Zip storage /// </summary> /// <param name="_method">Compression method</param> /// <param name="_pathname">Full path of file to add to Zip storage</param> /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param> /// <param name="_comment">Comment for stored file</param> public void AddFile(Compression _method, string _pathname, string _filenameInZip, string _comment) { if (Access == FileAccess.Read) throw new InvalidOperationException("Writing is not alowed"); FileStream stream = new FileStream(_pathname, FileMode.Open, FileAccess.Read); AddStream(_method, _filenameInZip, stream, File.GetLastWriteTime(_pathname), _comment); stream.Close(); } /// <summary> /// Add full contents of a stream into the Zip storage /// </summary> /// <param name="_method">Compression method</param> /// <param name="_filenameInZip">Filename and path as desired in Zip directory</param> /// <param name="_source">Stream object containing the data to store in Zip</param> /// <param name="_modTime">Modification time of the data to store</param> /// <param name="_comment">Comment for stored file</param> public void AddStream(Compression _method, string _filenameInZip, Stream _source, DateTime _modTime, string _comment) { if (Access == FileAccess.Read) throw new InvalidOperationException("Writing is not alowed"); long offset; if (this.Files.Count==0) offset = 0; else { ZipFileEntry last = this.Files[this.Files.Count-1]; offset = last.HeaderOffset + last.HeaderSize; } // Prepare the fileinfo ZipFileEntry zfe = new ZipFileEntry(); zfe.Method = _method; zfe.EncodeUTF8 = this.EncodeUTF8; zfe.FilenameInZip = NormalizedFilename(_filenameInZip); zfe.Comment = (_comment == null ? "" : _comment); // Even though we write the header now, it will have to be rewritten, since we don't know compressed size or crc. zfe.Crc32 = 0; // to be updated later zfe.HeaderOffset = (uint)this.ZipFileStream.Position; // offset within file of the start of this local record zfe.ModifyTime = _modTime; // Write local header WriteLocalHeader(ref zfe); zfe.FileOffset = (uint)this.ZipFileStream.Position; // Write file to zip (store) Store(ref zfe, _source); _source.Close(); this.UpdateCrcAndSizes(ref zfe); Files.Add(zfe); } /// <summary> /// Updates central directory (if pertinent) and close the Zip storage /// </summary> /// <remarks>This is a required step, unless automatic dispose is used</remarks> public void Close() { if (this.Access != FileAccess.Read) { uint centralOffset = (uint)this.ZipFileStream.Position; uint centralSize = 0; if (this.CentralDirImage != null) this.ZipFileStream.Write(CentralDirImage, 0, CentralDirImage.Length); for (int i = 0; i < Files.Count; i++) { long pos = this.ZipFileStream.Position; this.WriteCentralDirRecord(Files[i]); centralSize += (uint)(this.ZipFileStream.Position - pos); } if (this.CentralDirImage != null) this.WriteEndRecord(centralSize + (uint)CentralDirImage.Length, centralOffset); else this.WriteEndRecord(centralSize, centralOffset); } if (this.ZipFileStream != null) { this.ZipFileStream.Flush(); this.ZipFileStream.Dispose(); this.ZipFileStream = null; } } /// <summary> /// Read all the file records in the central directory /// </summary> /// <returns>List of all entries in directory</returns> public List<ZipFileEntry> ReadCentralDir() { if (this.CentralDirImage == null) throw new InvalidOperationException("Central directory currently does not exist"); List<ZipFileEntry> result = new List<ZipFileEntry>(); for (int pointer = 0; pointer < this.CentralDirImage.Length; ) { uint signature = BitConverter.ToUInt32(CentralDirImage, pointer); if (signature != 0x02014b50) break; bool encodeUTF8 = (BitConverter.ToUInt16(CentralDirImage, pointer + 8) & 0x0800) != 0; ushort method = BitConverter.ToUInt16(CentralDirImage, pointer + 10); uint modifyTime = BitConverter.ToUInt32(CentralDirImage, pointer + 12); uint crc32 = BitConverter.ToUInt32(CentralDirImage, pointer + 16); uint comprSize = BitConverter.ToUInt32(CentralDirImage, pointer + 20); uint fileSize = BitConverter.ToUInt32(CentralDirImage, pointer + 24); ushort filenameSize = BitConverter.ToUInt16(CentralDirImage, pointer + 28); ushort extraSize = BitConverter.ToUInt16(CentralDirImage, pointer + 30); ushort commentSize = BitConverter.ToUInt16(CentralDirImage, pointer + 32); uint headerOffset = BitConverter.ToUInt32(CentralDirImage, pointer + 42); uint headerSize = (uint)( 46 + filenameSize + extraSize + commentSize); Encoding encoder = encodeUTF8 ? Encoding.UTF8 : DefaultEncoding; ZipFileEntry zfe = new ZipFileEntry(); zfe.Method = (Compression)method; zfe.FilenameInZip = encoder.GetString(CentralDirImage, pointer + 46, filenameSize); zfe.FileOffset = GetFileOffset(headerOffset); zfe.FileSize = fileSize; zfe.CompressedSize = comprSize; zfe.HeaderOffset = headerOffset; zfe.HeaderSize = headerSize; zfe.Crc32 = crc32; zfe.ModifyTime = DosTimeToDateTime(modifyTime); if (commentSize > 0) zfe.Comment = encoder.GetString(CentralDirImage, pointer + 46 + filenameSize + extraSize, commentSize); result.Add(zfe); pointer += (46 + filenameSize + extraSize + commentSize); } return result; } /// <summary> /// Copy the contents of a stored file into a physical file /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_filename">Name of file to store uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry _zfe, string _filename) { // Make sure the parent directory exist string path = System.IO.Path.GetDirectoryName(_filename); if (!Directory.Exists(path)) Directory.CreateDirectory(path); // Check it is directory. If so, do nothing if (Directory.Exists(_filename)) return true; Stream output = new FileStream(_filename, FileMode.Create, FileAccess.Write); bool result = ExtractFile(_zfe, output); if (result) output.Close(); File.SetCreationTime(_filename, _zfe.ModifyTime); File.SetLastWriteTime(_filename, _zfe.ModifyTime); return result; } /// <summary> /// Copy the contents of a stored file into an opened stream /// </summary> /// <param name="_zfe">Entry information of file to extract</param> /// <param name="_stream">Stream to store the uncompressed data</param> /// <returns>True if success, false if not.</returns> /// <remarks>Unique compression methods are Store and Deflate</remarks> public bool ExtractFile(ZipFileEntry _zfe, Stream _stream) { if (!_stream.CanWrite) throw new InvalidOperationException("Stream cannot be written"); // check signature byte[] signature = new byte[4]; this.ZipFileStream.Seek(_zfe.HeaderOffset, SeekOrigin.Begin); this.ZipFileStream.Read(signature, 0, 4); if (BitConverter.ToUInt32(signature, 0) != 0x04034b50) return false; // Select input stream for inflating or just reading Stream inStream; if (_zfe.Method == Compression.Store) inStream = this.ZipFileStream; else if (_zfe.Method == Compression.Deflate) inStream = new DeflateStream(this.ZipFileStream, CompressionMode.Decompress, true); else return false; // Buffered copy byte[] buffer = new byte[16384]; this.ZipFileStream.Seek(_zfe.FileOffset, SeekOrigin.Begin); uint bytesPending = _zfe.FileSize; while (bytesPending > 0) { int bytesRead = inStream.Read(buffer, 0, (int)Math.Min(bytesPending, buffer.Length)); _stream.Write(buffer, 0, bytesRead); bytesPending -= (uint)bytesRead; } _stream.Flush(); if (_zfe.Method == Compression.Deflate) inStream.Dispose(); return true; } /// <summary> /// Removes one of many files in storage. It creates a new Zip file. /// </summary> /// <param name="_zip">Reference to the current Zip object</param> /// <param name="_zfes">List of Entries to remove from storage</param> /// <returns>True if success, false if not</returns> /// <remarks>This method only works for storage of type FileStream</remarks> public static bool RemoveEntries(ref ZipStorer _zip, List<ZipFileEntry> _zfes) { if (!(_zip.ZipFileStream is FileStream)) throw new InvalidOperationException("RemoveEntries is allowed just over streams of type FileStream"); //Get full list of entries List<ZipFileEntry> fullList = _zip.ReadCentralDir(); //In order to delete we need to create a copy of the zip file excluding the selected items string tempZipName = Path.GetTempFileName(); string tempEntryName = Path.GetTempFileName(); try { ZipStorer tempZip = ZipStorer.Create(tempZipName, string.Empty); foreach (ZipFileEntry zfe in fullList) { if (!_zfes.Contains(zfe)) { if (_zip.ExtractFile(zfe, tempEntryName)) { tempZip.AddFile(zfe.Method, tempEntryName, zfe.FilenameInZip, zfe.Comment); } } } _zip.Close(); tempZip.Close(); File.Delete(_zip.FileName); File.Move(tempZipName, _zip.FileName); _zip = ZipStorer.Open(_zip.FileName, _zip.Access); } catch { return false; } finally { if (File.Exists(tempZipName)) File.Delete(tempZipName); if (File.Exists(tempEntryName)) File.Delete(tempEntryName); } return true; } #endregion #region Private methods // Calculate the file offset by reading the corresponding local header private uint GetFileOffset(uint _headerOffset) { byte[] buffer = new byte[2]; this.ZipFileStream.Seek(_headerOffset + 26, SeekOrigin.Begin); this.ZipFileStream.Read(buffer, 0, 2); ushort filenameSize = BitConverter.ToUInt16(buffer, 0); this.ZipFileStream.Read(buffer, 0, 2); ushort extraSize = BitConverter.ToUInt16(buffer, 0); return (uint)(30 + filenameSize + extraSize + _headerOffset); } /* Local file header: local file header signature 4 bytes (0x04034b50) version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes filename length 2 bytes extra field length 2 bytes filename (variable size) extra field (variable size) */ private void WriteLocalHeader(ref ZipFileEntry _zfe) { long pos = this.ZipFileStream.Position; Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip); this.ZipFileStream.Write(new byte[] { 80, 75, 3, 4, 20, 0}, 0, 6); // No extra header this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time this.ZipFileStream.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, 0, 12); // unused CRC, un/compressed size, updated later this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // filename length this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length); _zfe.HeaderSize = (uint)(this.ZipFileStream.Position - pos); } /* Central directory's File header: central file header signature 4 bytes (0x02014b50) version made by 2 bytes version needed to extract 2 bytes general purpose bit flag 2 bytes compression method 2 bytes last mod file time 2 bytes last mod file date 2 bytes crc-32 4 bytes compressed size 4 bytes uncompressed size 4 bytes filename length 2 bytes extra field length 2 bytes file comment length 2 bytes disk number start 2 bytes internal file attributes 2 bytes external file attributes 4 bytes relative offset of local header 4 bytes filename (variable size) extra field (variable size) file comment (variable size) */ private void WriteCentralDirRecord(ZipFileEntry _zfe) { Encoding encoder = _zfe.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedFilename = encoder.GetBytes(_zfe.FilenameInZip); byte[] encodedComment = encoder.GetBytes(_zfe.Comment); this.ZipFileStream.Write(new byte[] { 80, 75, 1, 2, 23, 0xB, 20, 0 }, 0, 8); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)(_zfe.EncodeUTF8 ? 0x0800 : 0)), 0, 2); // filename and comment encoding this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Write(BitConverter.GetBytes(DateTimeToDosTime(_zfe.ModifyTime)), 0, 4); // zipping date and time this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // file CRC this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // compressed file size this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // uncompressed file size this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedFilename.Length), 0, 2); // Filename in zip this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // extra length this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // disk=0 this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // file type: binary this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0), 0, 2); // Internal file attributes this.ZipFileStream.Write(BitConverter.GetBytes((ushort)0x8100), 0, 2); // External file attributes (normal/readable) this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.HeaderOffset), 0, 4); // Offset of header this.ZipFileStream.Write(encodedFilename, 0, encodedFilename.Length); this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length); } /* End of central dir record: end of central dir signature 4 bytes (0x06054b50) number of this disk 2 bytes number of the disk with the start of the central directory 2 bytes total number of entries in the central dir on this disk 2 bytes total number of entries in the central dir 2 bytes size of the central directory 4 bytes offset of start of central directory with respect to the starting disk number 4 bytes zipfile comment length 2 bytes zipfile comment (variable size) */ private void WriteEndRecord(uint _size, uint _offset) { Encoding encoder = this.EncodeUTF8 ? Encoding.UTF8 : DefaultEncoding; byte[] encodedComment = encoder.GetBytes(this.Comment); this.ZipFileStream.Write(new byte[] { 80, 75, 5, 6, 0, 0, 0, 0 }, 0, 8); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)Files.Count+ExistingFiles), 0, 2); this.ZipFileStream.Write(BitConverter.GetBytes(_size), 0, 4); this.ZipFileStream.Write(BitConverter.GetBytes(_offset), 0, 4); this.ZipFileStream.Write(BitConverter.GetBytes((ushort)encodedComment.Length), 0, 2); this.ZipFileStream.Write(encodedComment, 0, encodedComment.Length); } // Copies all source file into storage file private void Store(ref ZipFileEntry _zfe, Stream _source) { byte[] buffer = new byte[16384]; int bytesRead; uint totalRead = 0; Stream outStream; long posStart = this.ZipFileStream.Position; long sourceStart = _source.Position; if (_zfe.Method == Compression.Store) outStream = this.ZipFileStream; else outStream = new DeflateStream(this.ZipFileStream, CompressionMode.Compress, true); _zfe.Crc32 = 0 ^ 0xffffffff; do { bytesRead = _source.Read(buffer, 0, buffer.Length); totalRead += (uint)bytesRead; if (bytesRead > 0) { outStream.Write(buffer, 0, bytesRead); for (uint i = 0; i < bytesRead; i++) { _zfe.Crc32 = ZipStorer.CrcTable[(_zfe.Crc32 ^ buffer[i]) & 0xFF] ^ (_zfe.Crc32 >> 8); } } } while (bytesRead == buffer.Length); outStream.Flush(); if (_zfe.Method == Compression.Deflate) outStream.Dispose(); _zfe.Crc32 ^= 0xffffffff; _zfe.FileSize = totalRead; _zfe.CompressedSize = (uint)(this.ZipFileStream.Position - posStart); // Verify for real compression if (_zfe.Method == Compression.Deflate && !this.ForceDeflating && _source.CanSeek && _zfe.CompressedSize > _zfe.FileSize) { // Start operation again with Store algorithm _zfe.Method = Compression.Store; this.ZipFileStream.Position = posStart; this.ZipFileStream.SetLength(posStart); _source.Position = sourceStart; this.Store(ref _zfe, _source); } } /* DOS Date and time: MS-DOS date. The date is a packed value with the following format. Bits Description 0-4 Day of the month (1?1) 5-8 Month (1 = January, 2 = February, and so on) 9-15 Year offset from 1980 (add 1980 to get actual year) MS-DOS time. The time is a packed value with the following format. Bits Description 0-4 Second divided by 2 5-10 Minute (0?9) 11-15 Hour (0?3 on a 24-hour clock) */ private uint DateTimeToDosTime(DateTime _dt) { return (uint)( (_dt.Second / 2) | (_dt.Minute << 5) | (_dt.Hour << 11) | (_dt.Day<<16) | (_dt.Month << 21) | ((_dt.Year - 1980) << 25)); } private DateTime DosTimeToDateTime(uint _dt) { return new DateTime( (int)(_dt >> 25) + 1980, (int)(_dt >> 21) & 15, (int)(_dt >> 16) & 31, (int)(_dt >> 11) & 31, (int)(_dt >> 5) & 63, (int)(_dt & 31) * 2); } /* CRC32 algorithm The 'magic number' for the CRC is 0xdebb20e3. The proper CRC pre and post conditioning is used, meaning that the CRC register is pre-conditioned with all ones (a starting value of 0xffffffff) and the value is post-conditioned by taking the one's complement of the CRC residual. If bit 3 of the general purpose flag is set, this field is set to zero in the local header and the correct value is put in the data descriptor and in the central directory. */ private void UpdateCrcAndSizes(ref ZipFileEntry _zfe) { long lastPos = this.ZipFileStream.Position; // remember position this.ZipFileStream.Position = _zfe.HeaderOffset + 8; this.ZipFileStream.Write(BitConverter.GetBytes((ushort)_zfe.Method), 0, 2); // zipping method this.ZipFileStream.Position = _zfe.HeaderOffset + 14; this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.Crc32), 0, 4); // Update CRC this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.CompressedSize), 0, 4); // Compressed size this.ZipFileStream.Write(BitConverter.GetBytes(_zfe.FileSize), 0, 4); // Uncompressed size this.ZipFileStream.Position = lastPos; // restore position } // Replaces backslashes with slashes to store in zip header private string NormalizedFilename(string _filename) { string filename = _filename.Replace('\\', '/'); int pos = filename.IndexOf(':'); if (pos >= 0) filename = filename.Remove(0, pos + 1); return filename.Trim('/'); } // Reads the end-of-central-directory record private bool ReadFileInfo() { if (this.ZipFileStream.Length < 22) return false; try { this.ZipFileStream.Seek(-17, SeekOrigin.End); BinaryReader br = new BinaryReader(this.ZipFileStream); do { this.ZipFileStream.Seek(-5, SeekOrigin.Current); UInt32 sig = br.ReadUInt32(); if (sig == 0x06054b50) { this.ZipFileStream.Seek(6, SeekOrigin.Current); UInt16 entries = br.ReadUInt16(); Int32 centralSize = br.ReadInt32(); UInt32 centralDirOffset = br.ReadUInt32(); UInt16 commentSize = br.ReadUInt16(); // check if comment field is the very last data in file if (this.ZipFileStream.Position + commentSize != this.ZipFileStream.Length) return false; // Copy entire central directory to a memory buffer this.ExistingFiles = entries; this.CentralDirImage = new byte[centralSize]; this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin); this.ZipFileStream.Read(this.CentralDirImage, 0, centralSize); // Leave the pointer at the begining of central dir, to append new files this.ZipFileStream.Seek(centralDirOffset, SeekOrigin.Begin); return true; } } while (this.ZipFileStream.Position > 0); } catch { } return false; } #endregion #region IDisposable Members /// <summary> /// Closes the Zip file stream /// </summary> public void Dispose() { this.Close(); } #endregion } }
/** * This example demonstrates reading and writing SAML metadata including the following: * * 1. Creating an IdP entity descriptor. * 2. Creating an SP entity descriptor. * 3. Reading an IdP entity descriptor. * 4. Reading an SP entity descriptor. */ using System; using System.Collections; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Text; using System.Xml; using ComponentSpace.SAML2; using ComponentSpace.SAML2.Metadata; using ComponentSpace.SAML2.Utility; namespace MetadataExample { class Program { private const string idpPrivateKeyFileName = "idp.pfx"; private const string spPrivateKeyFileName = "sp.pfx"; private const string privateKeyFilePassword = "password"; private const string idpCertificateFileName = "idp.cer"; private const string spCertificateFileName = "sp.cer"; // Creates a KeyInfo from the supplied X.509 certificate private static KeyInfo CreateKeyInfo(X509Certificate2 x509Certificate) { KeyInfoX509Data keyInfoX509Data = new KeyInfoX509Data(); keyInfoX509Data.AddCertificate(x509Certificate); KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(keyInfoX509Data); return keyInfo; } // Creates a KeyDescriptor from the supplied X.509 certificate private static KeyDescriptor CreateKeyDescriptor(X509Certificate2 x509Certificate) { KeyDescriptor keyDescriptor = new KeyDescriptor(); KeyInfo keyInfo = CreateKeyInfo(x509Certificate); keyDescriptor.KeyInfo = keyInfo.GetXml(); // Set the encryption method by specifying the entire XML. //XmlDocument xmlDocument = new XmlDocument(); //xmlDocument.PreserveWhitespace = true; //xmlDocument.LoadXml("<md:EncryptionMethod xmlns:md=\"urn:oasis:names:tc:SAML:2.0:metadata\" Algorithm=\"http://www.w3.org/2001/04/xmlenc#aes256-cbc\"/>"); //keyDescriptor.EncryptionMethods.Add(xmlDocument.DocumentElement); // Set the encryption method by specifying just the algorithm. //keyDescriptor.AddEncryptionMethod("http://www.w3.org/2001/04/xmlenc#aes256-cbc"); return keyDescriptor; } // Creates an IdP SSO descriptor private static IDPSSODescriptor CreateIDPSSODescriptor() { IDPSSODescriptor idpSSODescriptor = new IDPSSODescriptor(); idpSSODescriptor.WantAuthnRequestsSigned = true; idpSSODescriptor.ProtocolSupportEnumeration = SAML.NamespaceURIs.Protocol; X509Certificate2 x509Certificate = new X509Certificate2(idpCertificateFileName); idpSSODescriptor.KeyDescriptors.Add(CreateKeyDescriptor(x509Certificate)); IndexedEndpointType artifactResolutionService = new IndexedEndpointType(1, true); artifactResolutionService.Binding = SAMLIdentifiers.BindingURIs.SOAP; artifactResolutionService.Location = "https://www.idp.com/ArtifactResolutionService"; idpSSODescriptor.ArtifactResolutionServices.Add(artifactResolutionService); idpSSODescriptor.NameIDFormats.Add(SAMLIdentifiers.NameIdentifierFormats.Transient); EndpointType singleSignOnService = new EndpointType(SAMLIdentifiers.BindingURIs.HTTPRedirect, "https://www.idp.com/SSOService", null); idpSSODescriptor.SingleSignOnServices.Add(singleSignOnService); return idpSSODescriptor; } // Creates an IdP entity descriptor private static EntityDescriptor CreateIDPEntityDescriptor() { EntityDescriptor entityDescriptor = new EntityDescriptor(); entityDescriptor.EntityID = new EntityIDType("http://www.idp.com"); entityDescriptor.IDPSSODescriptors.Add(CreateIDPSSODescriptor()); Organization organization = new Organization(); organization.OrganizationNames.Add(new OrganizationName("IdP", "en")); organization.OrganizationDisplayNames.Add(new OrganizationDisplayName("IdP", "en")); organization.OrganizationURLs.Add(new OrganizationURL("www.idp.com", "en")); entityDescriptor.Organization = organization; ContactPerson contactPerson = new ContactPerson(); contactPerson.ContactTypeValue = "technical"; contactPerson.GivenName = "Joe"; contactPerson.Surname = "User"; contactPerson.EmailAddresses.Add("[email protected]"); entityDescriptor.ContactPeople.Add(contactPerson); return entityDescriptor; } // Creates an SP SSO descriptor private static SPSSODescriptor CreateSPSSODescriptor() { SPSSODescriptor spSSODescriptor = new SPSSODescriptor(); spSSODescriptor.ProtocolSupportEnumeration = SAML.NamespaceURIs.Protocol; X509Certificate2 x509Certificate = new X509Certificate2(spCertificateFileName); spSSODescriptor.KeyDescriptors.Add(CreateKeyDescriptor(x509Certificate)); IndexedEndpointType assertionConsumerService1 = new IndexedEndpointType(1, true); assertionConsumerService1.Binding = SAMLIdentifiers.BindingURIs.HTTPPost; assertionConsumerService1.Location = "https://www.idp.com/AssertionConsumerService/POST"; spSSODescriptor.AssertionConsumerServices.Add(assertionConsumerService1); IndexedEndpointType assertionConsumerService2 = new IndexedEndpointType(2, false); assertionConsumerService2.Binding = SAMLIdentifiers.BindingURIs.HTTPArtifact; assertionConsumerService2.Location = "https://www.idp.com/AssertionConsumerService/Artifact"; spSSODescriptor.AssertionConsumerServices.Add(assertionConsumerService2); spSSODescriptor.NameIDFormats.Add(SAMLIdentifiers.NameIdentifierFormats.Transient); return spSSODescriptor; } // Creates an SP entity descriptor private static EntityDescriptor CreateSPEntityDescriptor() { EntityDescriptor entityDescriptor = new EntityDescriptor(); entityDescriptor.EntityID = new EntityIDType("http://www.sp.com"); entityDescriptor.SPSSODescriptors.Add(CreateSPSSODescriptor()); Organization organization = new Organization(); organization.OrganizationNames.Add(new OrganizationName("SP", "en")); organization.OrganizationDisplayNames.Add(new OrganizationDisplayName("SP", "en")); organization.OrganizationURLs.Add(new OrganizationURL("www.sp.com", "en")); entityDescriptor.Organization = organization; ContactPerson contactPerson = new ContactPerson(); contactPerson.ContactTypeValue = "technical"; contactPerson.GivenName = "Jane"; contactPerson.Surname = "User"; contactPerson.EmailAddresses.Add("[email protected]"); entityDescriptor.ContactPeople.Add(contactPerson); return entityDescriptor; } // Reads the X.509 certificates contained within an IdP or SP SSO descriptor private static void ReadX509Certificates(RoleDescriptorType roleDescriptor) { foreach (KeyDescriptor keyDescriptor in roleDescriptor.KeyDescriptors) { KeyInfo keyInfo = new KeyInfo(); keyInfo.LoadXml(keyDescriptor.KeyInfo); IEnumerator enumerator = keyInfo.GetEnumerator(typeof(KeyInfoX509Data)); while (enumerator.MoveNext()) { KeyInfoX509Data keyInfoX509Data = (KeyInfoX509Data)enumerator.Current; foreach (X509Certificate2 x509Certificate in keyInfoX509Data.Certificates) { Console.WriteLine("X509 certificate: " + x509Certificate.ToString()); } } foreach (XmlElement xmlElement in keyDescriptor.EncryptionMethods) { Console.WriteLine("Encryption method: " + KeyDescriptor.GetEncryptionMethodAlgorithm(xmlElement)); } } } // Reads an entities descriptor private static void ReadEntitiesDescriptor(EntitiesDescriptor entitiesDescriptor) { foreach (EntityDescriptor entityDescriptor in entitiesDescriptor.EntityDescriptors) { ReadEntityDescriptor(entityDescriptor); } } // Reads an entity descriptor private static void ReadEntityDescriptor(EntityDescriptor entityDescriptor) { foreach (IDPSSODescriptor idpSSODescriptor in entityDescriptor.IDPSSODescriptors) { foreach (EndpointType singleSignOnService in idpSSODescriptor.SingleSignOnServices) { Console.WriteLine("Binding: " + singleSignOnService.Binding); Console.WriteLine("Location: " + singleSignOnService.Location); } ReadX509Certificates(idpSSODescriptor); } foreach (SPSSODescriptor spSSODescriptor in entityDescriptor.SPSSODescriptors) { foreach (EndpointType assertionConsumerService in spSSODescriptor.AssertionConsumerServices) { Console.WriteLine("Binding: " + assertionConsumerService.Binding); Console.WriteLine("Location: " + assertionConsumerService.Location); } ReadX509Certificates(spSSODescriptor); } foreach (OrganizationDisplayName organizationDisplayName in entityDescriptor.Organization.OrganizationDisplayNames) { Console.WriteLine("Organization: " + organizationDisplayName.Name); } } // Reads SAML v2.0 metadata private static void ReadMetadata(XmlElement xmlElement) { if (EntitiesDescriptor.IsValid(xmlElement)) { ReadEntitiesDescriptor(new EntitiesDescriptor(xmlElement)); } else if (EntityDescriptor.IsValid(xmlElement)) { ReadEntityDescriptor(new EntityDescriptor(xmlElement)); } else { throw new ArgumentException("Expecting entities descriptor or entity descriptor"); } } static void Main(string[] args) { // Create an IdP entity descriptor EntityDescriptor idpEntityDescriptor = CreateIDPEntityDescriptor(); // Convert the IdP entity descriptor to XML XmlElement xmlElement = idpEntityDescriptor.ToXml(); string s = xmlElement.OuterXml; Console.WriteLine(s); // Sign the IdP entity descriptor X509Certificate2 x509Certificate = new X509Certificate2(idpPrivateKeyFileName, privateKeyFilePassword); SAMLMetadataSignature.Generate(xmlElement, x509Certificate.PrivateKey, x509Certificate); Console.WriteLine(xmlElement.OuterXml); // Verify the IdP entity descriptor signature if (!SAMLMetadataSignature.Verify(xmlElement)) { throw new ArgumentException("The IdP entity descriptor signature failed to verify"); } // Read the IdP entity descriptor ReadMetadata(xmlElement); // Create an SP entity descriptor EntityDescriptor spEntityDescriptor = CreateSPEntityDescriptor(); // Convert the SP entity descriptor to XML xmlElement = spEntityDescriptor.ToXml(); Console.WriteLine(xmlElement.OuterXml); // Sign the SP entity descriptor x509Certificate = new X509Certificate2(spPrivateKeyFileName, privateKeyFilePassword); SAMLMetadataSignature.Generate(xmlElement, x509Certificate.PrivateKey, x509Certificate); Console.WriteLine(xmlElement.OuterXml); // Verify the SP entity descriptor signature if (!SAMLMetadataSignature.Verify(xmlElement)) { throw new ArgumentException("The SP entity descriptor signature failed to verify"); } // Read the SP entity descriptor ReadMetadata(xmlElement); } } }
//------------------------------------------------------------------------------ // <copyright file="SqlProfileProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Samples { using System.Web; using System.Web.UI; using System; using System.Web.Profile; using System.Web.Configuration; using System.Security.Principal; using System.Security.Permissions; using System.Globalization; using System.Runtime.Serialization; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using System.Reflection; using System.Xml.Serialization; using System.Text; using System.Configuration.Provider; using System.Configuration; using System.Web.Hosting; using System.Web.DataAccess; using System.Web.Util; /* TODO: * * Test page size/index stuff * 6. Utility/sproc generation * * REVIEW: * - Strings that are too long will throw an exception saying data will be truncated... * - Xml, Udt, Variant SqlDbDatatypes won't work (no corresponding column types for objects, for xml etc use strings) <add name="Timestamp" type="System.Byte[]" provider="R2" allowAnonymous="true" customProviderData="Timestamp;Timestamp"/> * * * DONE: * 1. Handle non string cases (double, date time, blob) * 2. Batch select up into one query, list<columns> * DeleteProfiles[] * 4. Implement other methods (GetProfiles, GetNumberInactive, DeleteInactive!) * Require LastActivityDate */ public class SqlTableProfileProvider : ProfileProvider { private string _appName; private Guid _appId; private bool _appIdSet; private string _sqlConnectionString; private int _commandTimeout; private string _table; public override void Initialize(string name, NameValueCollection config) { if (config == null) throw new ArgumentNullException("config"); if (String.IsNullOrEmpty(name)) name = "SqlTableProfileProvider"; if (string.IsNullOrEmpty(config["description"])) { config.Remove("description"); config.Add("description", "SqlTableProfileProvider"); } base.Initialize(name, config); string temp = config["connectionStringName"]; if (String.IsNullOrEmpty(temp)) throw new ProviderException("connectionStringName not specified"); _sqlConnectionString = SqlStoredProcedureProfileProvider.GetConnectionString(temp); if (String.IsNullOrEmpty(_sqlConnectionString)) { throw new ProviderException("connectionStringName not specified"); } _appName = config["applicationName"]; if (string.IsNullOrEmpty(_appName)) _appName = SqlStoredProcedureProfileProvider.GetDefaultAppName(); if (_appName.Length > 256) { throw new ProviderException("Application name too long"); } _table = config["table"]; if (string.IsNullOrEmpty(_table)) { throw new ProviderException("No table specified"); } EnsureValidTableOrColumnName(_table); string timeout = config["commandTimeout"]; if (string.IsNullOrEmpty(timeout) || !Int32.TryParse(timeout, out _commandTimeout)) { _commandTimeout = 30; } config.Remove("commandTimeout"); config.Remove("connectionStringName"); config.Remove("applicationName"); config.Remove("table"); if (config.Count > 0) { string attribUnrecognized = config.GetKey(0); if (!String.IsNullOrEmpty(attribUnrecognized)) throw new ProviderException("Unrecognized config attribute:" + attribUnrecognized); } } public override string ApplicationName { get { return _appName; } set { if (value == null) throw new ArgumentNullException("ApplicationName"); if (value.Length > 256) { throw new ProviderException("Application name too long"); } _appName = value; _appIdSet = false; } } private Guid AppId { get { if (!_appIdSet) { SqlConnection conn = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); SqlCommand cmd = new SqlCommand("dbo.aspnet_Applications_CreateApplication", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@applicationname", ApplicationName); cmd.Parameters.Add(CreateOutputParam("@ApplicationId", SqlDbType.UniqueIdentifier, 0)); cmd.ExecuteNonQuery(); _appId = (Guid)cmd.Parameters["@ApplicationId"].Value; _appIdSet = true; } finally { if (conn != null) { conn.Close(); } } } return _appId; } } private int CommandTimeout { get { return _commandTimeout; } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// private static string s_legalChars = "_@#$"; private static void EnsureValidTableOrColumnName(string name) { for (int i = 0; i < name.Length; ++i) { if (!Char.IsLetterOrDigit(name[i]) && s_legalChars.IndexOf(name[i]) == -1) throw new ProviderException("Table and column names cannot contain: "+name[i]); } } private void GetProfileDataFromTable(SettingsPropertyCollection properties, SettingsPropertyValueCollection svc, string username, SqlConnection conn) { List<ProfileColumnData> columnData = new List<ProfileColumnData>(properties.Count); StringBuilder commandText = new StringBuilder("SELECT u.UserID"); SqlCommand cmd = new SqlCommand(String.Empty, conn); int columnCount = 0; foreach (SettingsProperty prop in properties) { SettingsPropertyValue value = new SettingsPropertyValue(prop); svc.Add(value); string persistenceData = prop.Attributes["CustomProviderData"] as string; // If we can't find the table/column info we will ignore this data if (String.IsNullOrEmpty(persistenceData)) { // REVIEW: Perhaps we should throw instead? continue; } string[] chunk = persistenceData.Split(new char[] { ';' }); if (chunk.Length != 2) { // REVIEW: Perhaps we should throw instead? continue; } string columnName = chunk[0]; // REVIEW: Should we ignore case? SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true); columnData.Add(new ProfileColumnData(columnName, value, null /* not needed for get */, datatype)); commandText.Append(", "); commandText.Append("t."+columnName); ++columnCount; } commandText.Append(" FROM "+_table+" t, vw_aspnet_Users u WHERE u.ApplicationId = '").Append(AppId); commandText.Append("' AND u.UserName = LOWER(@Username) AND t.UserID = u.UserID"); cmd.CommandText = commandText.ToString(); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Username", username); SqlDataReader reader = null; try { reader = cmd.ExecuteReader(); //If no row exists in the database, then the default Profile values //from configuration are used. if (reader.Read()) { Guid userId = reader.GetGuid(0); for (int i = 0; i < columnData.Count; ++i) { object val = reader.GetValue(i+1); ProfileColumnData colData = columnData[i]; SettingsPropertyValue propValue = colData.PropertyValue; //Only initialize a SettingsPropertyValue for non-null values if (!(val is DBNull || val == null)) { propValue.PropertyValue = val; propValue.IsDirty = false; propValue.Deserialized = true; } } // need to close reader before we try to update the user if (reader != null) { reader.Close(); reader = null; } UpdateLastActivityDate(conn, userId); } } finally { if (reader != null) { reader.Close(); } } } private static void UpdateLastActivityDate(SqlConnection conn, Guid userId) { SqlCommand cmd = new SqlCommand("UPDATE aspnet_Users SET LastActivityDate = @LastUpdatedDate WHERE UserId = '" + userId + "'", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@LastUpdatedDate", DateTime.UtcNow); try { cmd.ExecuteNonQuery(); } finally { cmd.Dispose(); } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection collection) { SettingsPropertyValueCollection svc = new SettingsPropertyValueCollection(); if (collection == null || collection.Count < 1 || context == null) return svc; string username = (string)context["UserName"]; if (String.IsNullOrEmpty(username)) return svc; SqlConnection conn = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); GetProfileDataFromTable(collection, svc, username, conn); } finally { if (conn != null) { conn.Close(); } } return svc; } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Container struct for use in aggregating columns for queries private struct ProfileColumnData { public string ColumnName; public SettingsPropertyValue PropertyValue; public object Value; public SqlDbType DataType; public ProfileColumnData(string col, SettingsPropertyValue pv, object val, SqlDbType type) { EnsureValidTableOrColumnName(col); ColumnName = col; PropertyValue = pv; Value = val; DataType = type; } } public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection collection) { string username = (string)context["UserName"]; bool userIsAuthenticated = (bool)context["IsAuthenticated"]; if (username == null || username.Length < 1 || collection.Count < 1) return; SqlConnection conn = null; SqlDataReader reader = null; SqlCommand cmd = null; try { bool anyItemsToSave = false; // First make sure we have at least one item to save foreach (SettingsPropertyValue pp in collection) { if (pp.IsDirty) { if (!userIsAuthenticated) { bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"]; if (!allowAnonymous) continue; } anyItemsToSave = true; break; } } if (!anyItemsToSave) return; conn = new SqlConnection(_sqlConnectionString); conn.Open(); List<ProfileColumnData> columnData = new List<ProfileColumnData>(collection.Count); foreach (SettingsPropertyValue pp in collection) { if (!userIsAuthenticated) { bool allowAnonymous = (bool)pp.Property.Attributes["AllowAnonymous"]; if (!allowAnonymous) continue; } //Normal logic for original SQL provider //if (!pp.IsDirty && pp.UsingDefaultValue) // Not fetched from DB and not written to //Can eliminate unnecessary updates since we are using a table though if (!pp.IsDirty) continue; string persistenceData = pp.Property.Attributes["CustomProviderData"] as string; // If we can't find the table/column info we will ignore this data if (String.IsNullOrEmpty(persistenceData)) { // REVIEW: Perhaps we should throw instead? continue; } string[] chunk = persistenceData.Split(new char[] { ';' }); if (chunk.Length != 2) { // REVIEW: Perhaps we should throw instead? continue; } string columnName = chunk[0]; // REVIEW: Should we ignore case? SqlDbType datatype = (SqlDbType)Enum.Parse(typeof(SqlDbType), chunk[1], true); object value = null; // REVIEW: Is this handling null case correctly? if (pp.Deserialized && pp.PropertyValue == null) { // is value null? value = DBNull.Value; } else { value = pp.PropertyValue; } // REVIEW: Might be able to ditch datatype columnData.Add(new ProfileColumnData(columnName, pp, value, datatype)); } // Figure out userid, if we don't find a userid, go ahead and create a user in the aspnetUsers table Guid userId = Guid.Empty; cmd = new SqlCommand("SELECT u.UserId FROM vw_aspnet_Users u WHERE u.ApplicationId = '" + AppId + "' AND u.UserName = LOWER(@Username)", conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Username",username); try { reader = cmd.ExecuteReader(); if (reader.Read()) { userId = reader.GetGuid(0); } else { reader.Close(); cmd.Dispose(); reader = null; cmd = new SqlCommand("dbo.aspnet_Users_CreateUser", conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ApplicationId", AppId); cmd.Parameters.AddWithValue("@UserName", username); cmd.Parameters.AddWithValue("@IsUserAnonymous", !userIsAuthenticated); cmd.Parameters.AddWithValue("@LastActivityDate", DateTime.UtcNow); cmd.Parameters.Add(CreateOutputParam("@UserId", SqlDbType.UniqueIdentifier, 16)); cmd.ExecuteNonQuery(); userId = (Guid)cmd.Parameters["@userid"].Value; } } finally { if (reader != null) { reader.Close(); reader = null; } cmd.Dispose(); } // Figure out if the row already exists in the table and use appropriate SELECT/UPDATE cmd = new SqlCommand(String.Empty, conn); StringBuilder sqlCommand = new StringBuilder("IF EXISTS (SELECT 1 FROM ").Append(_table); sqlCommand.Append(" WHERE UserId = @UserId) "); cmd.Parameters.AddWithValue("@UserId", userId); // Build up strings used in the query StringBuilder columnStr = new StringBuilder(); StringBuilder valueStr = new StringBuilder(); StringBuilder setStr = new StringBuilder(); int count = 0; foreach (ProfileColumnData data in columnData) { columnStr.Append(", "); valueStr.Append(", "); columnStr.Append(data.ColumnName); string valueParam = "@Value" + count; valueStr.Append(valueParam); cmd.Parameters.AddWithValue(valueParam, data.Value); // REVIEW: Can't update Timestamps? if (data.DataType != SqlDbType.Timestamp) { if (count > 0) { setStr.Append(","); } setStr.Append(data.ColumnName); setStr.Append("="); setStr.Append(valueParam); } ++count; } columnStr.Append(",LastUpdatedDate "); valueStr.Append(",@LastUpdatedDate"); setStr.Append(",LastUpdatedDate=@LastUpdatedDate"); cmd.Parameters.AddWithValue("@LastUpdatedDate", DateTime.UtcNow); sqlCommand.Append("BEGIN UPDATE ").Append(_table).Append(" SET ").Append(setStr.ToString()); sqlCommand.Append(" WHERE UserId = '").Append(userId).Append("'"); sqlCommand.Append("END ELSE BEGIN INSERT ").Append(_table).Append(" (UserId").Append(columnStr.ToString()); sqlCommand.Append(") VALUES ('").Append(userId).Append("'").Append(valueStr.ToString()).Append(") END"); cmd.CommandText = sqlCommand.ToString(); cmd.CommandType = CommandType.Text; cmd.ExecuteNonQuery(); // Need to close reader before we try to update if (reader != null) { reader.Close(); reader = null; } UpdateLastActivityDate(conn, userId); } finally { if (reader != null) reader.Close(); if (cmd != null) cmd.Dispose(); if (conn != null) conn.Close(); } } //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// private static SqlParameter CreateInputParam(string paramName, SqlDbType dbType, object objValue) { SqlParameter param = new SqlParameter(paramName, dbType); if (objValue == null) objValue = String.Empty; param.Value = objValue; return param; } private static SqlParameter CreateOutputParam(string paramName, SqlDbType dbType, int size) { SqlParameter param = new SqlParameter(paramName, dbType); param.Direction = ParameterDirection.Output; param.Size = size; return param; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Mangement APIs from ProfileProvider class public override int DeleteProfiles(ProfileInfoCollection profiles) { if (profiles == null) { throw new ArgumentNullException("profiles"); } if (profiles.Count < 1) { throw new ArgumentException("Profiles collection is empty"); } string[] usernames = new string[profiles.Count]; int iter = 0; foreach (ProfileInfo profile in profiles) { usernames[iter++] = profile.UserName; } return DeleteProfiles(usernames); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override int DeleteProfiles(string[] usernames) { if (usernames == null || usernames.Length < 1) { return 0; } int numProfilesDeleted = 0; bool beginTranCalled = false; try { SqlConnection conn = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); SqlCommand cmd; int numUsersRemaing = usernames.Length; while (numUsersRemaing > 0) { cmd = new SqlCommand(String.Empty, conn); cmd.Parameters.AddWithValue("@UserName0", usernames[usernames.Length - numUsersRemaing]); StringBuilder allUsers = new StringBuilder("@UserName0"); numUsersRemaing--; int userIndex = 1; for (int iter = usernames.Length - numUsersRemaing; iter < usernames.Length; iter++) { // REVIEW: Should we check length of command string instead of parameter lengths? if (allUsers.Length + usernames[iter].Length + 3 >= 4000) break; string userNameParam = "@UserName" + userIndex; allUsers.Append(","); allUsers.Append(userNameParam); cmd.Parameters.AddWithValue(userNameParam, usernames[iter]); numUsersRemaing--; ++userIndex; } // We don't need to start a transaction if we can finish this in one sql command if (!beginTranCalled && numUsersRemaing > 0) { SqlCommand beginCmd = new SqlCommand("BEGIN TRANSACTION", conn); beginCmd.ExecuteNonQuery(); beginTranCalled = true; } cmd.CommandText = "DELETE FROM " + _table + " WHERE UserId IN ( SELECT u.UserId FROM vw_aspnet_Users u WHERE u.ApplicationId = '" + AppId + "' AND u.UserName IN (" + allUsers.ToString() + "))"; cmd.CommandTimeout = CommandTimeout; numProfilesDeleted += cmd.ExecuteNonQuery(); } if (beginTranCalled) { cmd = new SqlCommand("COMMIT TRANSACTION", conn); cmd.ExecuteNonQuery(); beginTranCalled = false; } } catch { if (beginTranCalled) { SqlCommand cmd = new SqlCommand("ROLLBACK TRANSACTION", conn); cmd.ExecuteNonQuery(); beginTranCalled = false; } throw; } finally { if (conn != null) { conn.Close(); conn = null; } } } catch { throw; } return numProfilesDeleted; } private string GenerateQuery(bool delete, ProfileAuthenticationOption authenticationOption) { StringBuilder cmdStr = new StringBuilder(200); if (delete) cmdStr.Append("DELETE FROM "); else cmdStr.Append("SELECT COUNT(*) FROM "); cmdStr.Append(_table); cmdStr.Append(" WHERE UserId IN (SELECT u.UserId FROM vw_aspnet_Users u WHERE u.ApplicationId = '").Append(AppId); cmdStr.Append("' AND (u.LastActivityDate <= @InactiveSinceDate)"); switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: cmdStr.Append(" AND u.IsAnonymous = 1"); break; case ProfileAuthenticationOption.Authenticated: cmdStr.Append(" AND u.IsAnonymous = 0"); break; case ProfileAuthenticationOption.All: // Want to delete all profiles here, so nothing more needed break; } cmdStr.Append(")"); return cmdStr.ToString(); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override int DeleteInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { try { SqlConnection conn = null; SqlCommand cmd = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); cmd = new SqlCommand(GenerateQuery(true, authenticationOption), conn); cmd.CommandTimeout = CommandTimeout; cmd.Parameters.Add(CreateInputParam("@InactiveSinceDate", SqlDbType.DateTime, userInactiveSinceDate.ToUniversalTime())); return cmd.ExecuteNonQuery(); } finally { if (cmd != null) { cmd.Dispose(); } if (conn != null) { conn.Close(); conn = null; } } } catch { throw; } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override int GetNumberOfInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate) { SqlConnection conn = null; SqlCommand cmd = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); cmd = new SqlCommand(GenerateQuery(false, authenticationOption), conn); cmd.CommandTimeout = CommandTimeout; cmd.Parameters.Add(CreateInputParam("@InactiveSinceDate", SqlDbType.DateTime, userInactiveSinceDate.ToUniversalTime())); object o = cmd.ExecuteScalar(); if (o == null || !(o is int)) return 0; return (int)o; } finally { if (cmd != null) cmd.Dispose(); if (conn != null) { conn.Close(); conn = null; } } } // TODO: Implement size private StringBuilder GenerateTempInsertQueryForGetProfiles(ProfileAuthenticationOption authenticationOption) { StringBuilder cmdStr = new StringBuilder(200); cmdStr.Append("INSERT INTO #PageIndexForProfileUsers (UserId) "); cmdStr.Append("SELECT u.UserId FROM vw_aspnet_Users u, ").Append(_table); cmdStr.Append(" p WHERE ApplicationId = '").Append(AppId); cmdStr.Append("' AND u.UserId = p.UserId"); switch (authenticationOption) { case ProfileAuthenticationOption.Anonymous: cmdStr.Append(" AND u.IsAnonymous = 1"); break; case ProfileAuthenticationOption.Authenticated: cmdStr.Append(" AND u.IsAnonymous = 0"); break; case ProfileAuthenticationOption.All: // Want to delete all profiles here, so nothing more needed break; } return cmdStr; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override ProfileInfoCollection GetAllProfiles(ProfileAuthenticationOption authenticationOption, int pageIndex, int pageSize, out int totalRecords) { StringBuilder insertQuery = GenerateTempInsertQueryForGetProfiles(authenticationOption); return GetProfilesForQuery(null, pageIndex, pageSize, insertQuery, out totalRecords); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override ProfileInfoCollection GetAllInactiveProfiles(ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { StringBuilder insertQuery = GenerateTempInsertQueryForGetProfiles(authenticationOption); insertQuery.Append(" AND u.LastActivityDate <= @InactiveSinceDate"); SqlParameter[] args = new SqlParameter[1]; args[0] = CreateInputParam("@InactiveSinceDate", SqlDbType.DateTime, userInactiveSinceDate.ToUniversalTime()); return GetProfilesForQuery(args, pageIndex, pageSize, insertQuery, out totalRecords); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords) { StringBuilder insertQuery = GenerateTempInsertQueryForGetProfiles(authenticationOption); insertQuery.Append(" AND u.UserName LIKE LOWER(@UserName)"); SqlParameter[] args = new SqlParameter[1]; args[0] = CreateInputParam("@UserName", SqlDbType.NVarChar, usernameToMatch); return GetProfilesForQuery(args, pageIndex, pageSize, insertQuery, out totalRecords); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public override ProfileInfoCollection FindInactiveProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, DateTime userInactiveSinceDate, int pageIndex, int pageSize, out int totalRecords) { StringBuilder insertQuery = GenerateTempInsertQueryForGetProfiles(authenticationOption); insertQuery.Append(" AND u.UserName LIKE LOWER(@UserName) AND u.LastActivityDate <= @InactiveSinceDate"); SqlParameter[] args = new SqlParameter[2]; args[0] = CreateInputParam("@InactiveSinceDate", SqlDbType.DateTime, userInactiveSinceDate.ToUniversalTime()); args[1] = CreateInputParam("@UserName", SqlDbType.NVarChar, usernameToMatch); return GetProfilesForQuery(args, pageIndex, pageSize, insertQuery, out totalRecords); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// // Private methods ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// private ProfileInfoCollection GetProfilesForQuery(SqlParameter[] insertArgs, int pageIndex, int pageSize, StringBuilder insertQuery, out int totalRecords) { if (pageIndex < 0) throw new ArgumentException("pageIndex"); if (pageSize < 1) throw new ArgumentException("pageSize"); long lowerBound = (long)pageIndex * pageSize; long upperBound = lowerBound + pageSize - 1; if (upperBound > Int32.MaxValue) { throw new ArgumentException("pageIndex and pageSize"); } SqlConnection conn = null; SqlDataReader reader = null; SqlCommand cmd = null; try { conn = new SqlConnection(_sqlConnectionString); conn.Open(); StringBuilder cmdStr = new StringBuilder(200); // Create a temp table TO store the select results cmd = new SqlCommand("CREATE TABLE #PageIndexForProfileUsers(IndexId int IDENTITY (0, 1) NOT NULL, UserId uniqueidentifier)", conn); cmd.CommandTimeout = CommandTimeout; cmd.ExecuteNonQuery(); cmd.Dispose(); insertQuery.Append(" ORDER BY UserName"); cmd = new SqlCommand(insertQuery.ToString(), conn); cmd.CommandTimeout = CommandTimeout; if (insertArgs != null) { foreach (SqlParameter arg in insertArgs) cmd.Parameters.Add(arg); } cmd.ExecuteNonQuery(); cmd.Dispose(); cmdStr = new StringBuilder(200); cmdStr.Append("SELECT u.UserName, u.IsAnonymous, u.LastActivityDate, p.LastUpdatedDate FROM vw_aspnet_Users u, ").Append(_table); cmdStr.Append(" p, #PageIndexForProfileUsers i WHERE u.UserId = p.UserId AND p.UserId = i.UserId AND i.IndexId >= "); cmdStr.Append(lowerBound).Append(" AND i.IndexId <= ").Append(upperBound); cmd = new SqlCommand(cmdStr.ToString(), conn); cmd.CommandTimeout = CommandTimeout; reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess); ProfileInfoCollection profiles = new ProfileInfoCollection(); while (reader.Read()) { string username; DateTime dtLastActivity, dtLastUpdated = DateTime.UtcNow; bool isAnon; username = reader.GetString(0); isAnon = reader.GetBoolean(1); dtLastActivity = DateTime.SpecifyKind(reader.GetDateTime(2), DateTimeKind.Utc); dtLastUpdated = DateTime.SpecifyKind(reader.GetDateTime(3), DateTimeKind.Utc); profiles.Add(new ProfileInfo(username, isAnon, dtLastActivity, dtLastUpdated, 0)); } totalRecords = profiles.Count; if (reader != null) { reader.Close(); reader = null; } cmd.Dispose(); // Cleanup, REVIEW: should move to finally? cmd = new SqlCommand("DROP TABLE #PageIndexForProfileUsers", conn); cmd.ExecuteNonQuery(); return profiles; } finally { if (reader != null) reader.Close(); if (cmd != null) cmd.Dispose(); if (conn != null) { conn.Close(); conn = null; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Specialized; using System.Globalization; using System.Net.Mail; using System.Text; namespace System.Net.Mime { /// <summary> /// Summary description for HeaderCollection. /// </summary> internal class HeaderCollection : NameValueCollection { private MimeBasePart _part = null; // default constructor // intentionally override the default comparer in the derived base class internal HeaderCollection() : base(StringComparer.OrdinalIgnoreCase) { } public override void Remove(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name)); } MailHeaderID id = MailHeaderInfo.GetID(name); if (id == MailHeaderID.ContentType && _part != null) { _part.ContentType = null; } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { ((MimePart)_part).ContentDisposition = null; } base.Remove(name); } public override string Get(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name)); } MailHeaderID id = MailHeaderInfo.GetID(name); if (id == MailHeaderID.ContentType && _part != null) { _part.ContentType.PersistIfNeeded(this, false); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false); } return base.Get(name); } public override string[] GetValues(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (name == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name)); } MailHeaderID id = MailHeaderInfo.GetID(name); if (id == MailHeaderID.ContentType && _part != null) { _part.ContentType.PersistIfNeeded(this, false); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { ((MimePart)_part).ContentDisposition.PersistIfNeeded(this, false); } return base.GetValues(name); } internal void InternalRemove(string name) => base.Remove(name); //set an existing header's value internal void InternalSet(string name, string value) => base.Set(name, value); //add a new header and set its value internal void InternalAdd(string name, string value) { if (MailHeaderInfo.IsSingleton(name)) { base.Set(name, value); } else { base.Add(name, value); } } public override void Set(string name, string value) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (name == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name)); } if (value == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(value)), nameof(name)); } if (!MimeBasePart.IsAscii(name, false)) { throw new FormatException(SR.Format(SR.InvalidHeaderName)); } // normalize the case of well known headers name = MailHeaderInfo.NormalizeCase(name); MailHeaderID id = MailHeaderInfo.GetID(name); value = value.Normalize(NormalizationForm.FormC); if (id == MailHeaderID.ContentType && _part != null) { _part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { ((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this); } else { base.Set(name, value); } } public override void Add(string name, string value) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (name == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(name)), nameof(name)); } if (value == string.Empty) { throw new ArgumentException(SR.Format(SR.net_emptystringcall, nameof(value)), nameof(name)); } MailBnfHelper.ValidateHeaderName(name); // normalize the case of well known headers name = MailHeaderInfo.NormalizeCase(name); MailHeaderID id = MailHeaderInfo.GetID(name); value = value.Normalize(NormalizationForm.FormC); if (id == MailHeaderID.ContentType && _part != null) { _part.ContentType.Set(value.ToLower(CultureInfo.InvariantCulture), this); } else if (id == MailHeaderID.ContentDisposition && _part is MimePart) { ((MimePart)_part).ContentDisposition.Set(value.ToLower(CultureInfo.InvariantCulture), this); } else { InternalAdd(name, value); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Threading.Tasks.Channels.Tests { public class CaseBuilderTests : TestBase { [Fact] public void CaseRead_Sync_InvalidArguments_ThrowsArgumentException() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseRead<int>(null, (Action<int>)null)); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseRead<int>(null, i => { })); Assert.Throws<ArgumentNullException>("action", () => cb.CaseRead<int>(Channel.CreateUnbounded<int>(), (Action<int>)null)); } [Fact] public void CaseRead_Async_InvalidArguments_ThrowsArgumentException() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseRead<int>(null, null)); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseRead<int>(null, i => Task.CompletedTask)); Assert.Throws<ArgumentNullException>("func", () => cb.CaseRead<int>(Channel.CreateUnbounded<int>(), null)); } [Fact] public void CaseWrite_Sync_InvalidArguments_ThrowsArgumentException() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseWrite<int>(null, 0, (Action)null)); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseWrite<int>(null, 0, delegate { })); Assert.Throws<ArgumentNullException>("action", () => cb.CaseWrite<int>(Channel.CreateUnbounded<int>(), 0, (Action)null)); } [Fact] public void CaseWrite_Async_InvalidArguments_ThrowsArgumentException() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseWrite<int>(null, 0, null)); Assert.Throws<ArgumentNullException>("channel", () => cb.CaseWrite<int>(null, 0, delegate { return Task.CompletedTask; })); Assert.Throws<ArgumentNullException>("func", () => cb.CaseWrite<int>(Channel.CreateUnbounded<int>(), 0, null)); } [Fact] public void CaseDefault_Sync_InvalidAction_ThrowsException() { CaseBuilder builder1 = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>(() => builder1.CaseDefault((Action)null)); } [Fact] public void CaseDefault_Async_InvalidAction_ThrowsException() { CaseBuilder builder1 = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => Task.CompletedTask); Assert.Throws<ArgumentNullException>(() => builder1.CaseDefault(null)); } [Fact] public void CaseReadWrite_Sync_CallMultipleTimes_IdempotentResult() { CaseBuilder builder1 = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Same(builder1, builder1.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { })); Assert.Same(builder1, builder1.CaseWrite(Channel.CreateUnbounded<string>(), "", () => { })); Assert.Same(builder1, builder1.CaseDefault(() => { })); CaseBuilder builder2 = Channel.CaseWrite(Channel.CreateUnbounded<int>(), 0, () => { }); Assert.Same(builder2, builder2.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { })); Assert.Same(builder2, builder2.CaseWrite(Channel.CreateUnbounded<string>(), "", () => { })); Assert.Same(builder2, builder2.CaseDefault(() => { })); } [Fact] public void CaseReadWrite_Async_CallMultipleTimes_IdempotentResult() { CaseBuilder builder1 = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => Task.CompletedTask); Assert.Same(builder1, builder1.CaseRead<int>(Channel.CreateUnbounded<int>(), i => Task.CompletedTask)); Assert.Same(builder1, builder1.CaseWrite(Channel.CreateUnbounded<string>(), "", () => Task.CompletedTask)); Assert.Same(builder1, builder1.CaseDefault(() => Task.CompletedTask)); CaseBuilder builder2 = Channel.CaseWrite(Channel.CreateUnbounded<int>(), 0, () => Task.CompletedTask); Assert.Same(builder2, builder2.CaseRead<int>(Channel.CreateUnbounded<int>(), i => Task.CompletedTask)); Assert.Same(builder2, builder2.CaseWrite(Channel.CreateUnbounded<string>(), "", () => Task.CompletedTask)); Assert.Same(builder2, builder2.CaseDefault(() => Task.CompletedTask)); } [Fact] public void CaseDefault_AlreadyExists_ThrowsException() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }).CaseDefault(() => { }); Assert.Throws<InvalidOperationException>(() => cb.CaseDefault(() => { })); Assert.Throws<InvalidOperationException>(() => cb.CaseDefault(() => Task.CompletedTask)); } [Fact] public void SelectAsync_Precanceled_ThrowsCancellationException() { Channel<int> c = Channel.CreateUnbounded<int>(); Assert.True(c.Out.TryWrite(42)); var cts = new CancellationTokenSource(); cts.Cancel(); Task<bool> select = Channel .CaseRead<int>(c, i => { throw new InvalidOperationException(); }) .SelectAsync(cts.Token); AssertSynchronouslyCanceled(select, cts.Token); } [Fact] public async Task SelectAsync_CanceledAfterSelectBeforeData_ThrowsCancellationException() { Channel<int> c = Channel.CreateUnbounded<int>(); var cts = new CancellationTokenSource(); Task<bool> select = Channel .CaseRead<int>(c, i => { throw new InvalidOperationException(); }) .SelectAsync(cts.Token); cts.Cancel(); await AssertCanceled(select, cts.Token); } [Fact] public void SelectAsync_NoChannelsAvailable_SyncDefault_CompletesSynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(() => tcs.SetResult(84)) .SelectAsync(); Assert.Equal(TaskStatus.RanToCompletion, select.Status); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.True(select.Result); Assert.Equal(84, tcs.Task.Result); } [Fact] public void SelectAsync_NoChannelsAvailable_AsyncDefault_CompletesSynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(() => { tcs.SetResult(84); return Task.CompletedTask; }) .SelectAsync(); Assert.Equal(TaskStatus.RanToCompletion, select.Status); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.True(select.Result); Assert.Equal(84, tcs.Task.Result); } [Fact] public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_CompletesAsynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(async () => { await Task.Yield(); tcs.SetResult(84); }) .SelectAsync(); Assert.True(await select); Assert.Equal(84, tcs.Task.Result); } [Fact] public async Task SelectAsync_NoChannelsAvailable_SyncDefault_ThrowsSynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(new Action(() => { throw new FormatException(); })) .SelectAsync(); Assert.True(select.IsCompleted); await Assert.ThrowsAsync<FormatException>(() => select); } [Fact] public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_ThrowsSynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(new Func<Task>(() => { throw new FormatException(); })) .SelectAsync(); Assert.True(select.IsCompleted); await Assert.ThrowsAsync<FormatException>(() => select); } [Fact] public async Task SelectAsync_NoChannelsAvailable_AsyncDefault_ThrowsAsynchronously() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .CaseDefault(async () => { await Task.Yield(); throw new FormatException(); }) .SelectAsync(); await Assert.ThrowsAsync<FormatException>(() => select); } [Fact] public async Task SelectAsync_AllChannelsCompletedBefore_ReturnsFalse() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); c1.Out.Complete(); c2.Out.Complete(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .SelectAsync(); Assert.False(await select); } [Fact] public async Task SelectAsync_AllChannelsCompletedAfter_ReturnsFalse() { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<int> c2 = Channel.CreateUnbuffered<int>(); Task<bool> select = Channel .CaseRead<int>(c1, i => { throw new InvalidOperationException(); }) .CaseWrite(c2, 42, () => { throw new InvalidOperationException(); }) .SelectAsync(); c1.Out.Complete(); c2.Out.Complete(); Assert.False(await select); } [Fact] public async Task SelectAsync_SingleCaseRead_Sync_DataAlreadyAvailable() { Channel<int> c = Channel.CreateUnbounded<int>(); Assert.True(c.Out.TryWrite(42)); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, i => tcs.SetResult(i)).SelectAsync(); Assert.True(select.IsCompleted); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseRead_Async_DataAlreadyAvailable_CompletesSynchronously() { Channel<int> c = Channel.CreateUnbounded<int>(); Assert.True(c.Out.TryWrite(42)); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, i => { tcs.SetResult(i); return Task.CompletedTask; }).SelectAsync(); Assert.True(select.IsCompleted); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseRead_Async_DataAlreadyAvailable_CompletesAsynchronously() { Channel<int> c = Channel.CreateUnbounded<int>(); Assert.True(c.Out.TryWrite(42)); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, async i => { await Task.Yield(); tcs.SetResult(i); }).SelectAsync(); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseRead_Sync_DataNotAlreadyAvailable() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, i => tcs.SetResult(i)).SelectAsync(); Assert.False(select.IsCompleted); Task write = c.Out.WriteAsync(42); Assert.True(await select); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseRead_Async_DataNotAlreadyAvailable_CompletesSynchronously() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, i => { tcs.SetResult(i); return Task.CompletedTask; }).SelectAsync(); Assert.False(select.IsCompleted); Task write = c.Out.WriteAsync(42); Assert.True(await select); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseRead_Async_DataNotAlreadyAvailable_CompletesAsynchronously() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseRead<int>(c, async i => { await Task.Yield(); tcs.SetResult(i); }).SelectAsync(); Assert.False(select.IsCompleted); Task write = c.Out.WriteAsync(42); Assert.True(await select); Assert.Equal(42, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseWrite_Sync_SpaceAlreadyAvailable_CompletesSynchronously() { Channel<int> c = Channel.CreateUnbounded<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, () => tcs.SetResult(1)).SelectAsync(); Assert.True(select.IsCompleted); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(1, await tcs.Task); int result; Assert.True(c.In.TryRead(out result)); Assert.Equal(42, result); } [Fact] public async Task SelectAsync_SingleCaseWrite_Async_SpaceAlreadyAvailable_CompletesSynchronously() { Channel<int> c = Channel.CreateUnbounded<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, () => { tcs.SetResult(1); return Task.CompletedTask; }).SelectAsync(); Assert.True(select.IsCompleted); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(1, await tcs.Task); int result; Assert.True(c.In.TryRead(out result)); Assert.Equal(42, result); } [Fact] public async Task SelectAsync_SingleCaseWrite_Async_SpaceAlreadyAvailable_CompletesAsynchronously() { Channel<int> c = Channel.CreateUnbounded<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, async () => { await Task.Yield(); tcs.SetResult(1); }).SelectAsync(); Assert.True(await select); Assert.Equal(TaskStatus.RanToCompletion, tcs.Task.Status); Assert.Equal(1, await tcs.Task); int result; Assert.True(c.In.TryRead(out result)); Assert.Equal(42, result); } [Fact] public async Task SelectAsync_SingleCaseWrite_Sync_SpaceNotAlreadyAvailable() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, () => tcs.SetResult(1)).SelectAsync(); Assert.False(select.IsCompleted); Task<int> read = c.In.ReadAsync().AsTask(); Assert.True(await select); Assert.Equal(42, await read); Assert.Equal(1, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseWrite_Async_SpaceNotAlreadyAvailable_CompletesSynchronously() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, () => { tcs.SetResult(1); return Task.CompletedTask; }).SelectAsync(); Assert.False(select.IsCompleted); Task<int> read = c.In.ReadAsync().AsTask(); Assert.True(await select); Assert.Equal(42, await read); Assert.Equal(1, await tcs.Task); } [Fact] public async Task SelectAsync_SingleCaseWrite_Async_SpaceNotAlreadyAvailable_CompletesAsynchronously() { Channel<int> c = Channel.CreateUnbuffered<int>(); var tcs = new TaskCompletionSource<int>(); Task<bool> select = Channel.CaseWrite(c, 42, async () => { await Task.Yield(); tcs.SetResult(1); }).SelectAsync(); Assert.False(select.IsCompleted); Task<int> read = c.In.ReadAsync().AsTask(); Assert.True(await select); Assert.Equal(42, await read); Assert.Equal(1, await tcs.Task); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseRead_Sync_ThrowsSynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task write; if (before) write = c.Out.WriteAsync(42); Task t = Channel.CaseRead<int>(c, new Action<int>(i => { throw new FormatException(); })).SelectAsync(); if (!before) write = c.Out.WriteAsync(42); await Assert.ThrowsAsync<FormatException>(() => t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseRead_Async_DataAlreadyAvailable_ThrowsSynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task write; if (before) write = c.Out.WriteAsync(42); Task t = Channel.CaseRead<int>(c, new Func<int, Task>(i => { throw new FormatException(); })).SelectAsync(); if (!before) write = c.Out.WriteAsync(42); await Assert.ThrowsAsync<FormatException>(() => t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseRead_Async_DataAlreadyAvailable_ThrowsAsynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task write; if (before) write = c.Out.WriteAsync(42); Task t = Channel.CaseRead<int>(c, async i => { await Task.Yield(); throw new FormatException(); }).SelectAsync(); if (!before) write = c.Out.WriteAsync(42); await Assert.ThrowsAsync<FormatException>(() => t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseWrite_Sync_ThrowsSynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task read; if (before) read = c.In.ReadAsync().AsTask(); Task t = Channel.CaseWrite(c, 42, new Action(() => { throw new FormatException(); })).SelectAsync(); if (!before) read = c.In.ReadAsync().AsTask(); await Assert.ThrowsAsync<FormatException>(() => t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseWrite_Async_ThrowsSynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task read; if (before) read = c.In.ReadAsync().AsTask(); Task t = Channel.CaseWrite(c, 42, new Func<Task>(() => { throw new FormatException(); })).SelectAsync(); if (!before) read = c.In.ReadAsync().AsTask(); await Assert.ThrowsAsync<FormatException>(() => t); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SelectAsync_CaseWrite_Async_ThrowsAsynchronously(bool before) { Channel<int> c = Channel.CreateUnbuffered<int>(); Task read; if (before) read = c.In.ReadAsync().AsTask(); Task t = Channel.CaseWrite(c, 42, async () => { await Task.Yield(); throw new FormatException(); }).SelectAsync(); if (!before) read = c.In.ReadAsync().AsTask(); await Assert.ThrowsAsync<FormatException>(() => t); } [Fact] public void SelectUntilAsync_InvalidArguments_ThrowsExceptions() { CaseBuilder cb = Channel.CaseRead<int>(Channel.CreateUnbounded<int>(), i => { }); Assert.Throws<ArgumentNullException>(() => { cb.SelectUntilAsync(null); }); } [Theory] [InlineData(false, 100, 150)] [InlineData(true, 100, 150)] [InlineData(false, 100, 100)] [InlineData(true, 100, 100)] [InlineData(false, 100, 99)] [InlineData(true, 100, 99)] [InlineData(false, 100, 1)] [InlineData(true, 100, 1)] [InlineData(false, 100, 0)] [InlineData(true, 100, 0)] public async Task SelectUntilAsync_ProcessUntilAllDataExhausted_Success(bool dataAvailableBefore, int numItems, int maxIterations) { Channel<int> c1 = Channel.CreateUnbounded<int>(); Channel<string> c2 = Channel.CreateUnbounded<string>(); Channel<double> c3 = Channel.CreateUnbounded<double>(); int delegatesInvoked = 0; Task<int> select = null; if (!dataAvailableBefore) { select = Channel .CaseRead<int>(c1, i => { Interlocked.Increment(ref delegatesInvoked); }) .CaseRead<string>(c2, s => { Interlocked.Increment(ref delegatesInvoked); }) .CaseRead<double>(c3, d => { Interlocked.Increment(ref delegatesInvoked); }) .SelectUntilAsync(i => i < maxIterations); } for (int i = 0; i < numItems; i++) { switch (i % 3) { case 0: Assert.True(c1.Out.TryWrite(i)); break; case 1: Assert.True(c2.Out.TryWrite(i.ToString())); break; case 2: Assert.True(c3.Out.TryWrite(i)); break; } } c1.Out.Complete(); c2.Out.Complete(); c3.Out.Complete(); if (dataAvailableBefore) { select = Channel .CaseRead<int>(c1, i => { Interlocked.Increment(ref delegatesInvoked); }) .CaseRead<string>(c2, s => { Interlocked.Increment(ref delegatesInvoked); }) .CaseRead<double>(c3, d => { Interlocked.Increment(ref delegatesInvoked); }) .SelectUntilAsync(i => i < maxIterations); } int expected = Math.Min(numItems, maxIterations); Assert.Equal(expected, await select); Assert.Equal(expected, delegatesInvoked); } } }
using MiaPlaza.ExpressionUtils.Evaluating; using MiaPlaza.ExpressionUtils.Expanding.Attributes; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace MiaPlaza.ExpressionUtils.Expanding { public static class ExpandingExtensions { class ThrowingEvaluator : IExpressionEvaluator { /// <remarks> /// This method is not needed for <see cref="Eval{R}(Expression{Func{R}})"/>. /// </remarks> public object Evaluate(Expression unparametrizedExpression) { throw new NotImplementedException(); } public VariadicArrayParametersDelegate EvaluateLambda(LambdaExpression lambdaExpression) { throw new InvalidOperationException("No evaluator set for handling 'Eval' calls!"); } public DELEGATE EvaluateTypedLambda<DELEGATE>(Expression<DELEGATE> expression) where DELEGATE : class { throw new NotImplementedException(); } } /// <summary> /// Sets the evaluator used to handle <see cref="Eval{R}(Expression{Func{R}})"/>-calls. Use only if /// you plan on using Eval outside of expression expansion as a "shortcut" for Evaluating+Executing. /// </summary> /// <remarks> /// <see cref="Eval{R}(Expression{Func{R}})"/> is primarily meant to be used for expression composition. /// Therefore, it should be used inside other expressions and treated like 'method calls' there (with /// the limitation not to use circular calls). Finally, in order to "inline" all the Eval-calls and /// 'flatten' the expression tree, one should use the <see cref="ExpressionExpanderVisitor"/>. /// </remarks> public static void SetEvaluator(IExpressionEvaluator evaluator) => ExpandingExtensions.evaluator = evaluator; private static IExpressionEvaluator evaluator = new ThrowingEvaluator(); /// <summary> /// Evaluates ('calls') a typed expression without arguments. /// If used in another expression, the subexpression can be inlined /// using the <see cref="SubExpressionExpander"/>. Therefore, cyclic /// Evals must not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R>(this Expression<Func<R>> expression) => (R)evaluator.EvaluateLambda(expression).Invoke(); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1>(this Expression<Func<P1, R>> expression, P1 p1) => (R)evaluator.EvaluateLambda(expression).Invoke(p1); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2>(this Expression<Func<P1, P2, R>> expression, P1 p1, P2 p2) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3>(this Expression<Func<P1, P2, P3, R>> expression, P1 p1, P2 p2, P3 p3) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4>(this Expression<Func<P1, P2, P3, P4, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5>(this Expression<Func<P1, P2, P3, P4, P5, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6>(this Expression<Func<P1, P2, P3, P4, P5, P6, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13, P14 p14) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13, P14 p14, P15 p15) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15); /// <summary> /// Evaluates ('calls') a typed expression with the specified arguments. /// If used in another expression, the subexpression can be inlined using /// the <see cref="SubExpressionExpander"/>. Therefore, cyclic Evals must /// not be used. /// </summary> [ExpanderTypeExpressionExpandableMethod(typeof(SubExpressionExpander))] public static R Eval<R, P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16>(this Expression<Func<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, P13, P14, P15, P16, R>> expression, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5, P6 p6, P7 p7, P8 p8, P9 p9, P10 p10, P11 p11, P12 p12, P13 p13, P14 p14, P15 p15, P16 p16) => (R)evaluator.EvaluateLambda(expression).Invoke(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16); /// <summary> /// Rewrites a call to any of the 'Eval' methods above by inlining the /// expression that would have been evaluated. /// </summary> class SubExpressionExpander : ExpressionExpander<MethodCallExpression> { public override Expression Expand(MethodCallExpression methodCallExpression, IExpressionEvaluator evaluator) { // The first argument of any 'Eval' call is always the expression to be evaluated. // Its retrival must not throw exceptions (unless in an invalid subtree). var lambda = (LambdaExpression)evaluator.Evaluate(methodCallExpression.Arguments[0]); var substituted = ParameterSubstituter.SubstituteParameter( lambda, methodCallExpression.Arguments.Skip(1)); return substituted; } } } }
// 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; public struct VT { public ushort[,] ushort2darr; public ushort[, ,] ushort3darr; public ushort[,] ushort2darr_b; public ushort[, ,] ushort3darr_b; } public class CL { public ushort[,] ushort2darr = { { 0, 1 }, { 0, 0 } }; public ushort[, ,] ushort3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; public ushort[,] ushort2darr_b = { { 0, 49 }, { 0, 0 } }; public ushort[, ,] ushort3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; } public class ushortMDArrTest { static ushort[,] ushort2darr = { { 0, 1 }, { 0, 0 } }; static ushort[, ,] ushort3darr = { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; static ushort[,] ushort2darr_b = { { 0, 49 }, { 0, 0 } }; static ushort[, ,] ushort3darr_b = { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; static ushort[][,] ja1 = new ushort[2][,]; static ushort[][, ,] ja2 = new ushort[2][, ,]; static ushort[][,] ja1_b = new ushort[2][,]; static ushort[][, ,] ja2_b = new ushort[2][, ,]; public static int Main() { bool pass = true; VT vt1; vt1.ushort2darr = new ushort[,] { { 0, 1 }, { 0, 0 } }; vt1.ushort3darr = new ushort[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; vt1.ushort2darr_b = new ushort[,] { { 0, 49 }, { 0, 0 } }; vt1.ushort3darr_b = new ushort[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; CL cl1 = new CL(); ja1[0] = new ushort[,] { { 0, 1 }, { 0, 0 } }; ja2[1] = new ushort[,,] { { { 0, 0 } }, { { 0, 1 } }, { { 0, 0 } } }; ja1_b[0] = new ushort[,] { { 0, 49 }, { 0, 0 } }; ja2_b[1] = new ushort[,,] { { { 0, 0 } }, { { 0, 49 } }, { { 0, 0 } } }; ushort result = 1; // 2D if (result != ushort2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.ushort2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.ushort2darr[0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja1[0][0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (result != ushort3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != vt1.ushort3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != cl1.ushort3darr[1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (result != ja2[1][1, 0, 1]) { Console.WriteLine("ERROR:"); Console.WriteLine("result is: {0}", result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToBool bool Bool_result = true; // 2D if (Bool_result != Convert.ToBoolean(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Bool_result != Convert.ToBoolean(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Bool_result != Convert.ToBoolean(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Bool_result is: {0}", Bool_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToByte tests byte Byte_result = 1; // 2D if (Byte_result != Convert.ToByte(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Byte_result != Convert.ToByte(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Byte_result != Convert.ToByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Byte_result is: {0}", Byte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToChar char Char_result = '1'; // 2D if (Char_result != Convert.ToChar(ushort2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.ushort2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.ushort2darr_b[0, 1] is: {0}", vt1.ushort2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.ushort2darr_b[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.ushort2darr_b[0, 1] is: {0}", cl1.ushort2darr_b[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja1_b[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja1_b[0][0, 1] is: {0}", ja1_b[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Char_result != Convert.ToChar(ushort3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ushort3darr_b[1,0,1] is: {0}", ushort3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(vt1.ushort3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("vt1.ushort3darr_b[1,0,1] is: {0}", vt1.ushort3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(cl1.ushort3darr_b[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("cl1.ushort3darr_b[1,0,1] is: {0}", cl1.ushort3darr_b[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Char_result != Convert.ToChar(ja2_b[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Char_result is: {0}", Char_result); Console.WriteLine("ja2_b[1][1,0,1] is: {0}", ja2_b[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToDecimal decimal Decimal_result = 1; // 2D if (Decimal_result != Convert.ToDecimal(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Decimal_result != Convert.ToDecimal(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Decimal_result != Convert.ToDecimal(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Decimal_result is: {0}", Decimal_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToDouble double Double_result = 1; // 2D if (Double_result != Convert.ToDouble(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Double_result != Convert.ToDouble(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Double_result != Convert.ToDouble(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Double_result is: {0}", Double_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToSingle float Single_result = 1; // 2D if (Single_result != Convert.ToSingle(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Single_result != Convert.ToSingle(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Single_result != Convert.ToSingle(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Single_result is: {0}", Single_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToInt32 int Int32_result = 1; // 2D if (Int32_result != Convert.ToInt32(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int32_result != Convert.ToInt32(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int32_result != Convert.ToInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int32_result is: {0}", Int32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToInt64 long Int64_result = 1; // 2D if (Int64_result != Convert.ToInt64(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int64_result != Convert.ToInt64(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int64_result != Convert.ToInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int64_result is: {0}", Int64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToSByte sbyte SByte_result = 1; // 2D if (SByte_result != Convert.ToSByte(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (SByte_result != Convert.ToSByte(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (SByte_result != Convert.ToSByte(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("SByte_result is: {0}", SByte_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToInt16 short Int16_result = 1; // 2D if (Int16_result != Convert.ToInt16(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (Int16_result != Convert.ToInt16(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (Int16_result != Convert.ToInt16(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("Int16_result is: {0}", Int16_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToUInt32 uint UInt32_result = 1; // 2D if (UInt32_result != Convert.ToUInt32(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt32_result != Convert.ToUInt32(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt32_result != Convert.ToUInt32(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt32_result is: {0}", UInt32_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } //UInt16ToUInt64 tests ulong UInt64_result = 1; // 2D if (UInt64_result != Convert.ToUInt64(ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("2darr[0, 1] is: {0}", ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.ushort2darr[0, 1] is: {0}", vt1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.ushort2darr[0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.ushort2darr[0, 1] is: {0}", cl1.ushort2darr[0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja1[0][0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja1[0][0, 1] is: {0}", ja1[0][0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } // 3D if (UInt64_result != Convert.ToUInt64(ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ushort3darr[1,0,1] is: {0}", ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(vt1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("vt1.ushort3darr[1,0,1] is: {0}", vt1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(cl1.ushort3darr[1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("cl1.ushort3darr[1,0,1] is: {0}", cl1.ushort3darr[1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (UInt64_result != Convert.ToUInt64(ja2[1][1, 0, 1])) { Console.WriteLine("ERROR:"); Console.WriteLine("UInt64_result is: {0}", UInt64_result); Console.WriteLine("ja2[1][1,0,1] is: {0}", ja2[1][1, 0, 1]); Console.WriteLine("and they are NOT equal !"); Console.WriteLine(); pass = false; } if (!pass) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); return 100; } } };
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.Linq.Expressions; using StructureMap.Configuration.DSL.Expressions; using StructureMap.Graph; using StructureMap.Interceptors; namespace StructureMap.Pipeline { /// <summary> /// Instance that builds objects with by calling constructor functions and using setter properties /// </summary> /// <typeparam name="T">The concrete type constructed by SmartInstance</typeparam> public class SmartInstance<T> : ConstructorInstance { private readonly List<Action<T>> _actions = new List<Action<T>>(); public SmartInstance() : base(typeof (T)) { } /// <summary> /// Sets the name of this Instance /// </summary> /// <param name="instanceKey"></param> /// <returns></returns> [Obsolete("Please change to Named(instanceKey)")] public SmartInstance<T> WithName(string instanceKey) { Name = instanceKey; return this; } /// <summary> /// Sets the name of this Instance /// </summary> /// <param name="instanceKey"></param> /// <returns></returns> public SmartInstance<T> Named(string instanceKey) { Name = instanceKey; return this; } /// <summary> /// Register an Action to perform on the object created by this Instance /// before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> OnCreation(Action<T> handler) { var interceptor = new StartupInterceptor<T>((c, o) => handler(o)); Interceptor = interceptor; return this; } /// <summary> /// Register an Action to perform on the object created by this Instance /// before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> OnCreation(Action<IContext, T> handler) { var interceptor = new StartupInterceptor<T>(handler); Interceptor = interceptor; return this; } /// <summary> /// Register a Func to potentially enrich or substitute for the object /// created by this Instance before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> EnrichWith(EnrichmentHandler<T> handler) { var interceptor = new EnrichmentInterceptor<T>((c, o) => handler(o)); Interceptor = interceptor; return this; } /// <summary> /// Register a Func to potentially enrich or substitute for the object /// created by this Instance before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> EnrichWith<PLUGINTYPE>(EnrichmentHandler<PLUGINTYPE> handler) { var interceptor = new EnrichmentInterceptor<PLUGINTYPE>((c, o) => handler(o)); Interceptor = interceptor; return this; } /// <summary> /// Register a Func to potentially enrich or substitute for the object /// created by this Instance before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> EnrichWith(ContextEnrichmentHandler<T> handler) { var interceptor = new EnrichmentInterceptor<T>(handler); Interceptor = interceptor; return this; } /// <summary> /// Register a Func to potentially enrich or substitute for the object /// created by this Instance before it is returned to the caller /// </summary> /// <param name="handler"></param> /// <returns></returns> public SmartInstance<T> EnrichWith<PLUGINTYPE>(ContextEnrichmentHandler<PLUGINTYPE> handler) { var interceptor = new EnrichmentInterceptor<PLUGINTYPE>(handler); Interceptor = interceptor; return this; } /// <summary> /// Register an <see cref="InstanceInterceptor">InstanceInterceptor</see> with this Instance /// </summary> /// <param name="interceptor"></param> /// <returns></returns> public SmartInstance<T> InterceptWith(InstanceInterceptor interceptor) { Interceptor = interceptor; return this; } /// <summary> /// Define a primitive constructor argument /// </summary> /// <param name="argumentName"></param> /// <returns></returns> [Obsolete("Use Ctor() instead")] public PropertyExpression<SmartInstance<T>> WithCtorArg(string argumentName) { return new PropertyExpression<SmartInstance<T>>(this, argumentName); } protected override object build(Type pluginType, BuildSession session) { var builtTarget = (T) base.build(pluginType, session); foreach (var action in _actions) { action(builtTarget); } return builtTarget; } /// <summary> /// Set simple setter properties /// </summary> /// <param name="action"></param> /// <returns></returns> public SmartInstance<T> SetProperty(Action<T> action) { _actions.Add(action); return this; } /// <summary> /// Define a primitive setter property by specifying the property name with /// an expression /// </summary> /// <param name="expression"></param> /// <returns></returns> public PropertyExpression<SmartInstance<T>> WithProperty(Expression<Func<T, object>> expression) { string propertyName = ReflectionHelper.GetProperty(expression).Name; return WithProperty(propertyName); } /// <summary> /// Define a primitive setter property by specifying the property name /// </summary> /// <param name="propertyName"></param> /// <returns></returns> public PropertyExpression<SmartInstance<T>> WithProperty(string propertyName) { return new PropertyExpression<SmartInstance<T>>(this, propertyName); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type. Do not /// use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="CTORTYPE"></typeparam> /// <returns></returns> [Obsolete("Change to Ctor<>()")] public DependencyExpression<CTORTYPE> CtorDependency<CTORTYPE>() { string constructorArg = getArgumentNameForType<CTORTYPE>(); return CtorDependency<CTORTYPE>(constructorArg); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type. Do not /// use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="CTORTYPE"></typeparam> /// <returns></returns> public DependencyExpression<CTORTYPE> Ctor<CTORTYPE>() { string constructorArg = getArgumentNameForType<CTORTYPE>(); return CtorDependency<CTORTYPE>(constructorArg); } private string getArgumentNameForType<CTORTYPE>() { Plugin plugin = PluginCache.GetPlugin(getConcreteType(null)); return plugin.FindArgumentNameForType<CTORTYPE>(); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. /// Use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="CTORTYPE"></typeparam> /// <param name="constructorArg"></param> /// <returns></returns> [Obsolete("Use Ctor<CTORTYPE>(constructorArg)")] public DependencyExpression<CTORTYPE> CtorDependency<CTORTYPE>(string constructorArg) { return new DependencyExpression<CTORTYPE>(this, constructorArg); } /// <summary> /// Inline definition of a constructor dependency. Select the constructor argument by type and constructor name. /// Use this method if there is more than one constructor arguments of the same type /// </summary> /// <typeparam name="CTORTYPE"></typeparam> /// <param name="constructorArg"></param> /// <returns></returns> public DependencyExpression<CTORTYPE> Ctor<CTORTYPE>(string constructorArg) { return new DependencyExpression<CTORTYPE>(this, constructorArg); } /// <summary> /// Inline definition of a setter dependency. The property name is specified with an Expression /// </summary> /// <typeparam name="SETTERTYPE"></typeparam> /// <param name="expression"></param> /// <returns></returns> [Obsolete("Use Setter()")] public DependencyExpression<SETTERTYPE> SetterDependency<SETTERTYPE>( Expression<Func<T, SETTERTYPE>> expression) { string propertyName = ReflectionHelper.GetProperty(expression).Name; return new DependencyExpression<SETTERTYPE>(this, propertyName); } /// <summary> /// Inline definition of a setter dependency. The property name is specified with an Expression /// </summary> /// <typeparam name="SETTERTYPE"></typeparam> /// <param name="expression"></param> /// <returns></returns> public DependencyExpression<SETTERTYPE> Setter<SETTERTYPE>( Expression<Func<T, SETTERTYPE>> expression) { string propertyName = ReflectionHelper.GetProperty(expression).Name; return new DependencyExpression<SETTERTYPE>(this, propertyName); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the SETTERTYPE /// </summary> /// <typeparam name="SETTERTYPE"></typeparam> /// <returns></returns> [Obsolete("Use Setter<>()")] public DependencyExpression<SETTERTYPE> SetterDependency<SETTERTYPE>() { return CtorDependency<SETTERTYPE>(); } /// <summary> /// Inline definition of a setter dependency. Only use this method if there /// is only a single property of the SETTERTYPE /// </summary> /// <typeparam name="SETTERTYPE"></typeparam> /// <returns></returns> public DependencyExpression<SETTERTYPE> Setter<SETTERTYPE>() { return CtorDependency<SETTERTYPE>(); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="CHILD"></typeparam> /// <returns></returns> [Obsolete("Use EnumerableOf<>")] public ArrayDefinitionExpression<CHILD> TheArrayOf<CHILD>() { if (typeof (CHILD).IsArray) { throw new ApplicationException("Please specify the element type in the call to TheArrayOf"); } Plugin plugin = PluginCache.GetPlugin(typeof (T)); string propertyName = plugin.FindArgumentNameForEnumerableOf(typeof (CHILD)); return TheArrayOf<CHILD>(propertyName); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="CHILD"></typeparam> /// <param name="ctorOrPropertyName"></param> /// <returns></returns> [Obsolete("Use EnumerableOf<>")] public ArrayDefinitionExpression<CHILD> TheArrayOf<CHILD>(string ctorOrPropertyName) { if (ctorOrPropertyName.IsEmpty()) { throw new StructureMapException(302, typeof(CHILD).FullName, typeof(T).FullName); } return new ArrayDefinitionExpression<CHILD>(this, ctorOrPropertyName); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="CHILD"></typeparam> /// <returns></returns> public ArrayDefinitionExpression<CHILD> EnumerableOf<CHILD>() { if (typeof(CHILD).IsArray) { throw new ApplicationException("Please specify the element type in the call to TheArrayOf"); } Plugin plugin = PluginCache.GetPlugin(typeof(T)); string propertyName = plugin.FindArgumentNameForEnumerableOf(typeof(CHILD)); return TheArrayOf<CHILD>(propertyName); } /// <summary> /// Inline definition of a dependency on an Array of the CHILD type and the specified setter property or constructor argument name. I.e. CHILD[]. /// This method can be used for either constructor arguments or setter properties /// </summary> /// <typeparam name="CHILD"></typeparam> /// <param name="ctorOrPropertyName"></param> /// <returns></returns> public ArrayDefinitionExpression<CHILD> EnumerableOf<CHILD>(string ctorOrPropertyName) { if (ctorOrPropertyName.IsEmpty()) { throw new StructureMapException(302, typeof(CHILD).FullName, typeof(T).FullName); } return new ArrayDefinitionExpression<CHILD>(this, ctorOrPropertyName); } #region Nested type: ArrayDefinitionExpression /// <summary> /// Expression Builder to help define multiple Instances for an Array dependency /// </summary> /// <typeparam name="ARRAY"></typeparam> public class ArrayDefinitionExpression<ARRAY> { private readonly SmartInstance<T> _instance; private readonly string _propertyName; internal ArrayDefinitionExpression(SmartInstance<T> instance, string propertyName) { _instance = instance; _propertyName = propertyName; } /// <summary> /// Nested Closure that allows you to add an unlimited number of child Instances /// </summary> /// <param name="action"></param> /// <returns></returns> public SmartInstance<T> Contains(Action<IInstanceExpression<ARRAY>> action) { var list = new List<Instance>(); var child = new InstanceExpression<ARRAY>(list.Add); action(child); _instance.SetCollection(_propertyName, list); return _instance; } /// <summary> /// Specify an array of Instance objects directly for an Array dependency /// </summary> /// <param name="children"></param> /// <returns></returns> public SmartInstance<T> Contains(params Instance[] children) { _instance.SetCollection(_propertyName, children); return _instance; } } #endregion #region Nested type: DependencyExpression /// <summary> /// Expression Builder that helps to define child dependencies inline /// </summary> /// <typeparam name="CHILD"></typeparam> public class DependencyExpression<CHILD> { private readonly SmartInstance<T> _instance; private readonly string _propertyName; internal DependencyExpression(SmartInstance<T> instance, string propertyName) { _instance = instance; _propertyName = propertyName; } /// <summary> /// Sets the value of the constructor argument to the key/value in the /// AppSettings /// </summary> /// <param name="appSettingKey">The key in appSettings for the value to use.</param> /// <returns></returns> public SmartInstance<T> EqualToAppSetting(string appSettingKey) { return EqualToAppSetting(appSettingKey, null); } /// <summary> /// Sets the value of the constructor argument to the key/value in the /// AppSettings when it exists. Otherwise uses the provided default value. /// </summary> /// <param name="appSettingKey">The key in appSettings for the value to use.</param> /// <param name="defaultValue">The value to use if an entry for <paramref name="appSettingKey"/> does not exist in the appSettings section.</param> /// <returns></returns> public SmartInstance<T> EqualToAppSetting(string appSettingKey, string defaultValue) { string propertyValue = ConfigurationManager.AppSettings[appSettingKey]; if (propertyValue == null) propertyValue = defaultValue; _instance.SetValue(_propertyName, propertyValue); return _instance; } /// <summary> /// Nested Closure to define a child dependency inline /// </summary> /// <param name="action"></param> /// <returns></returns> public SmartInstance<T> Is(Action<IInstanceExpression<CHILD>> action) { var expression = new InstanceExpression<CHILD>(i => _instance.SetChild(_propertyName, i)); action(expression); return _instance; } public SmartInstance<T> Is(Func<IContext, CHILD> func) { var child = new LambdaInstance<CHILD>(func); return Is(child); } /// <summary> /// Shortcut to set an inline dependency to an Instance /// </summary> /// <param name="instance"></param> /// <returns></returns> public SmartInstance<T> Is(Instance instance) { _instance.SetChild(_propertyName, instance); return _instance; } /// <summary> /// Shortcut to set an inline dependency to a designated object /// </summary> /// <param name="value"></param> /// <returns></returns> public SmartInstance<T> Is(CHILD value) { _instance.SetValue(_propertyName, value); return _instance; } /// <summary> /// Shortcut to set an inline dependency to a designated object /// </summary> /// <param name="value"></param> /// <returns></returns> [Obsolete("Change to Is()")] public SmartInstance<T> EqualTo(CHILD value) { _instance.SetValue(_propertyName, value); return _instance; } /// <summary> /// Set an Inline dependency to the Default Instance of the Property type /// Used mostly to force an optional Setter property to be filled by /// StructureMap /// </summary> /// <returns></returns> public SmartInstance<T> IsTheDefault() { return Is(new DefaultInstance()); } /// <summary> /// Shortcut method to define a child dependency inline /// </summary> /// <typeparam name="CONCRETETYPE"></typeparam> /// <returns></returns> public SmartInstance<T> Is<CONCRETETYPE>() where CONCRETETYPE : CHILD { return Is(new SmartInstance<CONCRETETYPE>()); } /// <summary> /// Shortcut method to define a child dependency inline and configure /// the child dependency /// </summary> /// <typeparam name="CONCRETETYPE"></typeparam> /// <returns></returns> public SmartInstance<T> Is<CONCRETETYPE>(Action<SmartInstance<CONCRETETYPE>> configure) where CONCRETETYPE : CHILD { var instance = new SmartInstance<CONCRETETYPE>(); configure(instance); return Is(instance); } public SmartInstance<T> Named(string name) { return Is(c => c.GetInstance<CHILD>(name)); } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="FlowSplitAfterSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using FluentAssertions; using Reactive.Streams; using Xunit; using Xunit.Abstractions; // ReSharper disable InvokeAsExtensionMethod // ReSharper disable UnusedMember.Local namespace Akka.Streams.Tests.Dsl { public class FlowSplitAfterSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowSplitAfterSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys) .WithInputBuffer(2, 2) .WithSubscriptionTimeoutSettings( new StreamSubscriptionTimeoutSettings( StreamSubscriptionTimeoutTerminationMode.CancelTermination, TimeSpan.FromSeconds(1))); Materializer = ActorMaterializer.Create(Sys, settings); } private sealed class StreamPuppet { private readonly TestSubscriber.ManualProbe<int> _probe; private readonly ISubscription _subscription; public StreamPuppet(IPublisher<int> p, TestKitBase kit) { _probe = TestSubscriber.CreateManualProbe<int>(kit); p.Subscribe(_probe); _subscription = _probe.ExpectSubscription(); } public void Request(int demand) => _subscription.Request(demand); public void ExpectNext(int element) => _probe.ExpectNext(element); public void ExpectNoMsg(TimeSpan max) => _probe.ExpectNoMsg(max); public void ExpectComplete() => _probe.ExpectComplete(); public void ExpectError(Exception ex) => _probe.ExpectError().Should().Be(ex); public void Cancel() => _subscription.Cancel(); } private void WithSubstreamsSupport(int splitAfter = 3, int elementCount = 6, SubstreamCancelStrategy substreamCancelStrategy = SubstreamCancelStrategy.Drain, Action<TestSubscriber.ManualProbe<Source<int, NotUsed>>, ISubscription, Func<Source<int, NotUsed>>> run = null) { var source = Source.From(Enumerable.Range(1, elementCount)); var groupStream = source.SplitAfter(substreamCancelStrategy, i => i == splitAfter) .Lift() .RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer); var masterSubscriber = TestSubscriber.CreateManualProbe<Source<int, NotUsed>>(this); groupStream.Subscribe(masterSubscriber); var masterSubscription = masterSubscriber.ExpectSubscription(); run?.Invoke(masterSubscriber, masterSubscription, () => { masterSubscription.Request(1); return masterSubscriber.ExpectNext(); }); } [Fact] public void SplitAfter_must_work_in_the_happy_case() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(3,5,run: (masterSubscriber, masterSubscription, expectSubFlow) => { var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s1.Request(2); s1.ExpectNext(1); s1.ExpectNext(2); s1.Request(1); s1.ExpectNext(3); s1.Request(1); s1.ExpectComplete(); var s2 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); s2.Request(2); s2.ExpectNext(4); s2.ExpectNext(5); s2.ExpectComplete(); masterSubscription.Request(1); masterSubscriber.ExpectComplete(); }); }, Materializer); } [Fact] public void SplitAfter_must_work_when_first_element_is_split_by() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(1, 3, run: (masterSubscriber, masterSubscription, expectSubFlow) => { var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); masterSubscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(100)); s1.Request(3); s1.ExpectNext(1); s1.ExpectComplete(); var s2 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); s2.Request(3); s2.ExpectNext(2); s2.ExpectNext(3); s2.ExpectComplete(); masterSubscription.Request(1); masterSubscriber.ExpectComplete(); }); }, Materializer); } [Fact] public void SplitAfter_must_work_with_single_element_splits_by() { this.AssertAllStagesStopped(() => { var task = Source.From(Enumerable.Range(1, 10)) .SplitAfter(_ => true) .Lift() .SelectAsync(1, s => s.RunWith(Sink.First<int>(), Materializer)) .Grouped(10) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); task.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10)); }, Materializer); } [Fact] public void SplitAfter_must_support_cancelling_substreams() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(5, 8, run: (masterSubscriber, masterSubscription, expectSubFlow) => { var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); masterSubscription.Cancel(); s1.Request(5); s1.ExpectNext(1); s1.ExpectNext(2); s1.ExpectNext(3); s1.ExpectNext(4); s1.ExpectNext(5); s1.Request(1); s1.ExpectComplete(); }); }, Materializer); } [Fact] public void SplitAfter_must_fail_stream_when_SplitAfter_function_throws() { this.AssertAllStagesStopped(() => { var publisherProbe = TestPublisher.CreateManualProbe<int>(this); var ex = new TestException("test"); var publisher = Source.FromPublisher(publisherProbe).SplitAfter(i => { if (i == 3) throw ex; return i%3 == 0; }).Lift().RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer); var subscriber = TestSubscriber.CreateManualProbe<Source<int, NotUsed>>(this); publisher.Subscribe(subscriber); var upstreamSubscription = publisherProbe.ExpectSubscription(); var downstreamSubscription = subscriber.ExpectSubscription(); downstreamSubscription.Request(100); upstreamSubscription.SendNext(1); var substream = subscriber.ExpectNext(); var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this); substreamPuppet.Request(10); substreamPuppet.ExpectNext(1); upstreamSubscription.SendNext(2); substreamPuppet.ExpectNext(2); upstreamSubscription.SendNext(3); subscriber.ExpectError().Should().Be(ex); substreamPuppet.ExpectError(ex); upstreamSubscription.ExpectCancellation(); }, Materializer); } [Fact(Skip = "Supervision is not supported fully by GraphStages yet")] public void SplitAfter_must_resume_stream_when_SplitAfter_function_throws() { this.AssertAllStagesStopped(() => { }, Materializer); } [Fact] public void SplitAfter_must_pass_along_early_cancellation() { this.AssertAllStagesStopped(() => { var up = TestPublisher.CreateManualProbe<int>(this); var down = TestSubscriber.CreateManualProbe<Source<int, NotUsed>>(this); var flowSubscriber = Source.AsSubscriber<int>() .SplitAfter(i => i%3 == 0) .Lift() .To(Sink.FromSubscriber(down)) .Run(Materializer); var downstream = down.ExpectSubscription(); downstream.Cancel(); up.Subscribe(flowSubscriber); var upSub = up.ExpectSubscription(); upSub.ExpectCancellation(); }, Materializer); } [Fact] public void SplitAfter_must_support_eager_cancellation_of_master_stream_on_cancelling_substreams() { this.AssertAllStagesStopped(() => { WithSubstreamsSupport(5,8,SubstreamCancelStrategy.Propagate, (masterSubscriber, masterSubscription, expectSubFlow) => { var s1 = new StreamPuppet(expectSubFlow().RunWith(Sink.AsPublisher<int>(false), Materializer), this); s1.Cancel(); masterSubscriber.ExpectComplete(); }); }, Materializer); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Apache.Geode.Client.Tests { using Apache.Geode.DUnitFramework; using Apache.Geode.Client; //using Region = Apache.Geode.Client.IRegion<TKey, TVal>; /// <summary> /// Helper class to populate regions and verify query results. /// This class is intentionally not thread-safe. /// </summary> public class QueryHelper<TKey,TVal> { #region Private members private int m_portfolioSetSize; private int m_portfolioNumSets; private int m_positionSetSize; private int m_positionNumSets; private Cache m_cache; private static QueryHelper<TKey, TVal> m_instance = null; #endregion #region Public accessors public virtual int PortfolioSetSize { get { return m_portfolioSetSize; } } public virtual int PortfolioNumSets { get { return m_portfolioNumSets; } } public virtual int PositionSetSize { get { return m_positionSetSize; } } public virtual int PositionNumSets { get { return m_positionNumSets; } } #endregion private QueryHelper(Cache cache) { m_portfolioSetSize = 20; m_portfolioNumSets = 1; m_positionSetSize = 20; m_positionNumSets = 1; m_cache = cache; } public static QueryHelper<TKey, TVal> GetHelper(Cache cache) { if (m_instance == null) { m_instance = new QueryHelper<TKey,TVal>(cache); } return m_instance; } public virtual void PopulatePortfolioData(IRegion<TKey, TVal> region, int setSize, int numSets) { PopulatePortfolioData(region, setSize, numSets, 1); } public virtual void PopulatePortfolioData(IRegion<TKey, TVal> region, int setSize, int numSets, int objSize) { PopulatePortfolioData(region, setSize, numSets, objSize, null); } public virtual void PopulatePortfolioPdxData(IRegion<TKey, TVal> region, int setSize, int numSets) { PopulatePortfolioPdxData(region, setSize, numSets, 1); } public virtual void PopulatePortfolioPdxData(IRegion<TKey, TVal> region, int setSize, int numSets, int objSize) { PopulatePortfolioPdxData(region, setSize, numSets, objSize, null); } public virtual void PopulatePortfolioData(IRegion<TKey, TVal> region, int setSize, int numSets, int objSize, string[] names) { Util.Log("QueryHelper.PopulatePortfolioData: putting for setSize={0}, numSets={1}, objSize={2}",setSize, numSets, objSize); if(names == null) { Util.Log("QueryHelper.PopulatePortfolioData: names is null"); } else { for(int i =0 ; i < names.Length; i++) { Util.Log("QueryHelper.PopulatePortfolioData: names[{0}]={1}", i, names[i]); } } Position.Count = 0; for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { Portfolio portfolio = new Portfolio(current, objSize, names); TKey portfolioName = (TKey)(object)string.Format("port{0}-{1}", set, current); //Util.Log("QueryHelper.PopulatePortfolioData: creating key = {0} and" //+ " puting data.", portfolioName); //Put operation region[portfolioName] = (TVal)(object)portfolio; } } //m_portfolioSetSize = setSize; //m_portfolioNumSets = numSets; //m_objectSize = objSize; Util.Log("QueryHelper.PopulatePortfolioData: all puts done."); } public virtual void PopulatePortfolioPdxData(IRegion<TKey, TVal> region, int setSize, int numSets, int objSize, string[] names) { Util.Log("QueryHelper.PopulatePortfolioPdxData: putting for setSize={0}, numSets={1}, objSize={2}", setSize, numSets, objSize); if (names == null) { Util.Log("QueryHelper.PopulatePortfolioPdxData: names is null"); } else { for (int i = 0; i < names.Length; i++) { Util.Log("QueryHelper.PopulatePortfolioPdxData: names[{0}]={1}", i, names[i]); } } PositionPdx.Count = 0; for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { PortfolioPdx portfolio = new PortfolioPdx(current, objSize, names); TKey portfolioName = (TKey)(object)string.Format("port{0}-{1}", set, current); //Util.Log("QueryHelper.PopulatePortfolioData: creating key = {0} and" //+ " puting data.", portfolioName); //Put operation region[portfolioName] = (TVal)(object)portfolio; } } //m_portfolioSetSize = setSize; //m_portfolioNumSets = numSets; //m_objectSize = objSize; Util.Log("QueryHelper.PopulatePortfolioPdxData: all puts done."); } public virtual void PopulatePositionData(IRegion<TKey, TVal> region, int setSize, int numSets) { Util.Log("QueryHelper.PopulatePositionData: putting for setSize={0}, numSets={1}", setSize, numSets); string[] secIds = Portfolio.SecIds; int numSecIds = secIds.Length; for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { Position pos = new Position(secIds[current % numSecIds], current * 100); TKey posName = (TKey)(object)string.Format("pos{0}-{1}", set, current); //Put Operation region[posName] = (TVal)(object)pos; } } //m_positionSetSize = setSize; //m_positionNumSets = numSets; Util.Log("QueryHelper.PopulatePositionData: all puts done."); } public virtual void PopulatePositionPdxData(IRegion<TKey, TVal> region, int setSize, int numSets) { Util.Log("QueryHelper.PopulatePositionPdxData: putting for setSize={0}, numSets={1}", setSize, numSets); string[] secIds = PortfolioPdx.SecIds; int numSecIds = secIds.Length; for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { PositionPdx pos = new PositionPdx(secIds[current % numSecIds], current * 100); TKey posName = (TKey)(object)string.Format("pos{0}-{1}", set, current); //Util.Log("QueryHelper.PopulatePositionPdxData: creating key = {0} and" //+ " puting data.", posName); //Put Operation region[posName] = (TVal)(object)pos; } } //m_positionSetSize = setSize; //m_positionNumSets = numSets; Util.Log("QueryHelper.PopulatePositionPdxData: all puts done."); } public virtual void DestroyPortfolioOrPositionData(IRegion<TKey, TVal> region, int setSize, int numSets, string objectType) { string prefix = string.Empty; if (objectType.Equals("Portfolio") || objectType.Equals("PortfolioPdx")) { prefix = "port"; } else // if (objectType.Equals("Position")) { prefix = "pos"; } for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { string keyname = string.Empty; keyname = prefix + set + "-" + current; // "port1-1" or "pos1-1" for example TKey key = (TKey)(object)keyname; region.Remove(key); } } } public virtual void InvalidatePortfolioOrPositionData(IRegion<TKey, TVal> region, int setSize, int numSets, string objectType) { string prefix = string.Empty; if (objectType.Equals("Portfolio") || objectType.Equals("PortfolioPdx")) { prefix = "port"; } else // if (objectType.Equals("Position")) { prefix = "pos"; } for (int set = 1; set <= numSets; set++) { for (int current = 1; current <= setSize; current++) { string keyname = string.Empty; keyname = prefix + set + "-" + current; // "port1-1" or "pos1-1" for example TKey key = (TKey)(object)keyname; region.Invalidate(key); } } } public virtual bool VerifyRS(ISelectResults<object> resultset, int expectedRows) { if (resultset == null) return false; int foundRows = 0; SelectResultsIterator<object> sr = resultset.GetIterator(); while (sr.HasNext) { //TVal ser = (TVal)sr.Next(); Object ser = sr.Next(); if (ser == null) { Util.Log("QueryHelper.VerifyRS: Object is null."); return false; } foundRows++; } Util.Log("QueryHelper.VerifyRS: found rows {0}, expected {1}", foundRows, expectedRows); return (foundRows == expectedRows); } public virtual bool VerifySS(ISelectResults<object> structset, int expectedRows, int expectedFields) { if (structset == null) { if (expectedRows == 0 && expectedFields == 0) return true; //quite possible we got a null set back. return false; } int foundRows = 0; foreach (Struct si in structset) { foundRows++; if (si == null) { Util.Log("QueryHelper.VerifySS: Struct is null."); return false; } int foundFields = 0; for (uint cols = 0; cols < si.Length; cols++) { //IGeodeSerializable field = si[cols]; object field = (object)si[cols]; foundFields++; } if (foundFields != expectedFields) { Util.Log("QueryHelper.VerifySS: found fields {0}, expected" + " fields {1}.", foundFields, expectedFields); return false; } } if (foundRows != expectedRows) { Util.Log("QueryHelper.VerifySS: rows fields {0}, expected rows {1}.", foundRows, expectedRows); return false; } return true; } public bool IsExpectedRowsConstantRS(int queryindex) { foreach (int constantIndex in QueryStatics.ConstantExpectedRowsRS) { if (queryindex == constantIndex) { Util.Log("Index {0} is having constant rows.", constantIndex); return true; } } return false; } public bool IsExpectedRowsConstantPQRS(int queryindex) { foreach (int constantIndex in QueryStatics.ConstantExpectedRowsPQRS) { if (queryindex == constantIndex) { Util.Log("Index {0} is having constant rows.", constantIndex); return true; } } return false; } public bool IsExpectedRowsConstantSS(int queryindex) { foreach (int constantIndex in QueryStatics.ConstantExpectedRowsSS) { if (queryindex == constantIndex) { Util.Log("Index {0} is having constant rows.", constantIndex); return true; } } return false; } public bool IsExpectedRowsConstantPQSS(int queryindex) { foreach (int constantIndex in QueryStatics.ConstantExpectedRowsPQSS) { if (queryindex == constantIndex) { Util.Log("Index {0} is having constant rows.", constantIndex); return true; } } return false; } public bool IsExpectedRowsConstantCQRS(int queryindex) { foreach (int constantIndex in QueryStatics.ConstantExpectedRowsCQRS) if (queryindex == constantIndex) { Util.Log("Index {0} is having constant rows.", constantIndex); return true; } return false; } public void PopulateRangePositionData(IRegion<TKey, TVal> region, int start, int end) { for (int i = start; i <= end; i++) { TVal pos = (TVal)(object)new Position(i); TKey key = (TKey)(object)string.Format("pos{0}", i); region[key] = pos; } } public void PopulateRangePositionPdxData(IRegion<TKey, TVal> region, int start, int end) { for (int i = start; i <= end; i++) { TVal pos = (TVal)(object)new PositionPdx(i); TKey key = (TKey)(object)string.Format("pos{0}", i); region[key] = pos; } } public bool CompareTwoPositionObjects(TVal pos1, TVal pos2) { Position p1 = pos1 as Position; Position p2 = pos2 as Position; if (p1 == null || p2 == null) { Util.Log("The object(s) passed are not of Position type"); return false; } DataOutput o1 = m_cache.CreateDataOutput(); DataOutput o2 = m_cache.CreateDataOutput(); p1.ToData(o1); p2.ToData(o2); uint len1 = o1.BufferLength; uint len2 = o2.BufferLength; if (len1 != len2) { return false; } byte[] ptr1 = o1.GetBuffer(); byte[] ptr2 = o2.GetBuffer(); if (ptr1.Length != ptr2.Length) { return false; } for (int i = ptr1.Length; i < ptr1.Length; i++) { if (ptr1[i] != ptr2[i]) { return false; } } return true; } public TVal GetExactPositionObject(int iForExactPosObject) { return (TVal)(object)new Position(iForExactPosObject); } public TVal GetExactPositionPdxObject(int iForExactPosObject) { return (TVal)(object)new PositionPdx(iForExactPosObject); } public TVal GetCachedPositionObject(IRegion<TKey, TVal> region, int iForExactPosObject) { TKey key = (TKey)(object)string.Format("pos{0}", iForExactPosObject); return region[key]; } public void PutExactPositionObject(IRegion<TKey, TVal> region, int iForExactPosObject) { TKey key = (TKey)(object)string.Format("pos{0}", iForExactPosObject); region[key] = (TVal)(object)new Position(iForExactPosObject); } public void PutExactPositionPdxObject(IRegion<TKey, TVal> region, int iForExactPosObject) { TKey key = (TKey)(object)string.Format("pos{0}", iForExactPosObject); region[key] = (TVal)(object)new PositionPdx(iForExactPosObject); } } }
//----------------------------------------------------------------------------- // Logicking's Game Factory // Copyright (C) Logicking.com, Inc. //----------------------------------------------------------------------------- // Sample rag dolls for bullet //----------------------------------------------------------------------------- //shape $ShapeType::Box,$ShapeType::Sphere, $ShapeType::Capsule - 2 //joint $JointType::ConeTwist, $JointType::Hinge, $JointType::Dof6", $JointType::BallSocket" datablock RagDollData(SpaceOrcRagDoll) { category = "RigidBody"; shapeFile = "art/shapes/actors/SpaceOrc/SpaceOrc.dts"; minContactSpeed = 5.0; slidingThreshold = 0.5; collisionSoundsCount = 1; collisionSound[0] = bodyFall0; //pelvis boneNodeName[0] = "Bip01 Pelvis"; boneSize[0] = "0.4 0.1 0.0"; boneMass[0] = 1;//25; boneShape[0] = $ShapeType::Capsule; boneOffset[0] = "0 0 0"; //torso boneParentNodeName[1] = "Bip01 Pelvis"; boneNodeName[1] = "Bip01 Spine2"; boneSize[1] = "0.2 0.2 0.0"; boneMass[1] = 1;//25; boneShape[1] = $ShapeType::Capsule; boneJointType[1] = $JointType::Hinge; boneOffset[1] = "0 0 0"; boneJointParam[1] = "0 1.57 0";//-0.785//"1.57 3.14 0" //head boneParentNodeName[2] = "Bip01 Spine2"; boneNodeName[2] = "Bip01 Head"; boneSize[2] = "0.2 0.1 0.0"; boneMass[2] = 1;//5; boneShape[2] = $ShapeType::Capsule; boneOffset[2] = "0 0 0"; boneJointType[2] = $JointType::ConeTwist;//1;// boneJointParam[2] = "0.785 0.785 0";//"0 0 0";//"0.785 0.785 1.57";// //left arm //upperarm boneParentNodeName[3] = "Bip01 Spine2"; boneNodeName[3] = "Bip01 L UpperArm"; boneSize[3] = "0.2 0.3 0.0"; boneMass[3] = 1;//5; boneShape[3] = $ShapeType::Capsule; boneOffset[3] = "0 0 0"; boneJointType[3] = $JointType::ConeTwist;//1;//3;// boneJointParam[3] = "0.785 0.785 0"; //forearm boneParentNodeName[4] = "Bip01 L UpperArm"; boneNodeName[4] = "Bip01 L Forearm"; boneSize[4] = "0.2 0.4 0.0"; boneMass[4] = 1;//5; boneShape[4] = $ShapeType::Capsule; boneOffset[4] = "0 0 0"; boneJointType[4] = $JointType::Hinge; boneJointParam[4] = "-1.57 0 0";//"0 1.57 0"; //right arm //upperarm boneParentNodeName[5] = "Bip01 Spine2"; boneNodeName[5] = "Bip01 R UpperArm"; boneSize[5] = "0.2 0.3 0.0"; boneMass[5] = 1;//5; boneShape[5] = $ShapeType::Capsule; boneOffset[5] = "0 0 0"; boneJointType[5] = $JointType::ConeTwist;//1;//3;// boneJointParam[5] = "0.785 0.785 0"; //forearm boneParentNodeName[6] = "Bip01 R UpperArm"; boneNodeName[6] = "Bip01 R Forearm"; boneSize[6] = "0.2 0.4 0.0"; boneMass[6] = 1;//5; boneShape[6] = $ShapeType::Capsule; boneOffset[6] = "0 0 0"; boneJointType[6] = $JointType::Hinge; boneJointParam[6] = "-1.57 0 0";//"0 1.57 0"; //left leg //upper boneParentNodeName[7] = "Bip01 Pelvis"; boneNodeName[7] = "Bip01 L Thigh"; boneSize[7] = "0.2 0.4 0.0"; boneMass[7] = 1;//7; boneShape[7] = $ShapeType::Capsule; boneOffset[7] = "0 0 0"; boneJointType[7] = $JointType::ConeTwist;//1;// boneJointParam[7] = "0.785 0.785 0"; //lower boneParentNodeName[8] = "Bip01 L Thigh"; boneNodeName[8] = "Bip01 L Calf"; boneSize[8] = "0.2 0.4 0.0"; boneMass[8] = 1;//7; boneShape[8] = $ShapeType::Capsule; boneOffset[8] = "0 0 0"; boneJointType[8] = $JointType::Hinge; boneJointParam[8] = "-1.57 0 0"; //right leg //upper boneParentNodeName[9] = "Bip01 Pelvis"; boneNodeName[9] = "Bip01 R Thigh"; boneSize[9] = "0.2 0.4 0.0"; boneMass[9] = 1;//7; boneShape[9] = $ShapeType::Capsule; boneOffset[9] = "0 0 0"; boneJointType[9] = $JointType::ConeTwist;//1;// boneJointParam[9] = "0.785 0.785 0"; //lower boneParentNodeName[10] = "Bip01 R Thigh"; boneNodeName[10] = "Bip01 R Calf"; boneSize[10] = "0.2 0.4 0.0"; boneMass[10] = 1;//7; boneShape[10] = $ShapeType::Capsule; boneOffset[10] = "0 0 0"; boneJointType[10] = $JointType::Hinge; boneJointParam[10] = "-1.57 0 0"; }; datablock RagDollData(ElfRagDoll) { category = "RigidBody"; shapeFile = "art/shapes/actors/Elf/Elf.dts"; minContactSpeed = 2.0; collisionSoundsCount = 1; collisionSound[0] = bodyFall0; //pelvis boneNodeName[0] = "Bip01 Pelvis"; boneSize[0] = "0.2 0.2 0.7"; boneMass[0] = 1;//25; boneShape[0] = $ShapeType::Capsule; boneOffset[0] = "0 0 0"; //torso boneParentNodeName[1] = "Bip01 Pelvis"; boneNodeName[1] = "Bip01 Spine2"; boneSize[1] = "0.2 0.2 0.7"; boneMass[1] = 1;//25; boneShape[1] = $ShapeType::Capsule; boneJointType[1] = $JointType::Hinge;//1; boneOffset[1] = "-0.3 0 0"; boneJointParam[1] = "0 1.57 0"; //head boneParentNodeName[2] = "Bip01 Spine2"; boneNodeName[2] = "Bip01 Head"; //boneSize[2] = "0.15 0.15 0.4"; boneSize[2] = "0.2 0.2 0.2"; boneMass[2] = 1;//5; boneShape[2] = $ShapeType::Capsule; boneOffset[2] = "0 0 0"; boneJointType[2] = $JointType::ConeTwist;//1;// boneJointParam[2] = "0.785 0.785 0";//"0 0 0";//"0.785 0.785 1.57";// //left arm //upperarm boneParentNodeName[3] = "Bip01 Spine2"; boneNodeName[3] = "Bip01 L UpperArm"; boneSize[3] = "0.1 0.2 0.2"; boneMass[3] = 1;//5; boneShape[3] = $ShapeType::Capsule; boneOffset[3] = "0.1 0 0"; boneJointType[3] = $JointType::ConeTwist;//1;// boneJointParam[3] = "0.785 0.785 0"; //forearm boneParentNodeName[4] = "Bip01 L UpperArm"; boneNodeName[4] = "Bip01 L Forearm"; boneSize[4] = "0.1 0.2 0.2"; boneMass[4] = 1;//5; boneShape[4] = $ShapeType::Capsule; boneOffset[4] = "0.1 0 0"; boneJointType[4] = $JointType::Hinge; boneJointParam[4] = "-1.57 0 0"; //right arm //upperarm boneParentNodeName[5] = "Bip01 Spine2"; boneNodeName[5] = "Bip01 R UpperArm"; boneSize[5] = "0.1 0.2 0.2"; boneMass[5] = 1;//5; boneShape[5] = $ShapeType::Capsule; boneOffset[5] = "0.1 0 0"; boneJointType[5] = $JointType::ConeTwist;//1;// boneJointParam[5] = "0.785 0.785 0"; //forearm boneParentNodeName[6] = "Bip01 R UpperArm"; boneNodeName[6] = "Bip01 R Forearm"; boneSize[6] = "0.1 0.2 0.2"; boneMass[6] =1;//5; boneShape[6] = $ShapeType::Capsule; boneOffset[6] = "0.1 0 0"; boneJointType[6] = $JointType::Hinge; boneJointParam[6] = "-1.57 0 0"; //left leg //upper boneParentNodeName[7] = "Bip01 Pelvis"; boneNodeName[7] = "Bip01 L Thigh"; boneSize[7] = "0.15 0.4 0.2"; boneMass[7] = 1;//7; boneShape[7] = $ShapeType::Capsule; boneOffset[7] = "0.0 0 0"; boneJointType[7] = $JointType::ConeTwist;//1;// boneJointParam[7] = "0.785 0.785 0"; //lower boneParentNodeName[8] = "Bip01 L Thigh"; boneNodeName[8] = "Bip01 L Calf"; boneSize[8] = "0.15 0.4 0.2"; boneMass[8] = 1;//7; boneShape[8] = $ShapeType::Capsule; boneOffset[8] = "0.0 0 0"; boneJointType[8] = $JointType::Hinge; boneJointParam[8] = "-1.57 0 0"; //right leg //upper boneParentNodeName[9] = "Bip01 Pelvis"; boneNodeName[9] = "Bip01 R Thigh"; boneSize[9] = "0.15 0.4 0.2"; boneMass[9] = 1;//7; boneShape[9] = $ShapeType::Capsule; boneOffset[9] = "0.0 0 0"; boneJointType[9] = $JointType::ConeTwist;//1;// boneJointParam[9] = "0.785 0.785 0"; //lower boneParentNodeName[10] = "Bip01 R Thigh"; boneNodeName[10] = "Bip01 R Calf"; boneSize[10] = "0.15 0.4 0.2"; boneMass[10] = 1;//7; boneShape[10] = $ShapeType::Capsule; boneOffset[10] = "0.0 0 0"; boneJointType[10] = $JointType::Hinge; boneJointParam[10] = "-1.57 0 0"; };
// ReSharper disable All using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json.Linq; using Frapid.Account.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Account.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Sign In Views. /// </summary> [RoutePrefix("api/v1.0/account/sign-in-view")] public class SignInViewController : FrapidApiController { /// <summary> /// The SignInView repository. /// </summary> private ISignInViewRepository SignInViewRepository; public SignInViewController() { } public SignInViewController(ISignInViewRepository repository) { this.SignInViewRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.SignInViewRepository == null) { this.SignInViewRepository = new Frapid.Account.DataAccess.SignInView { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Counts the number of sign in views. /// </summary> /// <returns>Returns the count of the sign in views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/account/sign-in-view/count")] [RestAuthorize] public long Count() { try { return this.SignInViewRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of sign in view for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("all")] [Route("~/api/account/sign-in-view/export")] [Route("~/api/account/sign-in-view/all")] [RestAuthorize] public IEnumerable<Frapid.Account.Entities.SignInView> Get() { try { return this.SignInViewRepository.Get(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 sign in views on each page, sorted by the property . /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/account/sign-in-view")] [RestAuthorize] public IEnumerable<Frapid.Account.Entities.SignInView> GetPaginatedResult() { try { return this.SignInViewRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 sign in views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/account/sign-in-view/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Account.Entities.SignInView> GetPaginatedResult(long pageNumber) { try { return this.SignInViewRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of sign in views. /// </summary> /// <returns>Returns an enumerable key/value collection of sign in views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/account/sign-in-view/display-fields")] [RestAuthorize] public IEnumerable<DisplayField> GetDisplayFields() { try { return this.SignInViewRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of sign in views using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered sign in views.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/account/sign-in-view/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.SignInViewRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 sign in views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/account/sign-in-view/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Account.Entities.SignInView> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.SignInViewRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of sign in views using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered sign in views.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/account/sign-in-view/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.SignInViewRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 sign in views on each page, sorted by the property . /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/account/sign-in-view/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Account.Entities.SignInView> GetFiltered(long pageNumber, string filterName) { try { return this.SignInViewRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel SSE hardware instructions via intrinsics /// </summary> [CLSCompliant(false)] public static class Sse { public static bool IsSupported { get { return false; } } /// <summary> /// __m128 _mm_add_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Add(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_and_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> And(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_andnot_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> AndNot(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpeq_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpgt_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpge_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmplt_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmple_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpneq_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareNotEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpngt_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareNotGreaterThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnge_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareNotGreaterThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnlt_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareNotLessThan(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpnle_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareNotLessThanOrEqual(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpord_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareOrdered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_cmpunord_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> CompareUnordered(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_div_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Divide(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_loadu_ps (float const* mem_address) /// </summary> public static unsafe Vector128<float> Load(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_load_ps (float const* mem_address) /// </summary> public static unsafe Vector128<float> LoadAligned(float* address) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_max_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Max(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_min_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Min(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_movehl_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> MoveHighToLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_movelh_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> MoveLowToHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_mul_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Multiply(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_or_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Or(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rcp_ps (__m128 a) /// </summary> public static Vector128<float> Reciprocal(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_rsqrt_ps (__m128 a) /// </summary> public static Vector128<float> ReciprocalSquareRoot(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_set_ps (float e3, float e2, float e1, float e0) /// </summary> public static Vector128<float> Set(float e3, float e2, float e1, float e0) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_set1_ps (float a) /// </summary> public static Vector128<float> Set1(float value) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_setzero_ps (void) /// </summary> public static Vector128<float> SetZero() { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_castpd_ps (__m128d a) /// __m128i _mm_castpd_si128 (__m128d a) /// __m128d _mm_castps_pd (__m128 a) /// __m128i _mm_castps_si128 (__m128 a) /// __m128d _mm_castsi128_pd (__m128i a) /// __m128 _mm_castsi128_ps (__m128i a) /// </summary> public static Vector128<U> StaticCast<T, U>(Vector128<T> value) where T : struct where U : struct { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_shuffle_ps (__m128 a, __m128 b, unsigned int control) /// </summary> public static Vector128<float> Shuffle(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_sqrt_ps (__m128 a) /// </summary> public static Vector128<float> Sqrt(Vector128<float> value) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_store_ps (float* mem_addr, __m128 a) /// </summary> public static unsafe void StoreAligned(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_stream_ps (float* mem_addr, __m128 a) /// </summary> public static unsafe void StoreAlignedNonTemporal(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// void _mm_storeu_ps (float* mem_addr, __m128 a) /// </summary> public static unsafe void Store(float* address, Vector128<float> source) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128d _mm_sub_ps (__m128d a, __m128d b) /// </summary> public static Vector128<float> Subtract(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_unpackhi_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> UnpackHigh(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_unpacklo_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> UnpackLow(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } /// <summary> /// __m128 _mm_xor_ps (__m128 a, __m128 b) /// </summary> public static Vector128<float> Xor(Vector128<float> left, Vector128<float> right) { throw new PlatformNotSupportedException(); } } }
/* * SystemIcons.cs - Implementation of the "System.Drawing.SystemIcons" class. * * Copyright (C) 2003 Neil Cawse. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing { using System; public sealed class SystemIcons { private enum IconType { Application = 0, Asterisk = 1, Error = 2, Exclamation = 3, Hand = 4, Information = 5, Question = 6, Warning = 7, WinLogo = 8 } private static Icon applicationIcon; private static Icon asteriskIcon; private static Icon errorIcon; private static Icon exclamationIcon; private static Icon handIcon; private static Icon informationIcon; private static Icon questionIcon; private static Icon warningIcon; private static Icon windowsLogoIcon; public SystemIcons() {} public static Icon Application { get { if (applicationIcon == null) applicationIcon = LoadIcon(IconType.Application); return applicationIcon; } } public static Icon Asterisk { get { if (asteriskIcon == null) { asteriskIcon = LoadIcon(IconType.Asterisk); } return asteriskIcon; } } public static Icon Error { get { if (errorIcon == null) { errorIcon = LoadIcon(IconType.Error); } return errorIcon; } } public static Icon Exclamation { get { if (exclamationIcon == null) { exclamationIcon = LoadIcon(IconType.Exclamation); } return exclamationIcon; } } public static Icon Hand { get { if (handIcon == null) { handIcon = LoadIcon(IconType.Hand); } return handIcon; } } public static Icon Information { get { if (informationIcon == null) { informationIcon = LoadIcon(IconType.Information); } return informationIcon; } } public static Icon Question { get { if (questionIcon == null) { questionIcon = LoadIcon(IconType.Question); } return questionIcon; } } public static Icon Warning { get { if (warningIcon == null) { warningIcon = LoadIcon(IconType.Warning); } return warningIcon; } } public static Icon WinLogo { get { if (windowsLogoIcon == null) { windowsLogoIcon = LoadIcon(IconType.WinLogo); } return windowsLogoIcon; } } // Load a particular icon from this assembly's resources. // Stolen from S.W.F.MessageBox.cs private static Icon LoadIcon(SystemIcons.IconType iconType) { lock(typeof(SystemIcons)) { Icon iconObject = null; try { switch(iconType) { case IconType.Application: { if(applicationIcon == null) { applicationIcon = new Icon (typeof(SystemIcons), "application.ico"); } iconObject = applicationIcon; } break; case IconType.Asterisk: { if(asteriskIcon == null) { asteriskIcon = new Icon (typeof(SystemIcons), "asterisk.ico"); } iconObject = asteriskIcon; } break; case IconType.Error: { if(errorIcon == null) { errorIcon = new Icon (typeof(SystemIcons), "error.ico"); } iconObject = errorIcon; } break; case IconType.Exclamation: { if(exclamationIcon == null) { exclamationIcon = new Icon (typeof(SystemIcons), "exclamation.ico"); } iconObject = exclamationIcon; } break; case IconType.Hand: { if(handIcon == null) { handIcon = new Icon (typeof(SystemIcons), "hand.ico"); } iconObject = handIcon; } break; case IconType.Information: { if(informationIcon == null) { informationIcon = new Icon (typeof(SystemIcons), "information.ico"); } iconObject = exclamationIcon; } break; case IconType.Question: { if(questionIcon == null) { questionIcon = new Icon (typeof(SystemIcons), "question.ico"); } iconObject = questionIcon; } break; case IconType.Warning: { if(warningIcon == null) { warningIcon = new Icon (typeof(SystemIcons), "warning.ico"); } iconObject = warningIcon; } break; case IconType.WinLogo: { if(windowsLogoIcon == null) { windowsLogoIcon = new Icon (typeof(SystemIcons), "windows.ico"); } iconObject = windowsLogoIcon; } break; } } catch { // Could not load the icon - ignore this condition. } return iconObject; } } } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Printing; using System.Data; using System.Windows.Forms; namespace dgvPrinter { public class DataGridViewPrinter { private DataGridView TheDataGridView; // The DataGridView Control which will be printed private PrintDocument ThePrintDocument; // The PrintDocument to be used for printing private bool IsCenterOnPage; // Determine if the report will be printed in the Top-Center of the page private bool IsWithTitle; // Determine if the page contain title text private string TheTitleText; // The title text to be printed in each page (if IsWithTitle is set to true) private Font TheTitleFont; // The font to be used with the title text (if IsWithTitle is set to true) private Color TheTitleColor; // The color to be used with the title text (if IsWithTitle is set to true) private bool IsWithPaging; // Determine if paging is used static int CurrentRow; // A static parameter that keep track on which Row (in the DataGridView control) that should be printed static int PageNumber; private int PageWidth; private int PageHeight; private int LeftMargin; private int TopMargin; private int RightMargin; private int BottomMargin; private float CurrentY; // A parameter that keep track on the y coordinate of the page, so the next object to be printed will start from this y coordinate private float RowHeaderHeight; private List<float> RowsHeight; private List<float> ColumnsWidth; private float TheDataGridViewWidth; // Maintain a generic list to hold start/stop points for the column printing // This will be used for wrapping in situations where the DataGridView will not fit on a single page private List<int[]> mColumnPoints; private List<float> mColumnPointsWidth; private int mColumnPoint; // The class constructor public DataGridViewPrinter(DataGridView aDataGridView, PrintDocument aPrintDocument, bool CenterOnPage, bool WithTitle, string aTitleText, Font aTitleFont, Color aTitleColor, bool WithPaging) { TheDataGridView = aDataGridView; ThePrintDocument = aPrintDocument; IsCenterOnPage = CenterOnPage; IsWithTitle = WithTitle; TheTitleText = aTitleText; TheTitleFont = aTitleFont; TheTitleColor = aTitleColor; IsWithPaging = WithPaging; PageNumber = 0; RowsHeight = new List<float>(); ColumnsWidth = new List<float>(); mColumnPoints = new List<int[]>(); mColumnPointsWidth = new List<float>(); // Claculating the PageWidth and the PageHeight if (!ThePrintDocument.DefaultPageSettings.Landscape) { PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Width; PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Height; } else { PageHeight = ThePrintDocument.DefaultPageSettings.PaperSize.Width; PageWidth = ThePrintDocument.DefaultPageSettings.PaperSize.Height; } // Claculating the page margins LeftMargin = ThePrintDocument.DefaultPageSettings.Margins.Left; TopMargin = ThePrintDocument.DefaultPageSettings.Margins.Top; RightMargin = ThePrintDocument.DefaultPageSettings.Margins.Right; BottomMargin = ThePrintDocument.DefaultPageSettings.Margins.Bottom; // First, the current row to be printed is the first row in the DataGridView control CurrentRow = 0; } // The function that calculate the height of each row (including the header row), the width of each column (according to the longest text in all its cells including the header cell), and the whole DataGridView width private void Calculate(Graphics g) { if (PageNumber == 0) // Just calculate once { SizeF tmpSize = new SizeF(); Font tmpFont; float tmpWidth; TheDataGridViewWidth = 0; for (int i = 0; i < TheDataGridView.Columns.Count; i++) { tmpFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font; if (tmpFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style tmpFont = TheDataGridView.DefaultCellStyle.Font; tmpSize = g.MeasureString(TheDataGridView.Columns[i].HeaderText, tmpFont); tmpWidth = tmpSize.Width; RowHeaderHeight = tmpSize.Height; for (int j = 0; j < TheDataGridView.Rows.Count; j++) { tmpFont = TheDataGridView.Rows[j].DefaultCellStyle.Font; if (tmpFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control tmpFont = TheDataGridView.DefaultCellStyle.Font; tmpSize = g.MeasureString("Anything", tmpFont); RowsHeight.Add(tmpSize.Height); tmpSize = g.MeasureString(TheDataGridView.Rows[j].Cells[i].EditedFormattedValue.ToString(), tmpFont); if (tmpSize.Width > tmpWidth) tmpWidth = tmpSize.Width; } if (TheDataGridView.Columns[i].Visible) TheDataGridViewWidth += tmpWidth; ColumnsWidth.Add(tmpWidth); } // Define the start/stop column points based on the page width and the DataGridView Width // We will use this to determine the columns which are drawn on each page and how wrapping will be handled // By default, the wrapping will occurr such that the maximum number of columns for a page will be determine int k; int mStartPoint = 0; for (k = 0; k < TheDataGridView.Columns.Count; k++) if (TheDataGridView.Columns[k].Visible) { mStartPoint = k; break; } int mEndPoint = TheDataGridView.Columns.Count; for (k = TheDataGridView.Columns.Count - 1; k >= 0; k--) if (TheDataGridView.Columns[k].Visible) { mEndPoint = k + 1; break; } float mTempWidth = TheDataGridViewWidth; float mTempPrintArea = (float)PageWidth - (float)LeftMargin - (float)RightMargin; // We only care about handling where the total datagridview width is bigger then the print area if (TheDataGridViewWidth > mTempPrintArea) { mTempWidth = 0.0F; for (k = 0; k < TheDataGridView.Columns.Count; k++) { if (TheDataGridView.Columns[k].Visible) { mTempWidth += ColumnsWidth[k]; // If the width is bigger than the page area, then define a new column print range if (mTempWidth > mTempPrintArea) { mTempWidth -= ColumnsWidth[k]; mColumnPoints.Add(new int[] { mStartPoint, mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mStartPoint = k; mTempWidth = ColumnsWidth[k]; } } // Our end point is actually one index above the current index mEndPoint = k + 1; } } // Add the last set of columns mColumnPoints.Add(new int[] { mStartPoint, mEndPoint }); mColumnPointsWidth.Add(mTempWidth); mColumnPoint = 0; } } // The funtion that print the title, page number, and the header row private void DrawHeader(Graphics g) { CurrentY = (float)TopMargin; // Printing the page number (if isWithPaging is set to true) if (IsWithPaging) { PageNumber++; string PageString = "Page " + PageNumber.ToString(); StringFormat PageStringFormat = new StringFormat(); PageStringFormat.Trimming = StringTrimming.Word; PageStringFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip; PageStringFormat.Alignment = StringAlignment.Far; Font PageStringFont = new Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point); RectangleF PageStringRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(PageString, PageStringFont).Height); g.DrawString(PageString, PageStringFont, new SolidBrush(Color.Black), PageStringRectangle, PageStringFormat); CurrentY += g.MeasureString(PageString, PageStringFont).Height; } // Printing the title (if IsWithTitle is set to true) if (IsWithTitle) { StringFormat TitleFormat = new StringFormat(); TitleFormat.Trimming = StringTrimming.Word; TitleFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip; if (IsCenterOnPage) TitleFormat.Alignment = StringAlignment.Center; else TitleFormat.Alignment = StringAlignment.Near; RectangleF TitleRectangle = new RectangleF((float)LeftMargin, CurrentY, (float)PageWidth - (float)RightMargin - (float)LeftMargin, g.MeasureString(TheTitleText, TheTitleFont).Height); g.DrawString(TheTitleText, TheTitleFont, new SolidBrush(TheTitleColor), TitleRectangle, TitleFormat); CurrentY += g.MeasureString(TheTitleText, TheTitleFont).Height; } // Calculating the starting x coordinate that the printing process will start from float CurrentX = (float)LeftMargin; if (IsCenterOnPage) CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F; // Setting the HeaderFore style Color HeaderForeColor = TheDataGridView.ColumnHeadersDefaultCellStyle.ForeColor; if (HeaderForeColor.IsEmpty) // If there is no special HeaderFore style, then use the default DataGridView style HeaderForeColor = TheDataGridView.DefaultCellStyle.ForeColor; SolidBrush HeaderForeBrush = new SolidBrush(HeaderForeColor); // Setting the HeaderBack style Color HeaderBackColor = TheDataGridView.ColumnHeadersDefaultCellStyle.BackColor; if (HeaderBackColor.IsEmpty) // If there is no special HeaderBack style, then use the default DataGridView style HeaderBackColor = TheDataGridView.DefaultCellStyle.BackColor; SolidBrush HeaderBackBrush = new SolidBrush(HeaderBackColor); // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control) Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1); // Setting the HeaderFont style Font HeaderFont = TheDataGridView.ColumnHeadersDefaultCellStyle.Font; if (HeaderFont == null) // If there is no special HeaderFont style, then use the default DataGridView font style HeaderFont = TheDataGridView.DefaultCellStyle.Font; // Calculating and drawing the HeaderBounds RectangleF HeaderBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowHeaderHeight); g.FillRectangle(HeaderBackBrush, HeaderBounds); // Setting the format that will be used to print each cell of the header row StringFormat CellFormat = new StringFormat(); CellFormat.Trimming = StringTrimming.Word; CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit | StringFormatFlags.NoClip; // Printing each visible cell of the header row RectangleF CellBounds; float ColumnWidth; for (int i = (int)mColumnPoints[mColumnPoint].GetValue(0); i < (int)mColumnPoints[mColumnPoint].GetValue(1); i++) { if (!TheDataGridView.Columns[i].Visible) continue; // If the column is not visible then ignore this iteration ColumnWidth = ColumnsWidth[i]; // Check the CurrentCell alignment and apply it to the CellFormat if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Right")) CellFormat.Alignment = StringAlignment.Far; else if (TheDataGridView.ColumnHeadersDefaultCellStyle.Alignment.ToString().Contains("Center")) CellFormat.Alignment = StringAlignment.Center; else CellFormat.Alignment = StringAlignment.Near; CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowHeaderHeight); // Printing the cell text g.DrawString(TheDataGridView.Columns[i].HeaderText, HeaderFont, HeaderForeBrush, CellBounds, CellFormat); // Drawing the cell bounds if (TheDataGridView.RowHeadersBorderStyle != DataGridViewHeaderBorderStyle.None) // Draw the cell border only if the HeaderBorderStyle is not None g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowHeaderHeight); CurrentX += ColumnWidth; } CurrentY += RowHeaderHeight; } // The function that print a bunch of rows that fit in one page // When it returns true, meaning that there are more rows still not printed, so another PagePrint action is required // When it returns false, meaning that all rows are printed (the CureentRow parameter reaches the last row of the DataGridView control) and no further PagePrint action is required private bool DrawRows(Graphics g) { // Setting the LinePen that will be used to draw lines and rectangles (derived from the GridColor property of the DataGridView control) Pen TheLinePen = new Pen(TheDataGridView.GridColor, 1); // The style paramters that will be used to print each cell Font RowFont; Color RowForeColor; Color RowBackColor; SolidBrush RowForeBrush; SolidBrush RowBackBrush; SolidBrush RowAlternatingBackBrush; // Setting the format that will be used to print each cell StringFormat CellFormat = new StringFormat(); CellFormat.Trimming = StringTrimming.Word; CellFormat.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.LineLimit; // Printing each visible cell RectangleF RowBounds; float CurrentX; float ColumnWidth; while (CurrentRow < TheDataGridView.Rows.Count) { if (TheDataGridView.Rows[CurrentRow].Visible) // Print the cells of the CurrentRow only if that row is visible { // Setting the row font style RowFont = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.Font; if (RowFont == null) // If the there is no special font style of the CurrentRow, then use the default one associated with the DataGridView control RowFont = TheDataGridView.DefaultCellStyle.Font; // Setting the RowFore style RowForeColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.ForeColor; if (RowForeColor.IsEmpty) // If the there is no special RowFore style of the CurrentRow, then use the default one associated with the DataGridView control RowForeColor = TheDataGridView.DefaultCellStyle.ForeColor; RowForeBrush = new SolidBrush(RowForeColor); // Setting the RowBack (for even rows) and the RowAlternatingBack (for odd rows) styles RowBackColor = TheDataGridView.Rows[CurrentRow].DefaultCellStyle.BackColor; if (RowBackColor.IsEmpty) // If the there is no special RowBack style of the CurrentRow, then use the default one associated with the DataGridView control { RowBackBrush = new SolidBrush(TheDataGridView.DefaultCellStyle.BackColor); RowAlternatingBackBrush = new SolidBrush(TheDataGridView.AlternatingRowsDefaultCellStyle.BackColor); } else // If the there is a special RowBack style of the CurrentRow, then use it for both the RowBack and the RowAlternatingBack styles { RowBackBrush = new SolidBrush(RowBackColor); RowAlternatingBackBrush = new SolidBrush(RowBackColor); } // Calculating the starting x coordinate that the printing process will start from CurrentX = (float)LeftMargin; if (IsCenterOnPage) CurrentX += (((float)PageWidth - (float)RightMargin - (float)LeftMargin) - mColumnPointsWidth[mColumnPoint]) / 2.0F; // Calculating the entire CurrentRow bounds RowBounds = new RectangleF(CurrentX, CurrentY, mColumnPointsWidth[mColumnPoint], RowsHeight[CurrentRow]); // Filling the back of the CurrentRow if (CurrentRow % 2 == 0) g.FillRectangle(RowBackBrush, RowBounds); else g.FillRectangle(RowAlternatingBackBrush, RowBounds); // Printing each visible cell of the CurrentRow for (int CurrentCell = (int)mColumnPoints[mColumnPoint].GetValue(0); CurrentCell < (int)mColumnPoints[mColumnPoint].GetValue(1); CurrentCell++) { if (!TheDataGridView.Columns[CurrentCell].Visible) continue; // If the cell is belong to invisible column, then ignore this iteration // Check the CurrentCell alignment and apply it to the CellFormat if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Right")) CellFormat.Alignment = StringAlignment.Far; else if (TheDataGridView.Columns[CurrentCell].DefaultCellStyle.Alignment.ToString().Contains("Center")) CellFormat.Alignment = StringAlignment.Center; else CellFormat.Alignment = StringAlignment.Near; ColumnWidth = ColumnsWidth[CurrentCell]; RectangleF CellBounds = new RectangleF(CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]); // Printing the cell text g.DrawString(TheDataGridView.Rows[CurrentRow].Cells[CurrentCell].EditedFormattedValue.ToString(), RowFont, RowForeBrush, CellBounds, CellFormat); // Drawing the cell bounds if (TheDataGridView.CellBorderStyle != DataGridViewCellBorderStyle.None) // Draw the cell border only if the CellBorderStyle is not None g.DrawRectangle(TheLinePen, CurrentX, CurrentY, ColumnWidth, RowsHeight[CurrentRow]); CurrentX += ColumnWidth; } CurrentY += RowsHeight[CurrentRow]; // Checking if the CurrentY is exceeds the page boundries // If so then exit the function and returning true meaning another PagePrint action is required if ((int)CurrentY > (PageHeight - TopMargin - BottomMargin)) { CurrentRow++; return true; } } CurrentRow++; } CurrentRow = 0; mColumnPoint++; // Continue to print the next group of columns if (mColumnPoint == mColumnPoints.Count) // Which means all columns are printed { mColumnPoint = 0; return false; } else return true; } // The method that calls all other functions public bool DrawDataGridView(Graphics g) { try { Calculate(g); DrawHeader(g); bool bContinue = DrawRows(g); return bContinue; } catch (Exception ex) { MessageBox.Show("Operation failed: " + ex.Message.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using SOURCE.Infrastructure.Services.Captcha; namespace SOURCE.Infrastructure.Services.Implementations.Captcha { /// <summary> /// Summary description for CaptchaImage. /// </summary> public class CaptchaImage : IDisposable, ICaptchaImage { // Internal properties. private string text; private int width; private int height; private string familyName; private Bitmap image; // For generating random numbers. private Random random = new Random(); // ==================================================================== // Initializes a new instance of the CaptchaImage class using the // specified text, width and height. // ==================================================================== public Bitmap GenerateImage(string s, int width, int height) { return GenerateImage(s, width, height, null); } // ==================================================================== // Initializes a new instance of the CaptchaImage class using the // specified text, width, height and font family. // ==================================================================== public Bitmap GenerateImage(string s, int width, int height, string familyName) { this.text = s; this.SetDimensions(width, height); if (familyName != null) this.SetFamilyName(familyName); this.GenerateImage(); return this.image; } // // Returns a string of six random digits. // public string GenerateRandomCode(long lenght = 6) { string s = ""; for (long i = 0; i < lenght; i++) s = String.Concat(s, this.random.Next(10).ToString()); return s; } // ==================================================================== // This member overrides Object.Finalize. // ==================================================================== ~CaptchaImage() { Dispose(false); } // ==================================================================== // Releases all resources used by this object. // ==================================================================== public void Dispose() { GC.SuppressFinalize(this); this.Dispose(true); } // ==================================================================== // Custom Dispose method to clean up unmanaged resources. // ==================================================================== protected virtual void Dispose(bool disposing) { if (disposing) { // Dispose of the bitmap. if (this.image != null) this.image.Dispose(); } } // ==================================================================== // Sets the image width and height. // ==================================================================== private void SetDimensions(int width, int height) { // Check the width and height. if (width <= 0) throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero."); if (height <= 0) throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero."); this.width = width; this.height = height; } // ==================================================================== // Sets the font used for the image text. // ==================================================================== private void SetFamilyName(string familyName) { // If the named font is not installed, default to a system font. try { Font font = new Font(this.familyName, 12F); this.familyName = familyName; font.Dispose(); } catch { this.familyName = System.Drawing.FontFamily.GenericSerif.Name; } } // ==================================================================== // Creates the bitmap image. // ==================================================================== private void GenerateImage() { // Create a new 32-bit bitmap image. Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb); // Create a graphics object for drawing. Graphics g = Graphics.FromImage(bitmap); g.SmoothingMode = SmoothingMode.AntiAlias; Rectangle rect = new Rectangle(0, 0, this.width, this.height); // Fill in the background. HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White); g.FillRectangle(hatchBrush, rect); // Set up the text font. SizeF size; float fontSize = rect.Height + 1; Font font; // Adjust the font size until the text fits within the image. do { fontSize--; font = new Font(this.familyName, fontSize, FontStyle.Bold); size = g.MeasureString(this.text, font); } while (size.Width > rect.Width); // Set up the text format. StringFormat format = new StringFormat(); format.Alignment = StringAlignment.Center; format.LineAlignment = StringAlignment.Center; // Create a path using the text and warp it randomly. GraphicsPath path = new GraphicsPath(); path.AddString(this.text, font.FontFamily, (int)font.Style, font.Size, rect, format); float v = 4F; PointF[] points = { new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v), new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v), new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v), new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v) }; Matrix matrix = new Matrix(); matrix.Translate(0F, 0F); path.Warp(points, rect, matrix, WarpMode.Perspective, 0F); // Draw the text. hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray); g.FillPath(hatchBrush, path); // Add some random noise. int m = Math.Max(rect.Width, rect.Height); for (int i = 0; i < (int)(rect.Width * rect.Height / 30F); i++) { int x = this.random.Next(rect.Width); int y = this.random.Next(rect.Height); int w = this.random.Next(m / 50); int h = this.random.Next(m / 50); g.FillEllipse(hatchBrush, x, y, w, h); } // Clean up. font.Dispose(); hatchBrush.Dispose(); g.Dispose(); // Set the image. this.image = bitmap; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptInstance : MarshalByRefObject, IScriptInstance { public static readonly long MaxMeasurementPeriod = 30 * TimeSpan.TicksPerMinute; public Object[] PluginData = new Object[0]; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<string, IScriptApi> m_Apis = new Dictionary<string, IScriptApi>(); private string m_Assembly; private UUID m_AttachedAvatar; private bool m_CollisionInQueue; private int m_ControlEventsInQueue; private EventWaitHandle m_coopSleepHandle; private bool m_coopTermination; private string m_CurrentEvent = String.Empty; private UUID m_CurrentStateHash; /// <summary> /// The current work item if an event for this script is running or waiting to run, /// </summary> /// <remarks> /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock. /// </remarks> private IScriptWorkItem m_CurrentWorkItem; private DetectParams[] m_DetectParams; private long m_eventDelayTicks; private DateTime m_EventStart; private bool m_InEvent; private bool m_InSelfDelete; private int m_LastControlLevel; private int m_MaxScriptQueue; // The following is for setting a minimum delay between events private double m_minEventDelay; private long m_nextEventTimeTicks; private bool m_postOnRez; private UUID m_RegionID; private bool m_SaveState = true; private IScript m_Script; private bool m_startedFromSavedState; private bool m_startOnInit = true; private StateSource m_stateSource; private bool m_Suspended; private bool m_TimerQueued; public ScriptInstance( IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item, int startParam, bool postOnRez, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; Part = part; ScriptTask = item; // This is currently only here to allow regression tests to get away without specifying any inventory // item when they are testing script logic that doesn't require an item. if (ScriptTask != null) { ScriptName = ScriptTask.Name; ItemID = ScriptTask.ItemID; AssetID = ScriptTask.AssetID; } PrimName = part.ParentGroup.Name; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_postOnRez = postOnRez; m_AttachedAvatar = Part.ParentGroup.AttachedAvatar; m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID; if (Engine.Config.GetString("ScriptStopStrategy", "abort") == "co-op") { m_coopTermination = true; m_coopSleepHandle = new XEngineEventWaitHandle(false, EventResetMode.AutoReset); } } public UUID AppDomain { get; set; } public UUID AssetID { get; private set; } public int DebugLevel { get; set; } public IScriptEngine Engine { get; private set; } public Queue EventQueue { get; private set; } public long EventsProcessed { get; private set; } public long EventsQueued { get { lock (EventQueue) return EventQueue.Count; } } public UUID ItemID { get; private set; } public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; } public uint LocalID { get { return Part.LocalId; } } public long MeasurementPeriodExecutionTime { get; private set; } public long MeasurementPeriodTickStart { get; private set; } /// <summary> /// Used by llMinEventDelay to suppress events happening any faster than this speed. /// This currently restricts all events in one go. Not sure if each event type has /// its own check so take the simple route first. /// </summary> public double MinEventDelay { get { return m_minEventDelay; } set { if (value > 0.001) m_minEventDelay = value; else m_minEventDelay = 0.0; m_eventDelayTicks = (long)(m_minEventDelay * 10000000L); m_nextEventTimeTicks = DateTime.Now.Ticks; } } public UUID ObjectID { get { return Part.UUID; } } public SceneObjectPart Part { get; private set; } public string PrimName { get; private set; } public UUID RegionID { get { return m_RegionID; } } public uint RootLocalID { get { return Part.ParentGroup.LocalId; } } public UUID RootObjectID { get { return Part.ParentGroup.UUID; } } public bool Running { get; set; } public string ScriptName { get; private set; } public TaskInventoryItem ScriptTask { get; private set; } public bool ShuttingDown { get; set; } public int StartParam { get; set; } public string State { get; set; } public bool Suspended { get { return m_Suspended; } set { // Need to do this inside a lock in order to avoid races with EventProcessor() lock (m_Script) { bool wasSuspended = m_Suspended; m_Suspended = value; if (wasSuspended && !m_Suspended) { lock (EventQueue) { // Need to place ourselves back in a work item if there are events to process if (EventQueue.Count > 0 && Running && !ShuttingDown) m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } } } public DateTime TimeStarted { get; private set; } public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry") { m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } } public void ClearQueue() { m_TimerQueued = false; EventQueue.Clear(); } public void DestroyScriptInstance() { ReleaseControls(); AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID); } /// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { // We check here as the thread stopping this instance from running may itself hold the m_Script lock. if (!Running) return 0; lock (m_Script) { // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName); if (Suspended) return 0; EventParams data = null; lock (EventQueue) { data = (EventParams)EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } return 0; } if (data.EventName == "timer") m_TimerQueued = false; if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) m_ControlEventsInQueue--; } if (data.EventName == "collision") m_CollisionInQueue = false; } if (DebugLevel >= 2) m_log.DebugFormat( "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", data.EventName, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { State = data.Params[0].ToString(); if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", State, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } else { if (Engine.World.PipeEventsForScript(LocalID) || data.EventName == "control") // Don't freeze avies! { // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; int start = Util.EnvironmentTickCount(); // Reset the measurement period when we reach the end of the current one. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod) MeasurementPeriodTickStart = start; m_Script.ExecuteEvent(State, data.EventName, data.Params); MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start; m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(m_Assembly); m_SaveState = false; } } catch(EventAbortException) { } catch (Exception e) { // m_log.DebugFormat( // "[SCRIPT] Exception in script {0} {1}: {2}{3}", // ScriptName, ItemID, e.Message, e.StackTrace); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException) && !(e.InnerException is ScriptCoopStopException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) text = text.Substring(0, 1000); Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, Part.AbsolutePosition, Part.Name, Part.UUID, false); m_log.Debug(string.Format( "[SCRIPT INSTANCE]: Runtime error in script {0}, part {1} {2} at {3} in {4} ", ScriptName, PrimName, Part.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name), e); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; Engine.World.DeleteSceneObject(Part.ParentGroup, false); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; Part.Inventory.RemoveInventoryItem(ItemID); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.", PrimName, ScriptName, data.EventName, State); } } } } // If there are more events and we are currently running and not shutting down, then ask the // script engine to run the next event. lock (EventQueue) { EventsProcessed++; if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } } m_DetectParams = null; return 0; } } public int EventTime() { if (!m_InEvent) return 0; return (DateTime.Now - m_EventStart).Seconds; } public IScriptApi GetApi(string name) { if (m_Apis.ContainsKey(name)) { // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName); return m_Apis[name]; } // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName); return null; } public string GetAssemblyName() { return m_Assembly; } public UUID GetDetectID(int idx) { if (m_DetectParams == null) return UUID.Zero; if (idx < 0 || idx >= m_DetectParams.Length) return UUID.Zero; return m_DetectParams[idx].Key; } public DetectParams GetDetectParams(int idx) { if (m_DetectParams == null) return null; if (idx < 0 || idx >= m_DetectParams.Length) return null; return m_DetectParams[idx]; } public Dictionary<string, object> GetVars() { if (m_Script != null) return m_Script.GetVars(); else return new Dictionary<string, object>(); } public string GetXMLState() { bool run = Running; Stop(100); Running = run; // We should not be doing this, but since we are about to // dispose this, it really doesn't make a difference // This is meant to work around a Windows only race // m_InEvent = false; // Force an update of the in-memory plugin data // PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); return ScriptSerializer.Serialize(this); } public void Init() { if (ShuttingDown) return; if (m_startedFromSavedState) { if (m_startOnInit) Start(); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] { new LSL_Types.LSLInteger(StartParam) }, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } else if (m_stateSource == StateSource.RegionStart) { //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script"); PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0])); } else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting) { // CHANGED_REGION PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0])); // CHANGED_TELEPORT if (m_stateSource == StateSource.Teleporting) PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0])); } } else { if (m_startOnInit) Start(); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] { new LSL_Types.LSLInteger(StartParam) }, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } } } /// <summary> /// Load the script from an assembly into an AppDomain. /// </summary> /// <param name='dom'></param> /// <param name='assembly'></param> /// <param name='stateSource'></param> /// <returns>false if load failed, true if suceeded</returns> public bool Load(AppDomain dom, string assembly, StateSource stateSource) { m_Assembly = assembly; m_stateSource = stateSource; ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle); } try { object[] constructorParams; Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly)); Type scriptType = scriptAssembly.GetType("SecondLife.XEngineScript"); if (scriptType != null) { constructorParams = new object[] { m_coopSleepHandle }; } else if (!m_coopTermination) { scriptType = scriptAssembly.GetType("SecondLife.Script"); constructorParams = null; } else { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. You must remove all existing {6}* script DLL files before using enabling co-op termination" + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run" + " or by deleting these files manually.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly); return false; } // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}", // scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name); if (dom != System.AppDomain.CurrentDomain) m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null, null); else m_Script = (IScript)scriptAssembly.CreateInstance( scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null); //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error loading assembly {6}. Exception {7}{8}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace); return false; } try { foreach (KeyValuePair<string, IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace); return false; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = Encoding.UTF8.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (!Running) m_startOnInit = false; Running = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.WarnFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState); } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace); } } // else // { // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID); // if (presence != null && (!postOnRez)) // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // } return true; } /// <summary> /// Post an event to this script instance. /// </summary> /// <remarks> /// The request to run the event is sent /// </remarks> /// <param name="data"></param> public void PostEvent(EventParams data) { // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); if (!Running) return; // If min event delay is set then ignore any events untill the time has expired // This currently only allows 1 event of any type in the given time period. // This may need extending to allow for a time for each individual event type. if (m_eventDelayTicks != 0) { if (DateTime.Now.Ticks < m_nextEventTimeTicks) return; m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks; } lock (EventQueue) { if (EventQueue.Count >= m_MaxScriptQueue) return; if (data.EventName == "timer") { if (m_TimerQueued) return; m_TimerQueued = true; } if (data.EventName == "control") { int held = ((LSL_Types.LSLInteger)data.Params[1]).value; // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value; // If the last message was a 0 (nothing held) // and this one is also nothing held, drop it // if (m_LastControlLevel == held && held == 0) return; // If there is one or more queued, then queue // only changed ones, else queue unconditionally // if (m_ControlEventsInQueue > 0) { if (m_LastControlLevel == held) return; } m_LastControlLevel = held; m_ControlEventsInQueue++; } if (data.EventName == "collision") { if (m_CollisionInQueue) return; if (data.DetectParams == null) return; m_CollisionInQueue = true; } EventQueue.Enqueue(data); if (m_CurrentWorkItem == null) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } public void RemoveState() { string savedState = Path.Combine(Path.GetDirectoryName(m_Assembly), ItemID.ToString() + ".state"); try { File.Delete(savedState); } catch (Exception e) { m_log.Warn( string.Format( "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ", savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name), e); } } public void ResetScript(int timeout) { if (m_Script == null) return; bool running = Running; RemoveState(); ReleaseControls(); Stop(timeout); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.UnregisterScriptFacilities(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) Start(); m_SaveState = true; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); } public void Resume() { Suspended = false; } public void SaveState(string assembly) { // If we're currently in an event, just tell it to save upon return // if (m_InEvent) { m_SaveState = true; return; } PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); string xml = ScriptSerializer.Serialize(this); // Compare hash of the state we just just created with the state last written to disk // If the state is different, update the disk file. UUID hash = UUID.Parse(Utils.MD5String(xml)); if (hash != m_CurrentStateHash) { try { FileStream fs = File.Create(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state")); Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml); fs.Write(buf, 0, buf.Length); fs.Close(); } catch (Exception) { // m_log.Error("Unable to save xml\n"+e.ToString()); } //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"))) //{ // throw new Exception("Completed persistence save, but no file was created"); //} m_CurrentStateHash = hash; } } public void SetState(string state) { if (state == State) return; PostEvent(new EventParams("state_exit", new Object[0], new DetectParams[0])); PostEvent(new EventParams("state", new Object[] { state }, new DetectParams[0])); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } public void SetVars(Dictionary<string, object> vars) { m_Script.SetVars(vars); } public void Start() { lock (EventQueue) { if (Running) return; Running = true; TimeStarted = DateTime.Now; MeasurementPeriodTickStart = Util.EnvironmentTickCount(); MeasurementPeriodExecutionTime = 0; if (EventQueue.Count > 0) { if (m_CurrentWorkItem == null) m_CurrentWorkItem = Engine.QueueEventHandler(this); // else // m_log.Error("[Script] Tried to start a script that was already queued"); } } } public bool Stop(int timeout) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}", ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks); IScriptWorkItem workItem; lock (EventQueue) { if (!Running) return true; // If we're not running or waiting to run an event then we can safely stop. if (m_CurrentWorkItem == null) { Running = false; return true; } // If we are waiting to run an event then we can try to cancel it. if (m_CurrentWorkItem.Cancel()) { m_CurrentWorkItem = null; Running = false; return true; } workItem = m_CurrentWorkItem; Running = false; } // Wait for the current event to complete. if (!m_InSelfDelete) { if (!m_coopTermination) { // If we're not co-operative terminating then try and wait for the event to complete before stopping if (workItem.Wait(timeout)) return true; } else { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); // This will terminate the event on next handle check by the script. m_coopSleepHandle.Set(); // For now, we will wait forever since the event should always cleanly terminate once LSL loop // checking is implemented. May want to allow a shorter timeout option later. if (workItem.Wait(Timeout.Infinite)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); return true; } } } lock (EventQueue) { workItem = m_CurrentWorkItem; } if (workItem == null) return true; // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then // forcibly abort the work item (this aborts the underlying thread). // Co-operative termination should never reach this point. if (!m_InSelfDelete) { m_log.DebugFormat( "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms", ScriptName, ItemID, PrimName, LocalID, timeout); workItem.Abort(); } lock (EventQueue) { m_CurrentWorkItem = null; } return true; } public void Suspend() { Suspended = true; } public override string ToString() { return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName); } public void VarDump(Dictionary<string, object> vars) { // m_log.Info("Variable dump for script "+ ItemID.ToString()); // foreach (KeyValuePair<string, object> v in vars) // { // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString()); // } } private string FormatException(Exception e) { if (e.InnerException == null) // Not a normal runtime error return e.ToString(); string message = "Runtime error:\n" + e.InnerException.StackTrace; string[] lines = message.Split(new char[] { '\n' }); foreach (string line in lines) { if (line.Contains("SecondLife.Script")) { int idx = line.IndexOf(':'); if (idx != -1) { string val = line.Substring(idx + 1); int lineNum = 0; if (int.TryParse(val, out lineNum)) { KeyValuePair<int, int> pos = Compiler.FindErrorPosition( lineNum, 0, LineMap); int scriptLine = pos.Key; int col = pos.Value; if (scriptLine == 0) scriptLine++; if (col == 0) col++; message = string.Format("Runtime error:\n" + "({0}): {1}", scriptLine - 1, e.InnerException.Message); return message; } } } } // m_log.ErrorFormat("Scripting exception:"); // m_log.ErrorFormat(e.ToString()); return e.ToString(); } private void ReleaseControls() { int permsMask; UUID permsGranter; lock (Part.TaskInventory) { if (!Part.TaskInventory.ContainsKey(ItemID)) return; permsGranter = Part.TaskInventory[ItemID].PermsGranter; permsMask = Part.TaskInventory[ItemID].PermsMask; } if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0) { ScenePresence presence = Engine.World.GetScenePresence(permsGranter); if (presence != null) presence.UnRegisterControlEventsToScript(LocalID, ItemID); } } } /// <summary> /// Xengine event wait handle. /// </summary> /// <remarks> /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that /// when scripts are running in different AppDomains the lease does not expire. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this, /// proper remoting sponsorship needs to be implemented across the board. /// </remarks> public class XEngineEventWaitHandle : EventWaitHandle { public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) { } public override Object InitializeLifetimeService() { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Security; using System.Security.Principal; using System.Threading; using System.ComponentModel; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; namespace System.Net.Security { // // The class maintains the state of the authentication process and the security context. // It encapsulates security context and does the real work in authentication and // user data encryption // internal class NegoState { private static readonly byte[] s_emptyMessage = new byte[0]; // used in reference comparisons private static readonly AsyncCallback s_readCallback = new AsyncCallback(ReadCallback); private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private Stream _innerStream; private bool _leaveStreamOpen; private Exception _exception; private StreamFramer _framer; private NTAuthentication _context; private int _nestedAuth; internal const int ERROR_TRUST_FAILURE = 1790; // Used to serialize protectionLevel or impersonationLevel mismatch error to the remote side. internal const int MaxReadFrameSize = 64 * 1024; internal const int MaxWriteDataSize = 63 * 1024; // 1k for the framing and trailer that is always less as per SSPI. private bool _canRetryAuthentication; private ProtectionLevel _expectedProtectionLevel; private TokenImpersonationLevel _expectedImpersonationLevel; private uint _writeSequenceNumber; private uint _readSequenceNumber; private ExtendedProtectionPolicy _extendedProtectionPolicy; // SSPI does not send a server ack on successful auth. // This is a state variable used to gracefully handle auth confirmation. private bool _remoteOk = false; internal NegoState(Stream innerStream, bool leaveStreamOpen) { if (innerStream == null) { throw new ArgumentNullException("stream"); } _innerStream = innerStream; _leaveStreamOpen = leaveStreamOpen; } internal static string DefaultPackage { get { return NegotiationInfoClass.Negotiate; } } internal IIdentity GetIdentity() { CheckThrow(true); return NegotiateStreamPal.GetIdentity(_context); } internal void ValidateCreateContext( string package, NetworkCredential credential, string servicePrincipalName, ExtendedProtectionPolicy policy, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (policy != null) { // One of these must be set if EP is turned on if (policy.CustomChannelBinding == null && policy.CustomServiceNames == null) { throw new ArgumentException(SR.net_auth_must_specify_extended_protection_scheme, nameof(policy)); } _extendedProtectionPolicy = policy; } else { _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } ValidateCreateContext(package, true, credential, servicePrincipalName, _extendedProtectionPolicy.CustomChannelBinding, protectionLevel, impersonationLevel); } internal void ValidateCreateContext( string package, bool isServer, NetworkCredential credential, string servicePrincipalName, ChannelBinding channelBinding, ProtectionLevel protectionLevel, TokenImpersonationLevel impersonationLevel) { if (_exception != null && !_canRetryAuthentication) { ExceptionDispatchInfo.Throw(_exception); } if (_context != null && _context.IsValidContext) { throw new InvalidOperationException(SR.net_auth_reauth); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } if (servicePrincipalName == null) { throw new ArgumentNullException(nameof(servicePrincipalName)); } NegotiateStreamPal.ValidateImpersonationLevel(impersonationLevel); if (_context != null && IsServer != isServer) { throw new InvalidOperationException(SR.net_auth_client_server); } _exception = null; _remoteOk = false; _framer = new StreamFramer(_innerStream); _framer.WriteHeader.MessageId = FrameHeader.HandshakeId; _expectedProtectionLevel = protectionLevel; _expectedImpersonationLevel = isServer ? impersonationLevel : TokenImpersonationLevel.None; _writeSequenceNumber = 0; _readSequenceNumber = 0; ContextFlagsPal flags = ContextFlagsPal.Connection; // A workaround for the client when talking to Win9x on the server side. if (protectionLevel == ProtectionLevel.None && !isServer) { package = NegotiationInfoClass.NTLM; } else if (protectionLevel == ProtectionLevel.EncryptAndSign) { flags |= ContextFlagsPal.Confidentiality; } else if (protectionLevel == ProtectionLevel.Sign) { // Assuming user expects NT4 SP4 and above. flags |= (ContextFlagsPal.ReplayDetect | ContextFlagsPal.SequenceDetect | ContextFlagsPal.InitIntegrity); } if (isServer) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { flags |= ContextFlagsPal.AllowMissingBindings; } if (_extendedProtectionPolicy.PolicyEnforcement != PolicyEnforcement.Never && _extendedProtectionPolicy.ProtectionScenario == ProtectionScenario.TrustedProxy) { flags |= ContextFlagsPal.ProxyBindings; } } else { // Server side should not request any of these flags. if (protectionLevel != ProtectionLevel.None) { flags |= ContextFlagsPal.MutualAuth; } if (impersonationLevel == TokenImpersonationLevel.Identification) { flags |= ContextFlagsPal.InitIdentify; } if (impersonationLevel == TokenImpersonationLevel.Delegation) { flags |= ContextFlagsPal.Delegate; } } _canRetryAuthentication = false; try { _context = new NTAuthentication(isServer, package, credential, servicePrincipalName, flags, channelBinding); } catch (Win32Exception e) { throw new AuthenticationException(SR.net_auth_SSPI, e); } } private Exception SetException(Exception e) { if (_exception == null || !(_exception is ObjectDisposedException)) { _exception = e; } if (_exception != null && _context != null) { _context.CloseContext(); } return _exception; } internal bool IsAuthenticated { get { return _context != null && HandshakeComplete && _exception == null && _remoteOk; } } internal bool IsMutuallyAuthenticated { get { if (!IsAuthenticated) { return false; } // Suppressing for NTLM since SSPI does not return correct value in the context flags. if (_context.IsNTLM) { return false; } return _context.IsMutualAuthFlag; } } internal bool IsEncrypted { get { return IsAuthenticated && _context.IsConfidentialityFlag; } } internal bool IsSigned { get { return IsAuthenticated && (_context.IsIntegrityFlag || _context.IsConfidentialityFlag); } } internal bool IsServer { get { return _context != null && _context.IsServer; } } internal bool CanGetSecureStream { get { return (_context.IsConfidentialityFlag || _context.IsIntegrityFlag); } } internal TokenImpersonationLevel AllowedImpersonation { get { CheckThrow(true); return PrivateImpersonationLevel; } } private TokenImpersonationLevel PrivateImpersonationLevel { get { // We should suppress the delegate flag in NTLM case. return (_context.IsDelegationFlag && _context.ProtocolName != NegotiationInfoClass.NTLM) ? TokenImpersonationLevel.Delegation : _context.IsIdentifyFlag ? TokenImpersonationLevel.Identification : TokenImpersonationLevel.Impersonation; } } private bool HandshakeComplete { get { return _context.IsCompleted && _context.IsValidContext; } } internal void CheckThrow(bool authSucessCheck) { if (_exception != null) { ExceptionDispatchInfo.Throw(_exception); } if (authSucessCheck && !IsAuthenticated) { throw new InvalidOperationException(SR.net_auth_noauth); } } // // This is to not depend on GC&SafeHandle class if the context is not needed anymore. // internal void Close() { // Mark this instance as disposed. _exception = new ObjectDisposedException("NegotiateStream"); if (_context != null) { _context.CloseContext(); } } internal void ProcessAuthentication(LazyAsyncResult lazyResult) { CheckThrow(false); if (Interlocked.Exchange(ref _nestedAuth, 1) == 1) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidnestedcall, lazyResult == null ? "BeginAuthenticate" : "Authenticate", "authenticate")); } try { if (_context.IsServer) { // Listen for a client blob. StartReceiveBlob(lazyResult); } else { // Start with the first blob. StartSendBlob(null, lazyResult); } } catch (Exception e) { // Round-trip it through SetException(). e = SetException(e); throw; } finally { if (lazyResult == null || _exception != null) { _nestedAuth = 0; } } } internal void EndProcessAuthentication(IAsyncResult result) { if (result == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = result as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedAuth, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate")); } // No "artificial" timeouts implemented so far, InnerStream controls that. lazyResult.InternalWaitForCompletion(); Exception e = lazyResult.Result as Exception; if (e != null) { // Round-trip it through the SetException(). e = SetException(e); ExceptionDispatchInfo.Throw(e); } } private bool CheckSpn() { if (_context.IsKerberos) { return true; } if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Never || _extendedProtectionPolicy.CustomServiceNames == null) { return true; } string clientSpn = _context.ClientSpecifiedSpn; if (String.IsNullOrEmpty(clientSpn)) { if (_extendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.WhenSupported) { return true; } } else { return _extendedProtectionPolicy.CustomServiceNames.Contains(clientSpn); } return false; } // // Client side starts here, but server also loops through this method. // private void StartSendBlob(byte[] message, LazyAsyncResult lazyResult) { Exception exception = null; if (message != s_emptyMessage) { message = GetOutgoingBlob(message, ref exception); } if (exception != null) { // Signal remote side on a failed attempt. StartSendAuthResetSignal(lazyResult, message, exception); return; } if (HandshakeComplete) { if (_context.IsServer && !CheckSpn()) { exception = new AuthenticationException(SR.net_auth_bad_client_creds_or_target_mismatch); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } if (PrivateImpersonationLevel < _expectedImpersonationLevel) { exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, _expectedImpersonationLevel.ToString(), PrivateImpersonationLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } ProtectionLevel result = _context.IsConfidentialityFlag ? ProtectionLevel.EncryptAndSign : _context.IsIntegrityFlag ? ProtectionLevel.Sign : ProtectionLevel.None; if (result < _expectedProtectionLevel) { exception = new AuthenticationException(SR.Format(SR.net_auth_context_expectation, result.ToString(), _expectedProtectionLevel.ToString())); int statusCode = ERROR_TRUST_FAILURE; message = new byte[8]; //sizeof(long) for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(statusCode & 0xFF); statusCode = (int)((uint)statusCode >> 8); } StartSendAuthResetSignal(lazyResult, message, exception); return; } // Signal remote party that we are done _framer.WriteHeader.MessageId = FrameHeader.HandshakeDoneId; if (_context.IsServer) { // Server may complete now because client SSPI would not complain at this point. _remoteOk = true; // However the client will wait for server to send this ACK //Force signaling server OK to the client if (message == null) { message = s_emptyMessage; } } } else if (message == null || message == s_emptyMessage) { throw new InternalException(); } if (message != null) { //even if we are completed, there could be a blob for sending. if (lazyResult == null) { _framer.WriteMessage(message); } else { IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } } CheckCompletionBeforeNextReceive(lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextReceive(LazyAsyncResult lazyResult) { if (HandshakeComplete && _remoteOk) { // We are done with success. if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } StartReceiveBlob(lazyResult); } // // Server side starts here, but client also loops through this method. // private void StartReceiveBlob(LazyAsyncResult lazyResult) { byte[] message; if (lazyResult == null) { message = _framer.ReadMessage(); } else { IAsyncResult ar = _framer.BeginReadMessage(s_readCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } message = _framer.EndReadMessage(ar); } ProcessReceivedBlob(message, lazyResult); } private void ProcessReceivedBlob(byte[] message, LazyAsyncResult lazyResult) { // This is an EOF otherwise we would get at least *empty* message but not a null one. if (message == null) { throw new AuthenticationException(SR.net_auth_eof, null); } // Process Header information. if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeErrId) { if (message.Length >= 8) // sizeof(long) { // Try to recover remote win32 Exception. long error = 0; for (int i = 0; i < 8; ++i) { error = (error << 8) + message[i]; } ThrowCredentialException(error); } throw new AuthenticationException(SR.net_auth_alert, null); } if (_framer.ReadHeader.MessageId == FrameHeader.HandshakeDoneId) { _remoteOk = true; } else if (_framer.ReadHeader.MessageId != FrameHeader.HandshakeId) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeId), null); } CheckCompletionBeforeNextSend(message, lazyResult); } // // This will check and logically complete the auth handshake. // private void CheckCompletionBeforeNextSend(byte[] message, LazyAsyncResult lazyResult) { //If we are done don't go into send. if (HandshakeComplete) { if (!_remoteOk) { throw new AuthenticationException(SR.Format(SR.net_io_header_id, "MessageId", _framer.ReadHeader.MessageId, FrameHeader.HandshakeDoneId), null); } if (lazyResult != null) { lazyResult.InvokeCallback(); } return; } // Not yet done, get a new blob and send it if any. StartSendBlob(message, lazyResult); } // // This is to reset auth state on the remote side. // If this write succeeds we will allow auth retrying. // private void StartSendAuthResetSignal(LazyAsyncResult lazyResult, byte[] message, Exception exception) { _framer.WriteHeader.MessageId = FrameHeader.HandshakeErrId; if (IsLogonDeniedException(exception)) { if (IsServer) { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds, exception); } else { exception = new InvalidCredentialException(SR.net_auth_bad_client_creds_or_target_mismatch, exception); } } if (!(exception is AuthenticationException)) { exception = new AuthenticationException(SR.net_auth_SSPI, exception); } if (lazyResult == null) { _framer.WriteMessage(message); } else { lazyResult.Result = exception; IAsyncResult ar = _framer.BeginWriteMessage(message, s_writeCallback, lazyResult); if (!ar.CompletedSynchronously) { return; } _framer.EndWriteMessage(ar); } _canRetryAuthentication = true; ExceptionDispatchInfo.Throw(exception); } private static void WriteCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is LazyAsyncResult)) { NetEventSource.Fail(transportResult, "State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; authState._framer.EndWriteMessage(transportResult); // Special case for an error notification. if (lazyResult.Result is Exception e) { authState._canRetryAuthentication = true; ExceptionDispatchInfo.Throw(e); } authState.CheckCompletionBeforeNextReceive(lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } private static void ReadCallback(IAsyncResult transportResult) { if (!(transportResult.AsyncState is LazyAsyncResult)) { NetEventSource.Fail(transportResult, "State type is wrong, expected LazyAsyncResult."); } if (transportResult.CompletedSynchronously) { return; } LazyAsyncResult lazyResult = (LazyAsyncResult)transportResult.AsyncState; // Async completion. try { NegoState authState = (NegoState)lazyResult.AsyncObject; byte[] message = authState._framer.EndReadMessage(transportResult); authState.ProcessReceivedBlob(message, lazyResult); } catch (Exception e) { if (lazyResult.InternalPeekCompleted) { // This will throw on a worker thread. throw; } lazyResult.InvokeCallback(e); } } internal static bool IsError(SecurityStatusPal status) { return ((int)status.ErrorCode >= (int)SecurityStatusPalErrorCode.OutOfMemory); } private unsafe byte[] GetOutgoingBlob(byte[] incomingBlob, ref Exception e) { SecurityStatusPal statusCode; byte[] message = _context.GetOutgoingBlob(incomingBlob, false, out statusCode); if (IsError(statusCode)) { e = NegotiateStreamPal.CreateExceptionFromError(statusCode); uint error = (uint)e.HResult; message = new byte[sizeof(long)]; for (int i = message.Length - 1; i >= 0; --i) { message[i] = (byte)(error & 0xFF); error = (error >> 8); } } if (message != null && message.Length == 0) { message = s_emptyMessage; } return message; } internal int EncryptData(byte[] buffer, int offset, int count, ref byte[] outBuffer) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_writeSequenceNumber; return _context.Encrypt(buffer, offset, count, ref outBuffer, _writeSequenceNumber); } internal int DecryptData(byte[] buffer, int offset, int count, out int newOffset) { CheckThrow(true); // SSPI seems to ignore this sequence number. ++_readSequenceNumber; return _context.Decrypt(buffer, offset, count, out newOffset, _readSequenceNumber); } internal static void ThrowCredentialException(long error) { Win32Exception e = new Win32Exception((int)error); if (e.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied) { throw new InvalidCredentialException(SR.net_auth_bad_client_creds, e); } if (e.NativeErrorCode == NegoState.ERROR_TRUST_FAILURE) { throw new AuthenticationException(SR.net_auth_context_expectation_remote, e); } throw new AuthenticationException(SR.net_auth_alert, e); } internal static bool IsLogonDeniedException(Exception exception) { Win32Exception win32exception = exception as Win32Exception; return (win32exception != null) && (win32exception.NativeErrorCode == (int)SecurityStatusPalErrorCode.LogonDenied); } } }
// // MtpSource.cs // // Author: // Gabriel Burt <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Collections; using Mtp; using MTP = Mtp; using Banshee.Base; using Banshee.Dap; using Banshee.ServiceStack; using Banshee.Library; using Banshee.Sources; using Banshee.Playlist; using Banshee.Configuration; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Hardware; namespace Banshee.Dap.Mtp { public class MtpSource : DapSource { private MtpDevice mtp_device; //private bool supports_jpegs = false; private Dictionary<long, Track> track_map; private Dictionary<string, Album> album_cache = new Dictionary<string, Album> (); private bool supports_jpegs = false; private bool can_sync_albumart = NeverSyncAlbumArtSchema.Get () == false; private int thumb_width = AlbumArtWidthSchema.Get (); public override void DeviceInitialize (IDevice device) { base.DeviceInitialize (device); var portInfo = device.ResolveUsbPortInfo (); if (portInfo == null || portInfo.DeviceNumber == 0) { throw new InvalidDeviceException (); } //int busnum = portInfo.BusNumber; int devnum = portInfo.DeviceNumber; List<RawMtpDevice> devices = null; try { devices = MtpDevice.Detect (); } catch (TypeInitializationException e) { Log.Exception (e); Log.Error ( Catalog.GetString ("Error Initializing MTP Device Support"), Catalog.GetString ("There was an error initializing MTP device support."), true ); throw new InvalidDeviceException (); } catch (Exception e) { Log.Exception (e); //ShowGeneralExceptionDialog (e); throw new InvalidDeviceException (); } IVolume volume = device as IVolume; foreach (var v in devices) { // Using the HAL hardware backend, HAL says the busnum is 2, but libmtp says it's 0, so disabling that check //if (v.BusNumber == busnum && v.DeviceNumber == devnum) { if (v.DeviceNumber == devnum) { // If gvfs-gphoto has it mounted, unmount it if (volume != null && volume.IsMounted) { volume.Unmount (); } for (int i = 5; i > 0 && mtp_device == null; i--) { try { mtp_device = MtpDevice.Connect (v); } catch (Exception) {} if (mtp_device == null) { Log.DebugFormat ("Failed to connect to mtp device. Trying {0} more times...", i - 1); Thread.Sleep (2000); } } } } if (mtp_device == null) { throw new InvalidDeviceException (); } // libmtp sometimes returns '?????'. I assume this is if the device does // not supply a friendly name. In this case show the model name. if (string.IsNullOrEmpty (mtp_device.Name) || mtp_device.Name == "?????") Name = mtp_device.ModelName; else Name = mtp_device.Name; Initialize (); List<string> mimetypes = new List<string> (); foreach (FileType format in mtp_device.GetFileTypes ()) { if (format == FileType.JPEG) { supports_jpegs = true; } else { string mimetype = MtpDevice.GetMimeTypeFor (format); if (mimetype != null) { mimetypes.Add (mimetype); } } } AcceptableMimeTypes = mimetypes.ToArray (); AddDapProperty (Catalog.GetString ("Serial number"), mtp_device.SerialNumber); AddDapProperty (Catalog.GetString ("Version"), mtp_device.Version); try { AddDapProperty (Catalog.GetString ("Battery level"), String.Format ("{0:0%}", mtp_device.BatteryLevel/100.0)); } catch (Exception e) { Log.Exception ("Unable to get battery level from MTP device", e); } } protected override void LoadFromDevice () { track_map = new Dictionary<long, Track> (); try { List<Track> files = null; lock (mtp_device) { files = mtp_device.GetAllTracks (delegate (ulong current, ulong total, IntPtr data) { //user_event.Progress = (double)current / total; // Translators: {0} is the name of the MTP audio device (eg Gabe's Zen Player), {1} is the // track currently being loaded, and {2} is the total # of tracks that will be loaded. SetStatus (String.Format (Catalog.GetString ("Loading {0} - {1} of {2}"), Name, current, total), false); return 0; }); } /*if (user_event.IsCancelRequested) { return; }*/ // Delete any empty albums lock (mtp_device) { foreach (Album album in mtp_device.GetAlbums ()) { if (album.Count == 0) { album.Remove (); } } } foreach (Track mtp_track in files) { long track_id; if ((track_id = DatabaseTrackInfo.GetTrackIdForUri (MtpTrackInfo.GetPathFromMtpTrack (mtp_track), DbId )) > 0) { track_map[track_id] = mtp_track; } else { MtpTrackInfo track = new MtpTrackInfo (mtp_device, mtp_track); track.PrimarySource = this; track.Save (false); track_map[track.TrackId] = mtp_track; } } Hyena.Data.Sqlite.HyenaSqliteCommand insert_cmd = new Hyena.Data.Sqlite.HyenaSqliteCommand ( @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) SELECT ?, TrackID FROM CoreTracks WHERE PrimarySourceID = ? AND ExternalID = ?"); lock (mtp_device) { var playlists = mtp_device.GetPlaylists (); if (playlists != null) { foreach (MTP.Playlist playlist in playlists) { PlaylistSource pl_src = new PlaylistSource (playlist.Name, this); pl_src.Save (); // TODO a transaction would make sense here (when the threading issue is fixed) foreach (uint id in playlist.TrackIds) { ServiceManager.DbConnection.Execute (insert_cmd, pl_src.DbId, this.DbId, id); } pl_src.UpdateCounts (); AddChildSource (pl_src); } } } } catch (Exception e) { Log.Exception (e); } OnTracksAdded (); } public override void Import () { Log.Information ("Import to Library is not implemented for MTP devices yet", true); //new LibraryImportManager (true).QueueSource (BaseDirectory); } public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, BatchUserJob job) { if (track_map.ContainsKey (track.TrackId)) { track_map[track.TrackId].Download (uri.LocalPath, delegate (ulong current, ulong total, IntPtr data) { job.DetailedProgress = (double) current / total; return 0; }); } else { throw new Exception ("Error copying track from MTP device"); } } public override void SyncPlaylists () { lock (mtp_device) { List<MTP.Playlist> device_playlists = new List<MTP.Playlist> (mtp_device.GetPlaylists ()); foreach (MTP.Playlist playlist in device_playlists) { playlist.Remove (); } device_playlists.Clear (); // Add playlists from Banshee to the device List<Source> children = new List<Source> (Children); foreach (Source child in children) { PlaylistSource from = child as PlaylistSource; if (from != null && from.Count > 0) { MTP.Playlist playlist = new MTP.Playlist (mtp_device, from.Name); foreach (uint track_id in ServiceManager.DbConnection.QueryEnumerable<uint> (String.Format ( "SELECT CoreTracks.ExternalID FROM {0} WHERE {1}", from.DatabaseTrackModel.ConditionFromFragment, from.DatabaseTrackModel.Condition))) { playlist.AddTrack (track_id); } playlist.Save (); } } } } public override bool CanRename { get { return !(IsAdding || IsDeleting); } } private SafeUri empty_file = new SafeUri (Paths.Combine (Paths.ApplicationCache, "mtp.mp3")); protected override void OnTracksDeleted () { // Hack to get the disk usage indicate to be accurate, which seems to // only be updated when tracks are added, not removed. try { lock (mtp_device) { using (System.IO.TextWriter writer = new System.IO.StreamWriter (Banshee.IO.File.OpenWrite (empty_file, true))) { writer.Write ("foo"); } Track mtp_track = new Track (System.IO.Path.GetFileName (empty_file.LocalPath), 3); mtp_device.UploadTrack (empty_file.AbsolutePath, mtp_track, mtp_device.MusicFolder); mtp_device.Remove (mtp_track); Banshee.IO.File.Delete (empty_file); } } catch {} base.OnTracksDeleted (); } public override void Rename (string newName) { base.Rename (newName); lock (mtp_device) { mtp_device.Name = newName; } } private long bytes_used; public override long BytesUsed { get { if (mtp_device != null && Monitor.TryEnter (mtp_device)) { try { bytes_used = 0; foreach (DeviceStorage s in mtp_device.GetStorage ()) { bytes_used += (long) s.MaxCapacity - (long) s.FreeSpaceInBytes; } } finally { Monitor.Exit (mtp_device); } } return bytes_used; } } private long bytes_capacity; public override long BytesCapacity { get { if (Monitor.TryEnter (mtp_device)) { try { bytes_capacity = 0; foreach (DeviceStorage s in mtp_device.GetStorage ()) { bytes_capacity += (long) s.MaxCapacity; } } finally { Monitor.Exit (mtp_device); } } return bytes_capacity; } } public override bool IsReadOnly { get { return false; } } protected override void AddTrackToDevice (DatabaseTrackInfo track, SafeUri fromUri) { if (track.PrimarySourceId == DbId) return; lock (mtp_device) { Track mtp_track = TrackInfoToMtpTrack (track, fromUri); bool video = track.HasAttribute (TrackMediaAttributes.VideoStream); mtp_device.UploadTrack (fromUri.LocalPath, mtp_track, GetFolderForTrack (track), OnUploadProgress); // Add/update album art if (!video) { string key = MakeAlbumKey (track.AlbumArtist, track.AlbumTitle); if (!album_cache.ContainsKey (key)) { // LIBMTP 1.0.3 BUG WORKAROUND // In libmtp.c the 'LIBMTP_Create_New_Album' function invokes 'create_new_abstract_list'. // The latter calls strlen on the 'name' parameter without null checking. If AlbumTitle is // null, this causes a sigsegv. Lets be safe and always pass non-null values. Album album = new Album (mtp_device, track.AlbumTitle ?? "", track.AlbumArtist ?? "", track.Genre ?? "", track.Composer ?? ""); album.AddTrack (mtp_track); if (supports_jpegs && can_sync_albumart) { try { Gdk.Pixbuf pic = ServiceManager.Get<Banshee.Collection.Gui.ArtworkManager> ().LookupScalePixbuf ( track.ArtworkId, thumb_width ); if (pic != null) { byte [] bytes = pic.SaveToBuffer ("jpeg"); album.Save (bytes, (uint)pic.Width, (uint)pic.Height); Banshee.Collection.Gui.ArtworkManager.DisposePixbuf (pic); } album_cache[key] = album; } catch (Exception e) { Log.Debug ("Failed to create MTP Album", e.Message); } } else { album.Save (); album_cache[key] = album; } } else { Album album = album_cache[key]; album.AddTrack (mtp_track); album.Save (); } } MtpTrackInfo new_track = new MtpTrackInfo (mtp_device, mtp_track); new_track.PrimarySource = this; new_track.Save (false); track_map[new_track.TrackId] = mtp_track; } } private Folder GetFolderForTrack (TrackInfo track) { if (track.HasAttribute (TrackMediaAttributes.VideoStream)) { return mtp_device.VideoFolder; } else if (track.HasAttribute (TrackMediaAttributes.Podcast)) { return mtp_device.PodcastFolder; } else { return mtp_device.MusicFolder; } } private int OnUploadProgress (ulong sent, ulong total, IntPtr data) { AddTrackJob.DetailedProgress = (double) sent / (double) total; return 0; } protected override bool DeleteTrack (DatabaseTrackInfo track) { lock (mtp_device) { Track mtp_track = track_map [track.TrackId]; track_map.Remove (track.TrackId); // Remove from device mtp_device.Remove (mtp_track); // Remove track from album, and remove album from device if it no longer has tracks string key = MakeAlbumKey (track.ArtistName, track.AlbumTitle); if (album_cache.ContainsKey (key)) { Album album = album_cache[key]; album.RemoveTrack (mtp_track); if (album.Count == 0) { album.Remove (); album_cache.Remove (key); } } return true; } } public Track TrackInfoToMtpTrack (TrackInfo track, SafeUri fromUri) { Track f = new Track (System.IO.Path.GetFileName (fromUri.LocalPath), (ulong) Banshee.IO.File.GetSize (fromUri)); MtpTrackInfo.ToMtpTrack (track, f); return f; } private bool disposed = false; public override void Dispose () { if (disposed) return; disposed = true; base.Dispose (); if (mtp_device != null) { lock (mtp_device) { mtp_device.Dispose (); } } ServiceManager.SourceManager.RemoveSource (this); mtp_device = null; } protected override void Eject () { base.Eject (); Dispose (); } private static string MakeAlbumKey (string album_artist, string album) { return String.Format ("{0}_{1}", album_artist, album); } public static readonly SchemaEntry<bool> NeverSyncAlbumArtSchema = new SchemaEntry<bool>( "plugins.mtp", "never_sync_albumart", false, "Album art disabled", "Regardless of device's capabilities, do not sync album art" ); public static readonly SchemaEntry<int> AlbumArtWidthSchema = new SchemaEntry<int>( "plugins.mtp", "albumart_max_width", 170, "Album art max width", "The maximum width to allow for album art." ); } }
/* * Copyright 2011-2012 Paul Heasley * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using phdesign.NppToolBucket.Utilities; namespace phdesign.NppToolBucket.PluginCore { internal class Editor : PluginBase { #region Constants private const int IndicatorMatch = 31; private const int BookmarkMarker = 24; #endregion #region Fields private readonly IntPtr _activeScintilla; #endregion #region Constructor private Editor(IntPtr activeScintilla) { _activeScintilla = activeScintilla; } #endregion #region Public Static Accessor Method public static Editor GetActive() { return new Editor(GetCurrentScintilla()); } #endregion #region Private Call Methods private int Call(SciMsg msg, int wParam, IntPtr lParam) { return (int)Win32.SendMessage(_activeScintilla, msg, wParam, lParam); } private int Call(SciMsg msg, int wParam, string lParam) { return (int)Win32.SendMessage(_activeScintilla, msg, wParam, lParam); } private int Call(SciMsg msg, int wParam, StringBuilder lParam) { return (int)Win32.SendMessage(_activeScintilla, msg, wParam, lParam); } private int Call(SciMsg msg, int wParam, int lParam) { return (int)Win32.SendMessage(_activeScintilla, msg, wParam, lParam); } private int Call(SciMsg msg, int wParam) { return Call(msg, wParam, 0); } private int Call(SciMsg msg) { return Call(msg, 0, 0); } #endregion #region Public Methods /// <summary> /// Returns the text between the positions start and end. If end is -1, text is returned to the end of the document. /// The text is 0 terminated, so you must supply a buffer that is at least 1 character longer than the number of characters /// you wish to read. The return value is the length of the returned text not including the terminating 0. /// </summary> public string GetTextByRange(int start, int end) { return GetTextByRange(start, end, end - start); } /// <summary> /// Returns the text between the positions start and end. If end is -1, text is returned to the end of the document. /// The text is 0 terminated, so you must supply a buffer that is at least 1 character longer than the number of characters /// you wish to read. The return value is the length of the returned text not including the terminating 0. /// </summary> public string GetTextByRange(int start, int end, int bufCapacity) { using (var textRange = new Sci_TextRange(start, end, bufCapacity)) { Call(SciMsg.SCI_GETTEXTRANGE, 0, textRange.NativePointer); //return textRange.lpstrText; return IsUnicode() ? StringUtils.AnsiToUnicode(textRange.lpstrText) : textRange.lpstrText; } } /// <summary> /// Replaces the current selected target range of text. /// </summary> /// <param name="text">The replacement text.</param> /// <param name="useRegularExpression">If true, uses a regular expressions replacement.</param> /// <returns> The length of the replacement string.</returns> public int ReplaceText(string text, bool useRegularExpression) { if (IsUnicode()) text = StringUtils.UnicodeToAnsi(text); return Call(useRegularExpression ? SciMsg.SCI_REPLACETARGETRE : SciMsg.SCI_REPLACETARGET, text.Length, text); } /// <summary> /// Replaces a range of text with new text. /// Note that the recommended way to delete text in the document is to set the target to the text to be removed, and to /// perform a replace target with an empty string. /// </summary> /// <returns> The length of the replacement string.</returns> public int ReplaceText(int start, int end, string text) { SetTargetRange(start, end); if (IsUnicode()) text = StringUtils.UnicodeToAnsi(text); // If length is -1, text is a zero terminated string, otherwise length sets the number of character to replace // the target with. After replacement, the target range refers to the replacement text. The return value is the // length of the replacement string. return Call(SciMsg.SCI_REPLACETARGET, text.Length, text); } /// <summary> /// Returns true if the current document is displaying in unicode format or false for ANSI. /// Note that all strings marshaled to and from Scintilla come in ANSI format so need to /// be converted if using Unicode. /// </summary> public bool IsUnicode() { var result = Call(SciMsg.SCI_GETCODEPAGE); return result == (int)SciMsg.SC_CP_UTF8; } /// <summary> /// Size in bytes of the selection. /// </summary> public int GetSelectionLength() { return Call(SciMsg.SCI_GETSELTEXT); } /// <summary> /// Returns the text currently selected (highlighted). /// </summary> /// <returns>Currently selected text.</returns> public string GetSelectedText() { var selLength = GetSelectionLength(); // Todo: Use a string / char array as stringbuilder can't handle null characters? var selectedText = new StringBuilder(selLength); if (selLength > 0) Call(SciMsg.SCI_GETSELTEXT, 0, selectedText); var ret = selectedText.ToString(); return IsUnicode() ? StringUtils.AnsiToUnicode(ret) : ret; } /// <summary> /// Gets the selected text or if nothing is selected, gets whole document text. /// </summary> /// <returns>Selected or whole document text.</returns> public string GetSelectedOrAllText() { var selectedText = GetSelectedText(); return string.IsNullOrEmpty(selectedText) ? GetDocumentText() : selectedText; } /// <summary> /// The currently selected text is replaced with text. If no text is selected the /// text is inserted at current cursor postion. /// </summary> /// <param name="text">The document text to set.</param> public void SetSelectedText(string text) { if (IsUnicode()) text = StringUtils.UnicodeToAnsi(text); Call(SciMsg.SCI_REPLACESEL, 0, text); } /// <summary> /// Sets the text for the entire document (replacing any existing text). /// </summary> /// <param name="text">The document text to set.</param> public void SetDocumentText(string text) { if (IsUnicode()) text = StringUtils.UnicodeToAnsi(text); Call(SciMsg.SCI_SETTEXT, 0, text); } /// <summary> /// Gets the entire document text. /// </summary> public string GetDocumentText() { var length = GetDocumentLength(); var text = new StringBuilder(length + 1); if (length > 0) Call(SciMsg.SCI_GETTEXT, length + 1, text); var ret = text.ToString(); return IsUnicode() ? StringUtils.AnsiToUnicode(ret) : ret; } /// <summary> /// Add a bookmark at a specific line. /// </summary> /// <param name="lineNumber">The line number to add a bookmark to.</param> public void AddBookmark(int lineNumber) { if (lineNumber == -1) lineNumber = GetCurrentLineNumber(); if (!IsBookmarkPresent(lineNumber)) Call(SciMsg.SCI_MARKERADD, lineNumber, BookmarkMarker); } /// <summary> /// Remove all bookmarks from the document. /// </summary> public void RemoveAllBookmarks() { Call(SciMsg.SCI_MARKERDELETEALL, BookmarkMarker); } /// <summary> /// Is there a bookmark set on a line. /// </summary> /// <param name="lineNumber">The line number to check.</param> /// <returns>True if a bookmark is set.</returns> public bool IsBookmarkPresent(int lineNumber) { if (lineNumber == -1) lineNumber = GetCurrentLineNumber(); var state = Call(SciMsg.SCI_MARKERGET, lineNumber); return (state & (1 << BookmarkMarker)) != 0; } /// <summary> /// Get the line number that the cursor is on. /// </summary> public int GetCurrentLineNumber() { var currentPos = Call(SciMsg.SCI_GETCURRENTPOS); return Call(SciMsg.SCI_LINEFROMPOSITION, currentPos, 0); } /// <summary> /// Remove all 'find' marks. /// </summary> public void RemoveFindMarks() { Call(SciMsg.SCI_SETINDICATORCURRENT, IndicatorMatch); Call(SciMsg.SCI_INDICATORCLEARRANGE, 0, GetDocumentLength()); } /// <summary> /// Marks a range of text. /// </summary> public void AddFindMark(int pos, int length) { Call(SciMsg.SCI_INDICATORFILLRANGE, pos, length); } /// <summary> /// Returns the start and end of the selection without regard to which end is the current position and which is the anchor. /// SCI_GETSELECTIONSTART returns the smaller of the current position or the anchor position. /// </summary> /// <returns>A character range.</returns> public Sci_CharacterRange GetSelectionRange() { return new Sci_CharacterRange( Call(SciMsg.SCI_GETSELECTIONSTART), Call(SciMsg.SCI_GETSELECTIONEND)); } /// <summary> /// Returns the current target start and end positions from a previous operation. /// </summary> public Sci_CharacterRange GetTargetRange() { return new Sci_CharacterRange( Call(SciMsg.SCI_GETTARGETSTART), Call(SciMsg.SCI_GETTARGETEND)); } /// <summary> /// Sets the start and end positions for an upcoming operation. /// </summary> public void SetTargetRange(int start, int end) { Call(SciMsg.SCI_SETTARGETSTART, start); Call(SciMsg.SCI_SETTARGETEND, end); } /// <summary> /// Returns the length of the document in bytes. /// </summary> public int GetDocumentLength() { return Call(SciMsg.SCI_GETLENGTH); } /// <summary> /// Sets both the anchor and the current position. If end is negative, it means the end of the document. /// If start is negative, it means remove any selection (i.e. set the start to the same position as end). /// The caret is scrolled into view after this operation. /// </summary> /// <param name="start">The selection start (anchor) position.</param> /// <param name="end">The selection end (current) position.</param> public void SetSelection(int start, int end) { Call(SciMsg.SCI_SETSEL, start, end); } /// <summary> /// Make a range visible by scrolling to the last line of the range. /// A line may be hidden because more than one of its parent lines is contracted. Both these message travels up the /// fold hierarchy, expanding any contracted folds until they reach the top level. The line will then be visible. /// </summary> public void EnsureRangeVisible(int start, int end) { var lineStart = Call(SciMsg.SCI_LINEFROMPOSITION, Math.Min(start, end)); var lineEnd = Call(SciMsg.SCI_LINEFROMPOSITION, Math.Max(start, end)); for (var line = lineStart; line <= lineEnd; line++) { Call(SciMsg.SCI_ENSUREVISIBLE, line); } } /// <summary> /// This searches for the first occurrence of a text string in the target defined by startPosition and endPosition. /// The text string is not zero terminated; the size is set by length. /// The search is modified by the search flags set by SCI_SETSEARCHFLAGS. /// If the search succeeds, the target is set to the found text and the return value is the position of the start /// of the matching text. If the search fails, the result is -1. /// </summary> /// <param name="findText">String to search for.</param> /// <param name="startPosition">Where to start searching from.</param> /// <param name="endPosition">Where to stop searching.</param> /// <returns>-1 if no match is found, otherwise the position (relative to start) of the first match.</returns> public int FindInTarget(string findText, int startPosition, int endPosition) { SetTargetRange(startPosition, endPosition); if (IsUnicode()) findText = StringUtils.UnicodeToAnsi(findText); return Call(SciMsg.SCI_SEARCHINTARGET, findText.Length, findText); } /// <summary> /// Gets the size of a tab as a multiple of the size of a space character in STYLE_DEFAULT. The default tab width is 8 characters. /// There are no limits on tab sizes, but values less than 1 or large values may have undesirable effects. /// </summary> public int GetTabWidth() { return Call(SciMsg.SCI_GETTABWIDTH); } /// <summary> /// Gets the size of indentation in terms of the width of a space in STYLE_DEFAULT. If you set a width of 0, /// the indent size is the same as the tab size. There are no limits on indent sizes, but values less than 0 or /// large values may have undesirable effects. /// </summary> public int GetIndent() { return Call(SciMsg.SCI_GETINDENT); } /// <summary> /// Determines whether indentation should be created out of a mixture of tabs and spaces or be based purely on spaces. /// Set useTabs to false (0) to create all tabs and indents out of spaces. The default is true. /// You can use SCI_GETCOLUMN to get the column of a position taking the width of a tab into account. /// </summary> public int GetUseTabs() { return Call(SciMsg.SCI_GETUSETABS); } /// <summary> /// Sets the size of a tab as a multiple of the size of a space character in STYLE_DEFAULT. The default tab width is 8 characters. /// There are no limits on tab sizes, but values less than 1 or large values may have undesirable effects. /// </summary> /// <param name="tabSize"></param> public void SetTabWidth(int tabSize) { Call(SciMsg.SCI_SETTABWIDTH, tabSize); } /// <summary> /// Sets the size of indentation in terms of the width of a space in STYLE_DEFAULT. If you set a width of 0, /// the indent size is the same as the tab size. There are no limits on indent sizes, but values less than 0 or /// large values may have undesirable effects. /// </summary> public void SetIndent(int indentSize) { Call(SciMsg.SCI_SETINDENT, indentSize); } /// <summary> /// Determines whether indentation should be created out of a mixture of tabs and spaces or be based purely on spaces. /// Set useTabs to false (0) to create all tabs and indents out of spaces. The default is true. /// You can use SCI_GETCOLUMN to get the column of a position taking the width of a tab into account. /// </summary> public void SetUseTabs(bool useTabs) { Call(SciMsg.SCI_SETUSETABS, useTabs ? 1 : 0); } /// <summary> /// Mark the beginning of a set of operations that you want to undo all as one operation but that you have to generate /// as several operations. Alternatively, you can use these to mark a set of operations that you do not want to have /// combined with the preceding or following operations if they are undone. /// </summary> public void BeginUndoAction() { Call(SciMsg.SCI_BEGINUNDOACTION); } /// <summary> /// Mark the end of a set of operations that you want to undo all as one operation but that you have to generate /// as several operations. Alternatively, you can use these to mark a set of operations that you do not want to have /// combined with the preceding or following operations if they are undone. /// </summary> public void EndUndoAction() { Call(SciMsg.SCI_ENDUNDOACTION); } /// <summary> /// This returns the number of lines in the document. An empty document contains 1 line. A document holding only an /// end of line sequence has 2 lines. /// </summary> public int GetLineCount() { return Call(SciMsg.SCI_GETLINECOUNT); } /// <summary> /// This returns the document position that corresponds with the start of the line. If line is negative, /// the position of the line holding the start of the selection is returned. If line is greater than the /// lines in the document, the return value is -1. If line is equal to the number of lines in the document /// (i.e. 1 line past the last line), the return value is the end of the document. /// </summary> public int PositionFromLine(int line) { return Call(SciMsg.SCI_POSITIONFROMLINE, line); } /// <summary> /// Returns the line that contains the position pos in the document. The return value is 0 if pos &lt;= 0. /// The return value is the last line if pos is beyond the end of the document. /// </summary> public int LineFromPosition(int pos) { return Call(SciMsg.SCI_LINEFROMPOSITION, pos); } /// <summary> /// Returns the amount of indentation on a line. The indentation is measured in character columns, which correspond to /// the width of space characters. /// </summary> public int GetLineIndentation(int line) { return Call(SciMsg.SCI_GETLINEINDENTATION, line); } /// <summary> /// This returns the position at the end of indentation of a line. /// </summary> /// <param name="line"></param> /// <returns></returns> public int GetLineIndentPosition(int line) { return Call(SciMsg.SCI_GETLINEINDENTPOSITION, line); } public void SetSearchFlags(bool matchWholeWord, bool matchCase, bool useRegularExpression, bool usePosixRegularExpressions) { var searchFlags = (matchWholeWord ? (int)SciMsg.SCFIND_WHOLEWORD : 0) | (matchCase ? (int)SciMsg.SCFIND_MATCHCASE : 0) | (useRegularExpression ? (int)SciMsg.SCFIND_REGEXP : 0) | (usePosixRegularExpressions ? (int)SciMsg.SCFIND_POSIX : 0); Call(SciMsg.SCI_SETSEARCHFLAGS, searchFlags); } /// <summary> /// This returns the character at pos in the document or 0 if pos is negative or past the end of the document. /// </summary> public char GetCharAt(int pos) { var bytes = new List<byte>(); // PositionAfter helps detect high Unicode characters, get up to 2 more bytes var end = Math.Min(PositionAfter(pos), pos + 2); for (var i = pos; i < end; i++) { bytes.Add((byte)Call(SciMsg.SCI_GETCHARAT, i)); } return IsUnicode() ? Encoding.UTF8.GetChars(bytes.ToArray())[0] : Encoding.Default.GetChars(bytes.ToArray())[0]; } /// <summary> /// return the position after another position in the document taking into account the current code page. /// The maximum is the last position in the document. If called with a position within a multi byte character will /// return the position of the end of that character. /// </summary> public int PositionAfter(int pos) { return Call(SciMsg.SCI_POSITIONAFTER, pos); } #endregion } }
// // 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.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Resources { /// <summary> /// Operations for managing deployment operations. /// </summary> internal partial class DeploymentOperationOperations : IServiceOperations<ResourceManagementClient>, IDeploymentOperationOperations { /// <summary> /// Initializes a new instance of the DeploymentOperationOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeploymentOperationOperations(ResourceManagementClient client) { this._client = client; } private ResourceManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Resources.ResourceManagementClient. /// </summary> public ResourceManagementClient Client { get { return this._client; } } /// <summary> /// Get a list of deployments operations. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='operationId'> /// Required. Operation Id. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Deployment operation. /// </returns> public async Task<DeploymentOperationsGetResult> GetAsync(string resourceGroupName, string deploymentName, string operationId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (operationId == null) { throw new ArgumentNullException("operationId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("operationId", operationId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/operations/"; url = url + Uri.EscapeDataString(operationId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-02-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.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 DeploymentOperationsGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DeploymentOperationsGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { DeploymentOperation operationInstance = new DeploymentOperation(); result.Operation = operationInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); operationInstance.Id = idInstance; } JToken operationIdValue = responseDoc["operationId"]; if (operationIdValue != null && operationIdValue.Type != JTokenType.Null) { string operationIdInstance = ((string)operationIdValue); operationInstance.OperationId = operationIdInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties(); operationInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken timestampValue = propertiesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); propertiesInstance.Timestamp = timestampInstance; } JToken serviceRequestIdValue = propertiesValue["serviceRequestId"]; if (serviceRequestIdValue != null && serviceRequestIdValue.Type != JTokenType.Null) { string serviceRequestIdInstance = ((string)serviceRequestIdValue); propertiesInstance.ServiceRequestId = serviceRequestIdInstance; } JToken statusCodeValue = propertiesValue["statusCode"]; if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null) { string statusCodeInstance = ((string)statusCodeValue); propertiesInstance.StatusCode = statusCodeInstance; } JToken statusMessageValue = propertiesValue["statusMessage"]; if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null) { string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.StatusMessage = statusMessageInstance; } JToken targetResourceValue = propertiesValue["targetResource"]; if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null) { TargetResource targetResourceInstance = new TargetResource(); propertiesInstance.TargetResource = targetResourceInstance; JToken idValue2 = targetResourceValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); targetResourceInstance.Id = idInstance2; } JToken resourceNameValue = targetResourceValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); targetResourceInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = targetResourceValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); targetResourceInstance.ResourceType = resourceTypeInstance; } } JToken requestValue = propertiesValue["request"]; if (requestValue != null && requestValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage requestInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Request = requestInstance; JToken contentValue = requestValue["content"]; if (contentValue != null && contentValue.Type != JTokenType.Null) { string contentInstance = contentValue.ToString(Newtonsoft.Json.Formatting.Indented); requestInstance.Content = contentInstance; } } JToken responseValue = propertiesValue["response"]; if (responseValue != null && responseValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage responseInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Response = responseInstance; JToken contentValue2 = responseValue["content"]; if (contentValue2 != null && contentValue2.Type != JTokenType.Null) { string contentInstance2 = contentValue2.ToString(Newtonsoft.Json.Formatting.Indented); responseInstance.Content = contentInstance2; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a list of deployments operations. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Optional. Query parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of deployment operations. /// </returns> public async Task<DeploymentOperationsListResult> ListAsync(string resourceGroupName, string deploymentName, DeploymentOperationsListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourcegroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/operations"; List<string> queryParameters = new List<string>(); if (parameters != null && parameters.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString())); } queryParameters.Add("api-version=2016-02-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.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 DeploymentOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DeploymentOperationsListResult(); 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)) { DeploymentOperation deploymentOperationInstance = new DeploymentOperation(); result.Operations.Add(deploymentOperationInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); deploymentOperationInstance.Id = idInstance; } JToken operationIdValue = valueValue["operationId"]; if (operationIdValue != null && operationIdValue.Type != JTokenType.Null) { string operationIdInstance = ((string)operationIdValue); deploymentOperationInstance.OperationId = operationIdInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties(); deploymentOperationInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken timestampValue = propertiesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); propertiesInstance.Timestamp = timestampInstance; } JToken serviceRequestIdValue = propertiesValue["serviceRequestId"]; if (serviceRequestIdValue != null && serviceRequestIdValue.Type != JTokenType.Null) { string serviceRequestIdInstance = ((string)serviceRequestIdValue); propertiesInstance.ServiceRequestId = serviceRequestIdInstance; } JToken statusCodeValue = propertiesValue["statusCode"]; if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null) { string statusCodeInstance = ((string)statusCodeValue); propertiesInstance.StatusCode = statusCodeInstance; } JToken statusMessageValue = propertiesValue["statusMessage"]; if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null) { string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.StatusMessage = statusMessageInstance; } JToken targetResourceValue = propertiesValue["targetResource"]; if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null) { TargetResource targetResourceInstance = new TargetResource(); propertiesInstance.TargetResource = targetResourceInstance; JToken idValue2 = targetResourceValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); targetResourceInstance.Id = idInstance2; } JToken resourceNameValue = targetResourceValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); targetResourceInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = targetResourceValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); targetResourceInstance.ResourceType = resourceTypeInstance; } } JToken requestValue = propertiesValue["request"]; if (requestValue != null && requestValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage requestInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Request = requestInstance; JToken contentValue = requestValue["content"]; if (contentValue != null && contentValue.Type != JTokenType.Null) { string contentInstance = contentValue.ToString(Newtonsoft.Json.Formatting.Indented); requestInstance.Content = contentInstance; } } JToken responseValue = propertiesValue["response"]; if (responseValue != null && responseValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage responseInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Response = responseInstance; JToken contentValue2 = responseValue["content"]; if (contentValue2 != null && contentValue2.Type != JTokenType.Null) { string contentInstance2 = contentValue2.ToString(Newtonsoft.Json.Formatting.Indented); responseInstance.Content = contentInstance2; } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets a next list of deployments operations. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of deployment operations. /// </returns> public async Task<DeploymentOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + nextLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // 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 DeploymentOperationsListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new DeploymentOperationsListResult(); 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)) { DeploymentOperation deploymentOperationInstance = new DeploymentOperation(); result.Operations.Add(deploymentOperationInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); deploymentOperationInstance.Id = idInstance; } JToken operationIdValue = valueValue["operationId"]; if (operationIdValue != null && operationIdValue.Type != JTokenType.Null) { string operationIdInstance = ((string)operationIdValue); deploymentOperationInstance.OperationId = operationIdInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { DeploymentOperationProperties propertiesInstance = new DeploymentOperationProperties(); deploymentOperationInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken timestampValue = propertiesValue["timestamp"]; if (timestampValue != null && timestampValue.Type != JTokenType.Null) { DateTime timestampInstance = ((DateTime)timestampValue); propertiesInstance.Timestamp = timestampInstance; } JToken serviceRequestIdValue = propertiesValue["serviceRequestId"]; if (serviceRequestIdValue != null && serviceRequestIdValue.Type != JTokenType.Null) { string serviceRequestIdInstance = ((string)serviceRequestIdValue); propertiesInstance.ServiceRequestId = serviceRequestIdInstance; } JToken statusCodeValue = propertiesValue["statusCode"]; if (statusCodeValue != null && statusCodeValue.Type != JTokenType.Null) { string statusCodeInstance = ((string)statusCodeValue); propertiesInstance.StatusCode = statusCodeInstance; } JToken statusMessageValue = propertiesValue["statusMessage"]; if (statusMessageValue != null && statusMessageValue.Type != JTokenType.Null) { string statusMessageInstance = statusMessageValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.StatusMessage = statusMessageInstance; } JToken targetResourceValue = propertiesValue["targetResource"]; if (targetResourceValue != null && targetResourceValue.Type != JTokenType.Null) { TargetResource targetResourceInstance = new TargetResource(); propertiesInstance.TargetResource = targetResourceInstance; JToken idValue2 = targetResourceValue["id"]; if (idValue2 != null && idValue2.Type != JTokenType.Null) { string idInstance2 = ((string)idValue2); targetResourceInstance.Id = idInstance2; } JToken resourceNameValue = targetResourceValue["resourceName"]; if (resourceNameValue != null && resourceNameValue.Type != JTokenType.Null) { string resourceNameInstance = ((string)resourceNameValue); targetResourceInstance.ResourceName = resourceNameInstance; } JToken resourceTypeValue = targetResourceValue["resourceType"]; if (resourceTypeValue != null && resourceTypeValue.Type != JTokenType.Null) { string resourceTypeInstance = ((string)resourceTypeValue); targetResourceInstance.ResourceType = resourceTypeInstance; } } JToken requestValue = propertiesValue["request"]; if (requestValue != null && requestValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage requestInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Request = requestInstance; JToken contentValue = requestValue["content"]; if (contentValue != null && contentValue.Type != JTokenType.Null) { string contentInstance = contentValue.ToString(Newtonsoft.Json.Formatting.Indented); requestInstance.Content = contentInstance; } } JToken responseValue = propertiesValue["response"]; if (responseValue != null && responseValue.Type != JTokenType.Null) { DeploymentOperationHttpMessage responseInstance = new DeploymentOperationHttpMessage(); propertiesInstance.Response = responseInstance; JToken contentValue2 = responseValue["content"]; if (contentValue2 != null && contentValue2.Type != JTokenType.Null) { string contentInstance2 = contentValue2.ToString(Newtonsoft.Json.Formatting.Indented); responseInstance.Content = contentInstance2; } } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Lucene.Net.Attributes; using Lucene.Net.Documents; namespace Lucene.Net.Index { using Lucene.Net.Randomized.Generators; using Lucene.Net.Support; using NUnit.Framework; using AlreadyClosedException = Lucene.Net.Store.AlreadyClosedException; using BytesRef = Lucene.Net.Util.BytesRef; using Codec = Lucene.Net.Codecs.Codec; using Directory = Lucene.Net.Store.Directory; using DocIdSetIterator = Lucene.Net.Search.DocIdSetIterator; using Document = Documents.Document; using FakeIOException = Lucene.Net.Store.MockDirectoryWrapper.FakeIOException; using Field = Field; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using InfoStream = Lucene.Net.Util.InfoStream; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; /* /// Copyright 2004 The Apache Software Foundation /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. */ using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using Query = Lucene.Net.Search.Query; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using TermQuery = Lucene.Net.Search.TermQuery; using TestUtil = Lucene.Net.Util.TestUtil; using TextField = TextField; using TopDocs = Lucene.Net.Search.TopDocs; [TestFixture] public class TestIndexWriterReader : LuceneTestCase { private readonly int NumThreads = TEST_NIGHTLY ? 5 : 3; public static int Count(Term t, IndexReader r) { int count = 0; DocsEnum td = TestUtil.Docs(Random(), r, t.Field, new BytesRef(t.Text()), MultiFields.GetLiveDocs(r), null, 0); if (td != null) { while (td.NextDoc() != DocIdSetIterator.NO_MORE_DOCS) { td.DocID(); count++; } } return count; } [Test] public virtual void TestAddCloseOpen() { // Can't use assertNoDeletes: this test pulls a non-NRT // reader in the end: Directory dir1 = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); IndexWriter writer = new IndexWriter(dir1, iwc); for (int i = 0; i < 97; i++) { DirectoryReader reader = writer.Reader; if (i == 0) { writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random().Next(5))); } else { int previous = Random().Next(i); // a check if the reader is current here could fail since there might be // merges going on. switch (Random().Next(5)) { case 0: case 1: case 2: writer.AddDocument(DocHelper.CreateDocument(i, "x", 1 + Random().Next(5))); break; case 3: writer.UpdateDocument(new Term("id", "" + previous), DocHelper.CreateDocument(previous, "x", 1 + Random().Next(5))); break; case 4: writer.DeleteDocuments(new Term("id", "" + previous)); break; } } Assert.IsFalse(reader.Current); reader.Dispose(); } writer.ForceMerge(1); // make sure all merging is done etc. DirectoryReader dirReader = writer.Reader; writer.Commit(); // no changes that are not visible to the reader Assert.IsTrue(dirReader.Current); writer.Dispose(); Assert.IsTrue(dirReader.Current); // all changes are visible to the reader iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); writer = new IndexWriter(dir1, iwc); Assert.IsTrue(dirReader.Current); writer.AddDocument(DocHelper.CreateDocument(1, "x", 1 + Random().Next(5))); Assert.IsTrue(dirReader.Current); // segments in ram but IW is different to the readers one writer.Dispose(); Assert.IsFalse(dirReader.Current); // segments written dirReader.Dispose(); dir1.Dispose(); } [Test] public virtual void TestUpdateDocument() { bool doFullMerge = true; Directory dir1 = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); if (iwc.MaxBufferedDocs < 20) { iwc.SetMaxBufferedDocs(20); } // no merging if (Random().NextBoolean()) { iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES); } else { iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); } if (VERBOSE) { Console.WriteLine("TEST: make index"); } IndexWriter writer = new IndexWriter(dir1, iwc); // create the index CreateIndexNoClose(!doFullMerge, "index1", writer); // writer.Flush(false, true, true); // get a reader DirectoryReader r1 = writer.Reader; Assert.IsTrue(r1.Current); string id10 = r1.Document(10).GetField("id").StringValue; Document newDoc = r1.Document(10); newDoc.RemoveField("id"); newDoc.Add(NewStringField("id", Convert.ToString(8000), Field.Store.YES)); writer.UpdateDocument(new Term("id", id10), newDoc); Assert.IsFalse(r1.Current); DirectoryReader r2 = writer.Reader; Assert.IsTrue(r2.Current); Assert.AreEqual(0, Count(new Term("id", id10), r2)); if (VERBOSE) { Console.WriteLine("TEST: verify id"); } Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r2)); r1.Dispose(); Assert.IsTrue(r2.Current); writer.Dispose(); Assert.IsTrue(r2.Current); DirectoryReader r3 = DirectoryReader.Open(dir1); Assert.IsTrue(r3.Current); Assert.IsTrue(r2.Current); Assert.AreEqual(0, Count(new Term("id", id10), r3)); Assert.AreEqual(1, Count(new Term("id", Convert.ToString(8000)), r3)); writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(NewTextField("field", "a b c", Field.Store.NO)); writer.AddDocument(doc); Assert.IsTrue(r2.Current); Assert.IsTrue(r3.Current); writer.Dispose(); Assert.IsFalse(r2.Current); Assert.IsTrue(!r3.Current); r2.Dispose(); r3.Dispose(); dir1.Dispose(); } [Test] public virtual void TestIsCurrent() { Directory dir = NewDirectory(); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); IndexWriter writer = new IndexWriter(dir, iwc); Document doc = new Document(); doc.Add(NewTextField("field", "a b c", Field.Store.NO)); writer.AddDocument(doc); writer.Dispose(); iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); writer = new IndexWriter(dir, iwc); doc = new Document(); doc.Add(NewTextField("field", "a b c", Field.Store.NO)); DirectoryReader nrtReader = writer.Reader; Assert.IsTrue(nrtReader.Current); writer.AddDocument(doc); Assert.IsFalse(nrtReader.Current); // should see the changes writer.ForceMerge(1); // make sure we don't have a merge going on Assert.IsFalse(nrtReader.Current); nrtReader.Dispose(); DirectoryReader dirReader = DirectoryReader.Open(dir); nrtReader = writer.Reader; Assert.IsTrue(dirReader.Current); Assert.IsTrue(nrtReader.Current); // nothing was committed yet so we are still current Assert.AreEqual(2, nrtReader.MaxDoc); // sees the actual document added Assert.AreEqual(1, dirReader.MaxDoc); writer.Dispose(); // close is actually a commit both should see the changes Assert.IsTrue(nrtReader.Current); Assert.IsFalse(dirReader.Current); // this reader has been opened before the writer was closed / committed dirReader.Dispose(); nrtReader.Dispose(); dir.Dispose(); } /// <summary> /// Test using IW.addIndexes /// </summary> [Test] public virtual void TestAddIndexes() { bool doFullMerge = false; Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); if (iwc.MaxBufferedDocs < 20) { iwc.SetMaxBufferedDocs(20); } // no merging if (Random().NextBoolean()) { iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES); } else { iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); } IndexWriter writer = new IndexWriter(dir1, iwc); // create the index CreateIndexNoClose(!doFullMerge, "index1", writer); writer.Flush(false, true); // create a 2nd index Directory dir2 = NewDirectory(); IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); CreateIndexNoClose(!doFullMerge, "index2", writer2); writer2.Dispose(); DirectoryReader r0 = writer.Reader; Assert.IsTrue(r0.Current); writer.AddIndexes(dir2); Assert.IsFalse(r0.Current); r0.Dispose(); DirectoryReader r1 = writer.Reader; Assert.IsTrue(r1.Current); writer.Commit(); Assert.IsTrue(r1.Current); // we have seen all changes - no change after opening the NRT reader Assert.AreEqual(200, r1.MaxDoc); int index2df = r1.DocFreq(new Term("indexname", "index2")); Assert.AreEqual(100, index2df); // verify the docs are from different indexes Document doc5 = r1.Document(5); Assert.AreEqual("index1", doc5.Get("indexname")); Document doc150 = r1.Document(150); Assert.AreEqual("index2", doc150.Get("indexname")); r1.Dispose(); writer.Dispose(); dir1.Dispose(); dir2.Dispose(); } [Test] public virtual void ExposeCompTermVR() { bool doFullMerge = false; Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriterConfig iwc = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); if (iwc.MaxBufferedDocs < 20) { iwc.SetMaxBufferedDocs(20); } // no merging if (Random().NextBoolean()) { iwc.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES); } else { iwc.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); } IndexWriter writer = new IndexWriter(dir1, iwc); CreateIndexNoClose(!doFullMerge, "index1", writer); writer.Dispose(); dir1.Dispose(); } [Test] public virtual void TestAddIndexes2() { bool doFullMerge = false; Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); // create a 2nd index Directory dir2 = NewDirectory(); IndexWriter writer2 = new IndexWriter(dir2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); CreateIndexNoClose(!doFullMerge, "index2", writer2); writer2.Dispose(); writer.AddIndexes(dir2); writer.AddIndexes(dir2); writer.AddIndexes(dir2); writer.AddIndexes(dir2); writer.AddIndexes(dir2); IndexReader r1 = writer.Reader; Assert.AreEqual(500, r1.MaxDoc); r1.Dispose(); writer.Dispose(); dir1.Dispose(); dir2.Dispose(); } /// <summary> /// Deletes using IW.deleteDocuments /// </summary> [Test] public virtual void TestDeleteFromIndexWriter() { bool doFullMerge = true; Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetReaderTermsIndexDivisor(2)); // create the index CreateIndexNoClose(!doFullMerge, "index1", writer); writer.Flush(false, true); // get a reader IndexReader r1 = writer.Reader; string id10 = r1.Document(10).GetField("id").StringValue; // deleted IW docs should not show up in the next getReader writer.DeleteDocuments(new Term("id", id10)); IndexReader r2 = writer.Reader; Assert.AreEqual(1, Count(new Term("id", id10), r1)); Assert.AreEqual(0, Count(new Term("id", id10), r2)); string id50 = r1.Document(50).GetField("id").StringValue; Assert.AreEqual(1, Count(new Term("id", id50), r1)); writer.DeleteDocuments(new Term("id", id50)); IndexReader r3 = writer.Reader; Assert.AreEqual(0, Count(new Term("id", id10), r3)); Assert.AreEqual(0, Count(new Term("id", id50), r3)); string id75 = r1.Document(75).GetField("id").StringValue; writer.DeleteDocuments(new TermQuery(new Term("id", id75))); IndexReader r4 = writer.Reader; Assert.AreEqual(1, Count(new Term("id", id75), r3)); Assert.AreEqual(0, Count(new Term("id", id75), r4)); r1.Dispose(); r2.Dispose(); r3.Dispose(); r4.Dispose(); writer.Dispose(); // reopen the writer to verify the delete made it to the directory writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); IndexReader w2r1 = writer.Reader; Assert.AreEqual(0, Count(new Term("id", id10), w2r1)); w2r1.Dispose(); writer.Dispose(); dir1.Dispose(); } [Test] public virtual void TestAddIndexesAndDoDeletesThreads() { const int numIter = 2; int numDirs = 3; Directory mainDir = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter mainWriter = new IndexWriter(mainDir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); TestUtil.ReduceOpenFiles(mainWriter); AddDirectoriesThreads addDirThreads = new AddDirectoriesThreads(this, numIter, mainWriter); addDirThreads.LaunchThreads(numDirs); addDirThreads.JoinThreads(); //Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads // * addDirThreads.NUM_INIT_DOCS, addDirThreads.mainWriter.NumDocs); Assert.AreEqual(addDirThreads.Count.Get(), addDirThreads.MainWriter.NumDocs()); addDirThreads.Close(true); Assert.IsTrue(addDirThreads.Failures.Count == 0); TestUtil.CheckIndex(mainDir); IndexReader reader = DirectoryReader.Open(mainDir); Assert.AreEqual(addDirThreads.Count.Get(), reader.NumDocs); //Assert.AreEqual(100 + numDirs * (3 * numIter / 4) * addDirThreads.numThreads // * addDirThreads.NUM_INIT_DOCS, reader.NumDocs); reader.Dispose(); addDirThreads.CloseDir(); mainDir.Dispose(); } private class AddDirectoriesThreads { internal bool InstanceFieldsInitialized = false; internal virtual void InitializeInstanceFields() { Threads = new ThreadClass[OuterInstance.NumThreads]; } private readonly TestIndexWriterReader OuterInstance; internal Directory AddDir; internal const int NUM_INIT_DOCS = 100; internal int NumDirs; internal ThreadClass[] Threads; internal IndexWriter MainWriter; internal readonly IList<Exception> Failures = new List<Exception>(); internal IndexReader[] Readers; internal bool DidClose = false; internal AtomicInteger Count = new AtomicInteger(0); internal AtomicInteger NumaddIndexes = new AtomicInteger(0); public AddDirectoriesThreads(TestIndexWriterReader outerInstance, int numDirs, IndexWriter mainWriter) { this.OuterInstance = outerInstance; if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; } this.NumDirs = numDirs; this.MainWriter = mainWriter; AddDir = NewDirectory(); IndexWriter writer = new IndexWriter(AddDir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2)); TestUtil.ReduceOpenFiles(writer); for (int i = 0; i < NUM_INIT_DOCS; i++) { Document doc = DocHelper.CreateDocument(i, "addindex", 4); writer.AddDocument(doc); } writer.Dispose(); Readers = new IndexReader[numDirs]; for (int i = 0; i < numDirs; i++) { Readers[i] = DirectoryReader.Open(AddDir); } } internal virtual void JoinThreads() { for (int i = 0; i < OuterInstance.NumThreads; i++) { try { Threads[i].Join(); } catch (ThreadInterruptedException ie) { throw new ThreadInterruptedException("Thread Interrupted Exception", ie); } } } internal virtual void Close(bool doWait) { DidClose = true; if (doWait) { MainWriter.WaitForMerges(); } MainWriter.Dispose(doWait); } internal virtual void CloseDir() { for (int i = 0; i < NumDirs; i++) { Readers[i].Dispose(); } AddDir.Dispose(); } internal virtual void Handle(Exception t) { Console.WriteLine(t.StackTrace); lock (Failures) { Failures.Add(t); } } internal virtual void LaunchThreads(int numIter) { for (int i = 0; i < OuterInstance.NumThreads; i++) { Threads[i] = new ThreadAnonymousInnerClassHelper(this, numIter); } for (int i = 0; i < OuterInstance.NumThreads; i++) { Threads[i].Start(); } } private class ThreadAnonymousInnerClassHelper : ThreadClass { private readonly AddDirectoriesThreads OuterInstance; private int NumIter; public ThreadAnonymousInnerClassHelper(AddDirectoriesThreads outerInstance, int numIter) { this.OuterInstance = outerInstance; this.NumIter = numIter; } public override void Run() { try { Directory[] dirs = new Directory[OuterInstance.NumDirs]; for (int k = 0; k < OuterInstance.NumDirs; k++) { dirs[k] = new MockDirectoryWrapper(Random(), new RAMDirectory(OuterInstance.AddDir, NewIOContext(Random()))); } //int j = 0; //while (true) { // System.out.println(Thread.currentThread().getName() + ": iter // j=" + j); for (int x = 0; x < NumIter; x++) { // only do addIndexes OuterInstance.DoBody(x, dirs); } //if (numIter > 0 && j == numIter) // break; //doBody(j++, dirs); //doBody(5, dirs); //} } catch (Exception t) { OuterInstance.Handle(t); } } } internal virtual void DoBody(int j, Directory[] dirs) { switch (j % 4) { case 0: MainWriter.AddIndexes(dirs); MainWriter.ForceMerge(1); break; case 1: MainWriter.AddIndexes(dirs); NumaddIndexes.IncrementAndGet(); break; case 2: MainWriter.AddIndexes(Readers); break; case 3: MainWriter.Commit(); break; } Count.AddAndGet(dirs.Length * NUM_INIT_DOCS); } } [Test] public virtual void TestIndexWriterReopenSegmentFullMerge() { DoTestIndexWriterReopenSegment(true); } [Test] public virtual void TestIndexWriterReopenSegment() { DoTestIndexWriterReopenSegment(false); } /// <summary> /// Tests creating a segment, then check to insure the segment can be seen via /// IW.getReader /// </summary> public virtual void DoTestIndexWriterReopenSegment(bool doFullMerge) { Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); IndexReader r1 = writer.Reader; Assert.AreEqual(0, r1.MaxDoc); CreateIndexNoClose(false, "index1", writer); writer.Flush(!doFullMerge, true); IndexReader iwr1 = writer.Reader; Assert.AreEqual(100, iwr1.MaxDoc); IndexReader r2 = writer.Reader; Assert.AreEqual(r2.MaxDoc, 100); // add 100 documents for (int x = 10000; x < 10000 + 100; x++) { Document d = DocHelper.CreateDocument(x, "index1", 5); writer.AddDocument(d); } writer.Flush(false, true); // verify the reader was reopened internally IndexReader iwr2 = writer.Reader; Assert.IsTrue(iwr2 != r1); Assert.AreEqual(200, iwr2.MaxDoc); // should have flushed out a segment IndexReader r3 = writer.Reader; Assert.IsTrue(r2 != r3); Assert.AreEqual(200, r3.MaxDoc); // dec ref the readers rather than close them because // closing flushes changes to the writer r1.Dispose(); iwr1.Dispose(); r2.Dispose(); r3.Dispose(); iwr2.Dispose(); writer.Dispose(); // test whether the changes made it to the directory writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); IndexReader w2r1 = writer.Reader; // insure the deletes were actually flushed to the directory Assert.AreEqual(200, w2r1.MaxDoc); w2r1.Dispose(); writer.Dispose(); dir1.Dispose(); } /* * Delete a document by term and return the doc id * * public static int deleteDocument(Term term, IndexWriter writer) throws * IOException { IndexReader reader = writer.GetReader(); TermDocs td = * reader.termDocs(term); int doc = -1; //if (td.Next()) { // doc = td.Doc(); * //} //writer.DeleteDocuments(term); td.Dispose(); return doc; } */ public static void CreateIndex(Random random, Directory dir1, string indexName, bool multiSegment) { IndexWriter w = new IndexWriter(dir1, LuceneTestCase.NewIndexWriterConfig(random, TEST_VERSION_CURRENT, new MockAnalyzer(random)).SetMergePolicy(new LogDocMergePolicy())); for (int i = 0; i < 100; i++) { w.AddDocument(DocHelper.CreateDocument(i, indexName, 4)); } if (!multiSegment) { w.ForceMerge(1); } w.Dispose(); } public static void CreateIndexNoClose(bool multiSegment, string indexName, IndexWriter w) { for (int i = 0; i < 100; i++) { w.AddDocument(DocHelper.CreateDocument(i, indexName, 4)); } if (!multiSegment) { w.ForceMerge(1); } } private class MyWarmer : IndexWriter.IndexReaderWarmer { internal int WarmCount; public override void Warm(AtomicReader reader) { WarmCount++; } } [Test] public virtual void TestMergeWarmer() { Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); // Enroll warmer MyWarmer warmer = new MyWarmer(); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetMergedSegmentWarmer(warmer).SetMergeScheduler(new ConcurrentMergeScheduler()).SetMergePolicy(NewLogMergePolicy())); // create the index CreateIndexNoClose(false, "test", writer); // get a reader to put writer into near real-time mode IndexReader r1 = writer.Reader; ((LogMergePolicy)writer.Config.MergePolicy).MergeFactor = 2; int num = AtLeast(100); for (int i = 0; i < num; i++) { writer.AddDocument(DocHelper.CreateDocument(i, "test", 4)); } ((ConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync(); Assert.IsTrue(warmer.WarmCount > 0); int count = warmer.WarmCount; writer.AddDocument(DocHelper.CreateDocument(17, "test", 4)); writer.ForceMerge(1); Assert.IsTrue(warmer.WarmCount > count); writer.Dispose(); r1.Dispose(); dir1.Dispose(); } [Test] public virtual void TestAfterCommit() { Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergeScheduler(new ConcurrentMergeScheduler())); writer.Commit(); // create the index CreateIndexNoClose(false, "test", writer); // get a reader to put writer into near real-time mode DirectoryReader r1 = writer.Reader; TestUtil.CheckIndex(dir1); writer.Commit(); TestUtil.CheckIndex(dir1); Assert.AreEqual(100, r1.NumDocs); for (int i = 0; i < 10; i++) { writer.AddDocument(DocHelper.CreateDocument(i, "test", 4)); } ((ConcurrentMergeScheduler)writer.Config.MergeScheduler).Sync(); DirectoryReader r2 = DirectoryReader.OpenIfChanged(r1); if (r2 != null) { r1.Dispose(); r1 = r2; } Assert.AreEqual(110, r1.NumDocs); writer.Dispose(); r1.Dispose(); dir1.Dispose(); } // Make sure reader remains usable even if IndexWriter closes [Test] public virtual void TestAfterClose() { Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); // create the index CreateIndexNoClose(false, "test", writer); DirectoryReader r = writer.Reader; writer.Dispose(); TestUtil.CheckIndex(dir1); // reader should remain usable even after IndexWriter is closed: Assert.AreEqual(100, r.NumDocs); Query q = new TermQuery(new Term("indexname", "test")); IndexSearcher searcher = NewSearcher(r); Assert.AreEqual(100, searcher.Search(q, 10).TotalHits); try { DirectoryReader.OpenIfChanged(r); Assert.Fail("failed to hit AlreadyClosedException"); } catch (AlreadyClosedException ace) { // expected } r.Dispose(); dir1.Dispose(); } // Stress test reopen during addIndexes [Test] public virtual void TestDuringAddIndexes() { Directory dir1 = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy(2))); // create the index CreateIndexNoClose(false, "test", writer); writer.Commit(); Directory[] dirs = new Directory[10]; for (int i = 0; i < 10; i++) { dirs[i] = new MockDirectoryWrapper(Random(), new RAMDirectory(dir1, NewIOContext(Random()))); } DirectoryReader r = writer.Reader; const float SECONDS = 0.5f; long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS); IList<Exception> excs = new SynchronizedCollection<Exception>(); // Only one thread can addIndexes at a time, because // IndexWriter acquires a write lock in each directory: var threads = new ThreadClass[1]; for (int i = 0; i < threads.Length; i++) { threads[i] = new ThreadAnonymousInnerClassHelper(writer, dirs, endTime, excs); threads[i].SetDaemon(true); threads[i].Start(); } int lastCount = 0; while (Environment.TickCount < endTime) { DirectoryReader r2 = DirectoryReader.OpenIfChanged(r); if (r2 != null) { r.Dispose(); r = r2; } Query q = new TermQuery(new Term("indexname", "test")); IndexSearcher searcher = NewSearcher(r); int count = searcher.Search(q, 10).TotalHits; Assert.IsTrue(count >= lastCount); lastCount = count; } for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } // final check DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r); if (dr2 != null) { r.Dispose(); r = dr2; } Query q2 = new TermQuery(new Term("indexname", "test")); IndexSearcher searcher_ = NewSearcher(r); int count_ = searcher_.Search(q2, 10).TotalHits; Assert.IsTrue(count_ >= lastCount); Assert.AreEqual(0, excs.Count); r.Dispose(); if (dir1 is MockDirectoryWrapper) { ICollection<string> openDeletedFiles = ((MockDirectoryWrapper)dir1).OpenDeletedFiles; Assert.AreEqual(0, openDeletedFiles.Count, "openDeleted=" + openDeletedFiles); } writer.Dispose(); dir1.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadClass { private IndexWriter Writer; private Directory[] Dirs; private long EndTime; private IList<Exception> Excs; public ThreadAnonymousInnerClassHelper(IndexWriter writer, Directory[] dirs, long endTime, IList<Exception> excs) { this.Writer = writer; this.Dirs = dirs; this.EndTime = endTime; this.Excs = excs; } public override void Run() { do { try { Writer.AddIndexes(Dirs); Writer.MaybeMerge(); } catch (Exception t) { Excs.Add(t); throw new Exception(t.Message, t); } } while (Environment.TickCount < EndTime); } } private Directory GetAssertNoDeletesDirectory(Directory directory) { if (directory is MockDirectoryWrapper) { ((MockDirectoryWrapper)directory).AssertNoDeleteOpenFile = true; } return directory; } // Stress test reopen during add/delete [Test] public virtual void TestDuringAddDelete() { Directory dir1 = NewDirectory(); var writer = new IndexWriter(dir1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy(2))); // create the index CreateIndexNoClose(false, "test", writer); writer.Commit(); DirectoryReader r = writer.Reader; const float SECONDS = 0.5f; long endTime = (long)(Environment.TickCount + 1000.0 * SECONDS); IList<Exception> excs = new SynchronizedCollection<Exception>(); var threads = new ThreadClass[NumThreads]; for (int i = 0; i < NumThreads; i++) { threads[i] = new ThreadAnonymousInnerClassHelper2(writer, r, endTime, excs); threads[i].SetDaemon(true); threads[i].Start(); } int sum = 0; while (Environment.TickCount < endTime) { DirectoryReader r2 = DirectoryReader.OpenIfChanged(r); if (r2 != null) { r.Dispose(); r = r2; } Query q = new TermQuery(new Term("indexname", "test")); IndexSearcher searcher = NewSearcher(r); sum += searcher.Search(q, 10).TotalHits; } for (int i = 0; i < NumThreads; i++) { threads[i].Join(); } // at least search once DirectoryReader dr2 = DirectoryReader.OpenIfChanged(r); if (dr2 != null) { r.Dispose(); r = dr2; } Query q2 = new TermQuery(new Term("indexname", "test")); IndexSearcher indSearcher = NewSearcher(r); sum += indSearcher.Search(q2, 10).TotalHits; Assert.IsTrue(sum > 0, "no documents found at all"); Assert.AreEqual(0, excs.Count); writer.Dispose(); r.Dispose(); dir1.Dispose(); } private class ThreadAnonymousInnerClassHelper2 : ThreadClass { private IndexWriter Writer; private DirectoryReader r; private long EndTime; private IList<Exception> Excs; public ThreadAnonymousInnerClassHelper2(IndexWriter writer, DirectoryReader r, long endTime, IList<Exception> excs) { this.Writer = writer; this.r = r; this.EndTime = endTime; this.Excs = excs; rand = new Random(Random().Next()); } internal readonly Random rand; public override void Run() { int count = 0; do { try { for (int docUpto = 0; docUpto < 10; docUpto++) { Writer.AddDocument(DocHelper.CreateDocument(10 * count + docUpto, "test", 4)); } count++; int limit = count * 10; for (int delUpto = 0; delUpto < 5; delUpto++) { int x = rand.Next(limit); Writer.DeleteDocuments(new Term("field3", "b" + x)); } } catch (Exception t) { Excs.Add(t); throw new Exception(t.Message, t); } } while (Environment.TickCount < EndTime); } } [Test] public virtual void TestForceMergeDeletes() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMergePolicy(NewLogMergePolicy())); Document doc = new Document(); doc.Add(NewTextField("field", "a b c", Field.Store.NO)); Field id = NewStringField("id", "", Field.Store.NO); doc.Add(id); id.StringValue = "0"; w.AddDocument(doc); id.StringValue = "1"; w.AddDocument(doc); w.DeleteDocuments(new Term("id", "0")); IndexReader r = w.Reader; w.ForceMergeDeletes(); w.Dispose(); r.Dispose(); r = DirectoryReader.Open(dir); Assert.AreEqual(1, r.NumDocs); Assert.IsFalse(r.HasDeletions); r.Dispose(); dir.Dispose(); } [Test] public virtual void TestDeletesNumDocs() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); Document doc = new Document(); doc.Add(NewTextField("field", "a b c", Field.Store.NO)); Field id = NewStringField("id", "", Field.Store.NO); doc.Add(id); id.StringValue = "0"; w.AddDocument(doc); id.StringValue = "1"; w.AddDocument(doc); IndexReader r = w.Reader; Assert.AreEqual(2, r.NumDocs); r.Dispose(); w.DeleteDocuments(new Term("id", "0")); r = w.Reader; Assert.AreEqual(1, r.NumDocs); r.Dispose(); w.DeleteDocuments(new Term("id", "1")); r = w.Reader; Assert.AreEqual(0, r.NumDocs); r.Dispose(); w.Dispose(); dir.Dispose(); } [Test] public virtual void TestEmptyIndex() { // Ensures that getReader works on an empty index, which hasn't been committed yet. Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); IndexReader r = w.Reader; Assert.AreEqual(0, r.NumDocs); r.Dispose(); w.Dispose(); dir.Dispose(); } [Test] public virtual void TestSegmentWarmer() { Directory dir = NewDirectory(); AtomicBoolean didWarm = new AtomicBoolean(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetReaderPooling(true).SetMergedSegmentWarmer(new IndexReaderWarmerAnonymousInnerClassHelper(this, didWarm)). SetMergePolicy(NewLogMergePolicy(10))); Document doc = new Document(); doc.Add(NewStringField("foo", "bar", Field.Store.NO)); for (int i = 0; i < 20; i++) { w.AddDocument(doc); } w.WaitForMerges(); w.Dispose(); dir.Dispose(); Assert.IsTrue(didWarm.Get()); } private class IndexReaderWarmerAnonymousInnerClassHelper : IndexWriter.IndexReaderWarmer { private readonly TestIndexWriterReader OuterInstance; private AtomicBoolean DidWarm; public IndexReaderWarmerAnonymousInnerClassHelper(TestIndexWriterReader outerInstance, AtomicBoolean didWarm) { this.OuterInstance = outerInstance; this.DidWarm = didWarm; } public override void Warm(AtomicReader r) { IndexSearcher s = NewSearcher(r); TopDocs hits = s.Search(new TermQuery(new Term("foo", "bar")), 10); Assert.AreEqual(20, hits.TotalHits); DidWarm.Set(true); } } [Test] public virtual void TestSimpleMergedSegmentWramer() { Directory dir = NewDirectory(); AtomicBoolean didWarm = new AtomicBoolean(); InfoStream infoStream = new InfoStreamAnonymousInnerClassHelper(this, didWarm); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(2).SetReaderPooling(true).SetInfoStream(infoStream).SetMergedSegmentWarmer(new SimpleMergedSegmentWarmer(infoStream)).SetMergePolicy(NewLogMergePolicy(10))); Document doc = new Document(); doc.Add(NewStringField("foo", "bar", Field.Store.NO)); for (int i = 0; i < 20; i++) { w.AddDocument(doc); } w.WaitForMerges(); w.Dispose(); dir.Dispose(); Assert.IsTrue(didWarm.Get()); } private class InfoStreamAnonymousInnerClassHelper : InfoStream { private readonly TestIndexWriterReader OuterInstance; private AtomicBoolean DidWarm; public InfoStreamAnonymousInnerClassHelper(TestIndexWriterReader outerInstance, AtomicBoolean didWarm) { this.OuterInstance = outerInstance; this.DidWarm = didWarm; } public override void Dispose() { } public override void Message(string component, string message) { if ("SMSW".Equals(component)) { DidWarm.Set(true); } } public override bool IsEnabled(string component) { return true; } } [Test] public virtual void TestNoTermsIndex() { // Some Codecs don't honor the ReaderTermsIndexDivisor, so skip the test if // they're picked. AssumeFalse("PreFlex codec does not support ReaderTermsIndexDivisor!", "Lucene3x".Equals(Codec.Default.Name)); IndexWriterConfig conf = (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetReaderTermsIndexDivisor(-1); // Don't proceed if picked Codec is in the list of illegal ones. string format = TestUtil.GetPostingsFormat("f"); AssumeFalse("Format: " + format + " does not support ReaderTermsIndexDivisor!", (format.Equals("FSTPulsing41") || format.Equals("FSTOrdPulsing41") || format.Equals("FST41") || format.Equals("FSTOrd41") || format.Equals("SimpleText") || format.Equals("Memory") || format.Equals("MockRandom") || format.Equals("Direct"))); Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, conf); Document doc = new Document(); doc.Add(new TextField("f", "val", Field.Store.NO)); w.AddDocument(doc); SegmentReader r = GetOnlySegmentReader(DirectoryReader.Open(w, true)); try { TestUtil.Docs(Random(), r, "f", new BytesRef("val"), null, null, DocsEnum.FLAG_NONE); Assert.Fail("should have failed to seek since terms index was not loaded."); } catch (InvalidOperationException e) { // expected - we didn't load the term index } finally { r.Dispose(); w.Dispose(); dir.Dispose(); } } [Test] public virtual void TestReopenAfterNoRealChange() { Directory d = GetAssertNoDeletesDirectory(NewDirectory()); IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random()))); DirectoryReader r = w.Reader; // start pooling readers DirectoryReader r2 = DirectoryReader.OpenIfChanged(r); Assert.IsNull(r2); w.AddDocument(new Document()); DirectoryReader r3 = DirectoryReader.OpenIfChanged(r); Assert.IsNotNull(r3); Assert.IsTrue(r3.Version != r.Version); Assert.IsTrue(r3.Current); // Deletes nothing in reality...: w.DeleteDocuments(new Term("foo", "bar")); // ... but IW marks this as not current: Assert.IsFalse(r3.Current); DirectoryReader r4 = DirectoryReader.OpenIfChanged(r3); Assert.IsNull(r4); // Deletes nothing in reality...: w.DeleteDocuments(new Term("foo", "bar")); DirectoryReader r5 = DirectoryReader.OpenIfChanged(r3, w, true); Assert.IsNull(r5); r3.Dispose(); w.Dispose(); d.Dispose(); } [Test] public virtual void TestNRTOpenExceptions() { // LUCENE-5262: test that several failed attempts to obtain an NRT reader // don't leak file handles. MockDirectoryWrapper dir = (MockDirectoryWrapper)GetAssertNoDeletesDirectory(NewMockDirectory()); AtomicBoolean shouldFail = new AtomicBoolean(); dir.FailOn(new FailureAnonymousInnerClassHelper(shouldFail)); IndexWriterConfig conf = NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); conf.SetMergePolicy(NoMergePolicy.COMPOUND_FILES); // prevent merges from getting in the way IndexWriter writer = new IndexWriter(dir, conf); // create a segment and open an NRT reader writer.AddDocument(new Document()); writer.Reader.Dispose(); // add a new document so a new NRT reader is required writer.AddDocument(new Document()); // try to obtain an NRT reader twice: first time it fails and closes all the // other NRT readers. second time it fails, but also fails to close the // other NRT reader, since it is already marked closed! for (int i = 0; i < 2; i++) { shouldFail.Set(true); try { writer.Reader.Dispose(); } catch (FakeIOException e) { // expected if (VERBOSE) { Console.WriteLine("hit expected fake IOE"); } } } writer.Dispose(); dir.Dispose(); } private class FailureAnonymousInnerClassHelper : MockDirectoryWrapper.Failure { private readonly AtomicBoolean ShouldFail; public FailureAnonymousInnerClassHelper(AtomicBoolean shouldFail) { this.ShouldFail = shouldFail; } public override void Eval(MockDirectoryWrapper dir) { var trace = new StackTrace(); if (ShouldFail.Get()) { foreach (var frame in trace.GetFrames()) { var method = frame.GetMethod(); if ("GetReadOnlyClone".Equals(method.Name)) { if (VERBOSE) { Console.WriteLine("TEST: now fail; exc:"); Console.WriteLine((new Exception()).StackTrace); } ShouldFail.Set(false); throw new FakeIOException(); } } } } } /// <summary> /// Make sure if all we do is open NRT reader against /// writer, we don't see merge starvation. /// </summary> [Test] public virtual void TestTooManySegments() { Directory dir = GetAssertNoDeletesDirectory(NewDirectory()); // Don't use newIndexWriterConfig, because we need a // "sane" mergePolicy: IndexWriterConfig iwc = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())); IndexWriter w = new IndexWriter(dir, iwc); // Create 500 segments: for (int i = 0; i < 500; i++) { Document doc = new Document(); doc.Add(NewStringField("id", "" + i, Field.Store.NO)); w.AddDocument(doc); IndexReader r = DirectoryReader.Open(w, true); // Make sure segment count never exceeds 100: Assert.IsTrue(r.Leaves.Count < 100); r.Dispose(); } w.Dispose(); dir.Dispose(); } } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Account.DataAccess; using Frapid.Account.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.Account.Api.Tests { public class UserTests { public static UserController Fixture() { UserController controller = new UserController(new UserRepository()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.Account.Entities.User user = Fixture().Get(0); Assert.NotNull(user); } [Fact] [Conditional("Debug")] public void First() { Frapid.Account.Entities.User user = Fixture().GetFirst(); Assert.NotNull(user); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.Account.Entities.User user = Fixture().GetPrevious(0); Assert.NotNull(user); } [Fact] [Conditional("Debug")] public void Next() { Frapid.Account.Entities.User user = Fixture().GetNext(0); Assert.NotNull(user); } [Fact] [Conditional("Debug")] public void Last() { Frapid.Account.Entities.User user = Fixture().GetLast(); Assert.NotNull(user); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.Account.Entities.User> users = Fixture().Get(new int[] { }); Assert.NotNull(users); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime; using Internal.Runtime.CompilerServices; #pragma warning disable SA1121 // explicitly using type aliases instead of built-in types #if BIT64 using nuint = System.UInt64; #else using nuint = System.UInt32; #endif namespace System { internal static partial class SpanHelpers { public static unsafe void ClearWithoutReferences(ref byte b, nuint byteLength) { if (byteLength == 0) return; #if AMD64 || ARM64 // The exact matrix on when RhZeroMemory is faster than InitBlockUnaligned is very complex. The factors to consider include // type of hardware and memory aligment. This threshold was chosen as a good balance accross different configurations. if (byteLength > 768) goto PInvoke; Unsafe.InitBlockUnaligned(ref b, 0, (uint)byteLength); return; #else // TODO: Optimize other platforms to be on par with AMD64 CoreCLR // Note: It's important that this switch handles lengths at least up to 22. // See notes below near the main loop for why. // The switch will be very fast since it can be implemented using a jump // table in assembly. See http://stackoverflow.com/a/449297/4077294 for more info. switch (byteLength) { case 1: b = 0; return; case 2: Unsafe.As<byte, short>(ref b) = 0; return; case 3: Unsafe.As<byte, short>(ref b) = 0; Unsafe.Add<byte>(ref b, 2) = 0; return; case 4: Unsafe.As<byte, int>(ref b) = 0; return; case 5: Unsafe.As<byte, int>(ref b) = 0; Unsafe.Add<byte>(ref b, 4) = 0; return; case 6: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; return; case 7: Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.Add<byte>(ref b, 6) = 0; return; case 8: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif return; case 9: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.Add<byte>(ref b, 8) = 0; return; case 10: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 11: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 10) = 0; return; case 12: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; return; case 13: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.Add<byte>(ref b, 12) = 0; return; case 14: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; return; case 15: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 12)) = 0; Unsafe.Add<byte>(ref b, 14) = 0; return; case 16: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif return; case 17: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.Add<byte>(ref b, 16) = 0; return; case 18: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 19: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 18) = 0; return; case 20: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; return; case 21: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.Add<byte>(ref b, 20) = 0; return; case 22: #if BIT64 Unsafe.As<byte, long>(ref b) = 0; Unsafe.As<byte, long>(ref Unsafe.Add<byte>(ref b, 8)) = 0; #else Unsafe.As<byte, int>(ref b) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 12)) = 0; #endif Unsafe.As<byte, int>(ref Unsafe.Add<byte>(ref b, 16)) = 0; Unsafe.As<byte, short>(ref Unsafe.Add<byte>(ref b, 20)) = 0; return; } // P/Invoke into the native version for large lengths if (byteLength >= 512) goto PInvoke; nuint i = 0; // byte offset at which we're copying if (((nuint)Unsafe.AsPointer(ref b) & 3) != 0) { if (((nuint)Unsafe.AsPointer(ref b) & 1) != 0) { b = 0; i += 1; if (((nuint)Unsafe.AsPointer(ref b) & 2) != 0) goto IntAligned; } Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } IntAligned: // On 64-bit IntPtr.Size == 8, so we want to advance to the next 8-aligned address. If // (int)b % 8 is 0, 5, 6, or 7, we will already have advanced by 0, 3, 2, or 1 // bytes to the next aligned address (respectively), so do nothing. On the other hand, // if it is 1, 2, 3, or 4 we will want to copy-and-advance another 4 bytes until // we're aligned. // The thing 1, 2, 3, and 4 have in common that the others don't is that if you // subtract one from them, their 3rd lsb will not be set. Hence, the below check. if ((((nuint)Unsafe.AsPointer(ref b) - 1) & 4) == 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } nuint end = byteLength - 16; byteLength -= i; // lower 4 bits of byteLength represent how many bytes are left *after* the unrolled loop // We know due to the above switch-case that this loop will always run 1 iteration; max // bytes we clear before checking is 23 (7 to align the pointers, 16 for 1 iteration) so // the switch handles lengths 0-22. Debug.Assert(end >= 7 && i <= end); // This is separated out into a different variable, so the i + 16 addition can be // performed at the start of the pipeline and the loop condition does not have // a dependency on the writes. nuint counter; do { counter = i + 16; // This loop looks very costly since there appear to be a bunch of temporary values // being created with the adds, but the jit (for x86 anyways) will convert each of // these to use memory addressing operands. // So the only cost is a bit of code size, which is made up for by the fact that // we save on writes to b. #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 8)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 12)) = 0; #endif i = counter; // See notes above for why this wasn't used instead // i += 16; } while (counter <= end); if ((byteLength & 8) != 0) { #if BIT64 Unsafe.As<byte, long>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; #else Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i + 4)) = 0; #endif i += 8; } if ((byteLength & 4) != 0) { Unsafe.As<byte, int>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 4; } if ((byteLength & 2) != 0) { Unsafe.As<byte, short>(ref Unsafe.AddByteOffset<byte>(ref b, i)) = 0; i += 2; } if ((byteLength & 1) != 0) { Unsafe.AddByteOffset<byte>(ref b, i) = 0; // We're not using i after this, so not needed // i += 1; } return; #endif PInvoke: RuntimeImports.RhZeroMemory(ref b, byteLength); } public static unsafe void ClearWithReferences(ref IntPtr ip, nuint pointerSizeLength) { Debug.Assert((int)Unsafe.AsPointer(ref ip) % sizeof(IntPtr) == 0, "Should've been aligned on natural word boundary."); // First write backward 8 natural words at a time. // Writing backward allows us to get away with only simple modifications to the // mov instruction's base and index registers between loop iterations. for (; pointerSizeLength >= 8; pointerSizeLength -= 8) { Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -1) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -2) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -3) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -4) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -5) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -6) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -7) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -8) = default; } Debug.Assert(pointerSizeLength <= 7); // The logic below works by trying to minimize the number of branches taken for any // given range of lengths. For example, the lengths [ 4 .. 7 ] are handled by a single // branch, [ 2 .. 3 ] are handled by a single branch, and [ 1 ] is handled by a single // branch. // // We can write both forward and backward as a perf improvement. For example, // the lengths [ 4 .. 7 ] can be handled by zeroing out the first four natural // words and the last 3 natural words. In the best case (length = 7), there are // no overlapping writes. In the worst case (length = 4), there are three // overlapping writes near the middle of the buffer. In perf testing, the // penalty for performing duplicate writes is less expensive than the penalty // for complex branching. if (pointerSizeLength >= 4) { goto Write4To7; } else if (pointerSizeLength >= 2) { goto Write2To3; } else if (pointerSizeLength > 0) { goto Write1; } else { return; // nothing to write } Write4To7: Debug.Assert(pointerSizeLength >= 4); // Write first four and last three. Unsafe.Add(ref ip, 2) = default; Unsafe.Add(ref ip, 3) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -3) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -2) = default; Write2To3: Debug.Assert(pointerSizeLength >= 2); // Write first two and last one. Unsafe.Add(ref ip, 1) = default; Unsafe.Add(ref Unsafe.Add(ref ip, (IntPtr)pointerSizeLength), -1) = default; Write1: Debug.Assert(pointerSizeLength >= 1); // Write only element. ip = default; } } }
using System; using NUnit.Framework; using Zu.AsyncChromeDriver.Tests.Environment; using System.Collections.ObjectModel; using System.Threading.Tasks; using Zu.AsyncWebDriver; using Zu.WebBrowser.BasicTypes; using Zu.WebBrowser.BrowserOptions; using Size = Zu.WebBrowser.BasicTypes.WebSize; namespace Zu.AsyncChromeDriver.Tests { [TestFixture] public class VisibilityTest : DriverTestFixture { [Test] public async Task ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot() { await driver.GoToUrl(javascriptPage); Assert.That(await driver.FindElement(By.Id("displayed")).Displayed(), Is.True, "Element with ID 'displayed' should be displayed"); Assert.That(await driver.FindElement(By.Id("none")).Displayed(), Is.False, "Element with ID 'none' should not be displayed"); Assert.That(await driver.FindElement(By.Id("suppressedParagraph")).Displayed(), Is.False, "Element with ID 'suppressedParagraph' should not be displayed"); Assert.That(await driver.FindElement(By.Id("hidden")).Displayed(), Is.False, "Element with ID 'hidden' should not be displayed"); } [Test] public async Task VisibilityShouldTakeIntoAccountParentVisibility() { await driver.GoToUrl(javascriptPage); IWebElement childDiv = await driver.FindElement(By.Id("hiddenchild")); IWebElement hiddenLink = await driver.FindElement(By.Id("hiddenlink")); Assert.That(await childDiv.Displayed(), Is.False, "Child div should not be displayed"); Assert.That(await hiddenLink.Displayed(), Is.False, "Hidden link should not be displayed"); } [Test] public async Task ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet() { await driver.GoToUrl(javascriptPage); IWebElement shown = await driver.FindElement(By.Id("visibleSubElement")); Assert.That(await shown.Displayed(), Is.True); } [Test] public async Task ShouldModifyTheVisibilityOfAnElementDynamically() { await driver.GoToUrl(javascriptPage); IWebElement element = await driver.FindElement(By.Id("hideMe")); Assert.That(await element.Displayed(), Is.True); await element.Click(); Assert.That(await element.Displayed(), Is.False); } [Test] public async Task HiddenInputElementsAreNeverVisible() { await driver.GoToUrl(javascriptPage); IWebElement shown = await driver.FindElement(By.Name("hidden")); Assert.That(await shown.Displayed(), Is.False); } [Test] public async Task ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed() { await driver.GoToUrl(javascriptPage); IWebElement element = await driver.FindElement(By.Id("unclickable")); //Assert.That(async () => await element.Click(), Throws.InstanceOf<ElementNotInteractableException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.Click(), exception => Assert.AreEqual("ElementNotInteractableException", exception.Error)); } [Test] public async Task ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed() { await driver.GoToUrl(javascriptPage); IWebElement element = await driver.FindElement(By.Id("unclickable")); //Assert.That(async () => await element.SendKeys("You don't see me"), Throws.InstanceOf<ElementNotInteractableException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.SendKeys("You don't see me"), exception => Assert.AreEqual("ElementNotInteractableException", exception.Error)); Assert.That(await element.GetAttribute("value"), Is.Not.EqualTo("You don't see me")); } [Test] public async Task ZeroSizedDivIsShownIfDescendantHasSize() { await driver.GoToUrl(javascriptPage); IWebElement element = await driver.FindElement(By.Id("zero")); Size size = await element.Size(); Assert.AreEqual(0, size.Width, "Should have 0 width"); Assert.AreEqual(0, size.Height, "Should have 0 height"); Assert.That(await element.Displayed(), Is.True); } [Test] public async Task ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden() { String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html"); await driver.GoToUrl(url); IWebElement element = await driver.FindElement(By.Id("suggest")); Assert.That(await element.Displayed(), Is.True); } [Test] public async Task ElementHiddenByOverflowXIsNotVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_hidden.html", "overflow/x_hidden_y_scroll.html", "overflow/x_hidden_y_auto.html", }; foreach (string page in pages) { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs(page)); IWebElement right = await driver.FindElement(By.Id("right")); Assert.That(await right.Displayed(), Is.False, "Failed for " + page); IWebElement bottomRight = await driver.FindElement(By.Id("bottom-right")); Assert.That(await bottomRight.Displayed(), Is.False, "Failed for " + page); } } [Test] public async Task ElementHiddenByOverflowYIsNotVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_hidden.html", "overflow/x_scroll_y_hidden.html", "overflow/x_auto_y_hidden.html", }; foreach (string page in pages) { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs(page)); IWebElement bottom = await driver.FindElement(By.Id("bottom")); Assert.That(await bottom.Displayed(), Is.False, "Failed for " + page); IWebElement bottomRight = await driver.FindElement(By.Id("bottom-right")); Assert.That(await bottomRight.Displayed(), Is.False, "Failed for " + page); } } [Test] public async Task ElementScrollableByOverflowXIsVisible() { string[] pages = new string[]{ "overflow/x_scroll_y_hidden.html", "overflow/x_scroll_y_scroll.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_hidden.html", "overflow/x_auto_y_scroll.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs(page)); IWebElement right = await driver.FindElement(By.Id("right")); Assert.That(await right.Displayed(), Is.True, "Failed for " + page); } } [Test] public async Task ElementScrollableByOverflowYIsVisible() { string[] pages = new string[]{ "overflow/x_hidden_y_scroll.html", "overflow/x_scroll_y_scroll.html", "overflow/x_auto_y_scroll.html", "overflow/x_hidden_y_auto.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs(page)); IWebElement bottom = await driver.FindElement(By.Id("bottom")); Assert.That(await bottom.Displayed(), Is.True, "Failed for " + page); } } [Test] public async Task ElementScrollableByOverflowXAndYIsVisible() { string[] pages = new string[]{ "overflow/x_scroll_y_scroll.html", "overflow/x_scroll_y_auto.html", "overflow/x_auto_y_scroll.html", "overflow/x_auto_y_auto.html", }; foreach (string page in pages) { await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs(page)); IWebElement bottomRight = await driver.FindElement(By.Id("bottom-right")); Assert.That(await bottomRight.Displayed(), Is.True, "Failed for " + page); } } [Test] public async Task TooSmallAWindowWithOverflowHiddenIsNotAProblem() { IWindow window = driver.Options().Window; Size originalSize = await window.GetSize(); try { // Short in the Y dimension await window.SetSize(new Size(1024, 500)); await driver.GoToUrl(EnvironmentManager.Instance.UrlBuilder.WhereIs("overflow-body.html")); IWebElement element = await driver.FindElement(By.Name("resultsFrame")); Assert.That(await element.Displayed(), Is.True); } finally { await window.SetSize(originalSize); } } [Test] public async Task ShouldShowElementNotVisibleWithHiddenAttribute() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html"); await driver.GoToUrl(url); IWebElement element = await driver.FindElement(By.Id("singleHidden")); Assert.That(await element.Displayed(), Is.False); } [Test] public async Task ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute() { string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html"); await driver.GoToUrl(url); IWebElement element = await driver.FindElement(By.Id("child")); Assert.That(await element.Displayed(), Is.False); } [Test] public async Task ShouldBeAbleToClickOnElementsWithOpacityZero() { await driver.GoToUrl(clickJackerPage); IWebElement element = await driver.FindElement(By.Id("clickJacker")); Assert.AreEqual("0", await element.GetCssValue("opacity"), "Precondition failed: clickJacker should be transparent"); await element.Click(); Assert.AreEqual("1", await element.GetCssValue("opacity")); } [Test] public async Task ShouldBeAbleToSelectOptionsFromAnInvisibleSelect() { await driver.GoToUrl(formsPage); IWebElement select = await driver.FindElement(By.Id("invisi_select")); ReadOnlyCollection<IWebElement> options = await select.FindElements(By.TagName("option")); IWebElement apples = options[0]; IWebElement oranges = options[1]; Assert.That(await apples.Selected(), Is.True, "Apples should be selected"); Assert.That(await oranges.Selected(), Is.False, "Oranges shoudl be selected"); await oranges.Click(); Assert.That(await apples.Selected(), Is.False, "Apples should not be selected"); Assert.That(await oranges.Selected(), Is.True, "Oranges should be selected"); } [Test] public async Task CorrectlyDetectMapElementsAreShown() { await driver.GoToUrl(mapVisibilityPage); IWebElement area = await driver.FindElement(By.Id("mtgt_unnamed_0")); bool isShown = await area.Displayed(); Assert.That(isShown, Is.True, "The element and the enclosing map should be considered shown."); } //------------------------------------------------------------------ // Tests below here are not included in the Java test suite //------------------------------------------------------------------ [Test] public async Task ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed() { await driver.GoToUrl(javascriptPage); IWebElement element = await driver.FindElement(By.Id("untogglable")); //Assert.That(async () => await element.Click(), Throws.InstanceOf<ElementNotInteractableException>()); await AssertEx.ThrowsAsync<WebBrowserException>(async () => await element.Click(), exception => Assert.AreEqual("ElementNotInteractableException", exception.Error)); } [Test] public async Task ElementsWithOpacityZeroShouldNotBeVisible() { await driver.GoToUrl(clickJackerPage); IWebElement element = await driver.FindElement(By.Id("clickJacker")); Assert.That(await element.Displayed(), Is.False); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// SyncListPermissionResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Preview.Sync.Service.SyncList { public class SyncListPermissionResource : Resource { private static Request BuildFetchRequest(FetchSyncListPermissionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a specific Sync List Permission. /// </summary> /// <param name="options"> Fetch SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static SyncListPermissionResource Fetch(FetchSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a specific Sync List Permission. /// </summary> /// <param name="options"> Fetch SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<SyncListPermissionResource> FetchAsync(FetchSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a specific Sync List Permission. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static SyncListPermissionResource Fetch(string pathServiceSid, string pathListSid, string pathIdentity, ITwilioRestClient client = null) { var options = new FetchSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a specific Sync List Permission. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<SyncListPermissionResource> FetchAsync(string pathServiceSid, string pathListSid, string pathIdentity, ITwilioRestClient client = null) { var options = new FetchSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteSyncListPermissionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific Sync List Permission. /// </summary> /// <param name="options"> Delete SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static bool Delete(DeleteSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific Sync List Permission. /// </summary> /// <param name="options"> Delete SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific Sync List Permission. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static bool Delete(string pathServiceSid, string pathListSid, string pathIdentity, ITwilioRestClient client = null) { var options = new DeleteSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific Sync List Permission. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathListSid, string pathIdentity, ITwilioRestClient client = null) { var options = new DeleteSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity); return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadSyncListPermissionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Permissions applying to a Sync List. /// </summary> /// <param name="options"> Read SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static ResourceSet<SyncListPermissionResource> Read(ReadSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<SyncListPermissionResource>.FromJson("permissions", response.Content); return new ResourceSet<SyncListPermissionResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Permissions applying to a Sync List. /// </summary> /// <param name="options"> Read SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<ResourceSet<SyncListPermissionResource>> ReadAsync(ReadSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<SyncListPermissionResource>.FromJson("permissions", response.Content); return new ResourceSet<SyncListPermissionResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Permissions applying to a Sync List. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static ResourceSet<SyncListPermissionResource> Read(string pathServiceSid, string pathListSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSyncListPermissionOptions(pathServiceSid, pathListSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Permissions applying to a Sync List. /// </summary> /// <param name="pathServiceSid"> The service_sid </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<ResourceSet<SyncListPermissionResource>> ReadAsync(string pathServiceSid, string pathListSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSyncListPermissionOptions(pathServiceSid, pathListSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<SyncListPermissionResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<SyncListPermissionResource>.FromJson("permissions", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<SyncListPermissionResource> NextPage(Page<SyncListPermissionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SyncListPermissionResource>.FromJson("permissions", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<SyncListPermissionResource> PreviousPage(Page<SyncListPermissionResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SyncListPermissionResource>.FromJson("permissions", response.Content); } private static Request BuildUpdateRequest(UpdateSyncListPermissionOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/Sync/Services/" + options.PathServiceSid + "/Lists/" + options.PathListSid + "/Permissions/" + options.PathIdentity + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update an identity's access to a specific Sync List. /// </summary> /// <param name="options"> Update SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static SyncListPermissionResource Update(UpdateSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update an identity's access to a specific Sync List. /// </summary> /// <param name="options"> Update SyncListPermission parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<SyncListPermissionResource> UpdateAsync(UpdateSyncListPermissionOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update an identity's access to a specific Sync List. /// </summary> /// <param name="pathServiceSid"> Sync Service Instance SID. </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="read"> Read access. </param> /// <param name="write"> Write access. </param> /// <param name="manage"> Manage access. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of SyncListPermission </returns> public static SyncListPermissionResource Update(string pathServiceSid, string pathListSid, string pathIdentity, bool? read, bool? write, bool? manage, ITwilioRestClient client = null) { var options = new UpdateSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity, read, write, manage); return Update(options, client); } #if !NET35 /// <summary> /// Update an identity's access to a specific Sync List. /// </summary> /// <param name="pathServiceSid"> Sync Service Instance SID. </param> /// <param name="pathListSid"> Sync List SID or unique name. </param> /// <param name="pathIdentity"> Identity of the user to whom the Sync List Permission applies. </param> /// <param name="read"> Read access. </param> /// <param name="write"> Write access. </param> /// <param name="manage"> Manage access. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of SyncListPermission </returns> public static async System.Threading.Tasks.Task<SyncListPermissionResource> UpdateAsync(string pathServiceSid, string pathListSid, string pathIdentity, bool? read, bool? write, bool? manage, ITwilioRestClient client = null) { var options = new UpdateSyncListPermissionOptions(pathServiceSid, pathListSid, pathIdentity, read, write, manage); return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a SyncListPermissionResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> SyncListPermissionResource object represented by the provided JSON </returns> public static SyncListPermissionResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<SyncListPermissionResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// Twilio Account SID. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// Sync Service Instance SID. /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// Sync List SID. /// </summary> [JsonProperty("list_sid")] public string ListSid { get; private set; } /// <summary> /// Identity of the user to whom the Sync List Permission applies. /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// Read access. /// </summary> [JsonProperty("read")] public bool? _Read { get; private set; } /// <summary> /// Write access. /// </summary> [JsonProperty("write")] public bool? Write { get; private set; } /// <summary> /// Manage access. /// </summary> [JsonProperty("manage")] public bool? Manage { get; private set; } /// <summary> /// URL of this Sync List Permission. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private SyncListPermissionResource() { } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Api.V2010.Account.AvailablePhoneNumberCountry { /// <summary> /// ReadNationalOptions /// </summary> public class ReadNationalOptions : ReadOptions<NationalResource> { /// <summary> /// The SID of the Account requesting the AvailablePhoneNumber resources /// </summary> public string PathAccountSid { get; set; } /// <summary> /// The ISO Country code of the country from which to read phone numbers /// </summary> public string PathCountryCode { get; } /// <summary> /// The area code of the phone numbers to read /// </summary> public int? AreaCode { get; set; } /// <summary> /// The pattern on which to match phone numbers /// </summary> public string Contains { get; set; } /// <summary> /// Whether the phone numbers can receive text messages /// </summary> public bool? SmsEnabled { get; set; } /// <summary> /// Whether the phone numbers can receive MMS messages /// </summary> public bool? MmsEnabled { get; set; } /// <summary> /// Whether the phone numbers can receive calls. /// </summary> public bool? VoiceEnabled { get; set; } /// <summary> /// Whether to exclude phone numbers that require an Address /// </summary> public bool? ExcludeAllAddressRequired { get; set; } /// <summary> /// Whether to exclude phone numbers that require a local address /// </summary> public bool? ExcludeLocalAddressRequired { get; set; } /// <summary> /// Whether to exclude phone numbers that require a foreign address /// </summary> public bool? ExcludeForeignAddressRequired { get; set; } /// <summary> /// Whether to read phone numbers new to the Twilio platform /// </summary> public bool? Beta { get; set; } /// <summary> /// Given a phone number, find a geographically close number within distance miles. (US/Canada only) /// </summary> public Types.PhoneNumber NearNumber { get; set; } /// <summary> /// Given a latitude/longitude pair lat,long find geographically close numbers within distance miles. (US/Canada only) /// </summary> public string NearLatLong { get; set; } /// <summary> /// The search radius, in miles, for a near_ query. (US/Canada only) /// </summary> public int? Distance { get; set; } /// <summary> /// Limit results to a particular postal code. (US/Canada only) /// </summary> public string InPostalCode { get; set; } /// <summary> /// Limit results to a particular region. (US/Canada only) /// </summary> public string InRegion { get; set; } /// <summary> /// Limit results to a specific rate center, or given a phone number search within the same rate center as that number. (US/Canada only) /// </summary> public string InRateCenter { get; set; } /// <summary> /// Limit results to a specific local access and transport area. (US/Canada only) /// </summary> public string InLata { get; set; } /// <summary> /// Limit results to a particular locality /// </summary> public string InLocality { get; set; } /// <summary> /// Whether the phone numbers can receive faxes /// </summary> public bool? FaxEnabled { get; set; } /// <summary> /// Construct a new ReadNationalOptions /// </summary> /// <param name="pathCountryCode"> The ISO Country code of the country from which to read phone numbers </param> public ReadNationalOptions(string pathCountryCode) { PathCountryCode = pathCountryCode; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (AreaCode != null) { p.Add(new KeyValuePair<string, string>("AreaCode", AreaCode.ToString())); } if (Contains != null) { p.Add(new KeyValuePair<string, string>("Contains", Contains)); } if (SmsEnabled != null) { p.Add(new KeyValuePair<string, string>("SmsEnabled", SmsEnabled.Value.ToString().ToLower())); } if (MmsEnabled != null) { p.Add(new KeyValuePair<string, string>("MmsEnabled", MmsEnabled.Value.ToString().ToLower())); } if (VoiceEnabled != null) { p.Add(new KeyValuePair<string, string>("VoiceEnabled", VoiceEnabled.Value.ToString().ToLower())); } if (ExcludeAllAddressRequired != null) { p.Add(new KeyValuePair<string, string>("ExcludeAllAddressRequired", ExcludeAllAddressRequired.Value.ToString().ToLower())); } if (ExcludeLocalAddressRequired != null) { p.Add(new KeyValuePair<string, string>("ExcludeLocalAddressRequired", ExcludeLocalAddressRequired.Value.ToString().ToLower())); } if (ExcludeForeignAddressRequired != null) { p.Add(new KeyValuePair<string, string>("ExcludeForeignAddressRequired", ExcludeForeignAddressRequired.Value.ToString().ToLower())); } if (Beta != null) { p.Add(new KeyValuePair<string, string>("Beta", Beta.Value.ToString().ToLower())); } if (NearNumber != null) { p.Add(new KeyValuePair<string, string>("NearNumber", NearNumber.ToString())); } if (NearLatLong != null) { p.Add(new KeyValuePair<string, string>("NearLatLong", NearLatLong)); } if (Distance != null) { p.Add(new KeyValuePair<string, string>("Distance", Distance.ToString())); } if (InPostalCode != null) { p.Add(new KeyValuePair<string, string>("InPostalCode", InPostalCode)); } if (InRegion != null) { p.Add(new KeyValuePair<string, string>("InRegion", InRegion)); } if (InRateCenter != null) { p.Add(new KeyValuePair<string, string>("InRateCenter", InRateCenter)); } if (InLata != null) { p.Add(new KeyValuePair<string, string>("InLata", InLata)); } if (InLocality != null) { p.Add(new KeyValuePair<string, string>("InLocality", InLocality)); } if (FaxEnabled != null) { p.Add(new KeyValuePair<string, string>("FaxEnabled", FaxEnabled.Value.ToString().ToLower())); } if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Reflection; using System.IO; using System.Windows.Forms; using Tilde.Framework.Controller; using Tilde.Framework.Model; using Tilde.Framework.Model.ProjectHierarchy; using Tilde.Framework.View; using System.Text.RegularExpressions; using WeifenLuo.WinFormsUI.Docking; using Tilde.Framework; using System.Diagnostics; using Tilde.Framework.Controls; using Microsoft.Win32; namespace Tilde.TildeApp { public class Manager : IManager { private RegistryKey mRegistryRoot; private List<Assembly> mAssemblies; private List<string> mPluginPath; private PluginCollection mPlugins; private Project mProject; private List<Document> mOpenDocuments; private Dictionary<string, Type> mFileTypes; private MainWindow mMainWindow; private Document mActiveDocument; private object[] mSelection; private FileWatcher mFileWatcher; private OptionsManager mOptionsManager; private ApplicationOptions mApplicationOptions; private bool m_closing = false; public Manager(CommandLineArguments args) { mAssemblies = new List<Assembly>(); mPlugins = new PluginCollection(); mOpenDocuments = new List<Document>(); mFileTypes = new Dictionary<string, Type>(); mActiveDocument = null; mFileWatcher = new FileWatcher(); mFileWatcher.FileModified += new FileModifiedEventHandler(FileWatcher_FileModified); mFileWatcher.FileAttributesChanged += new FileAttributesChangedEventHandler(FileWatcher_FileAttributesChanged); mOptionsManager = new OptionsManager(this); mApplicationOptions = new ApplicationOptions(); mOptionsManager.Options.Add(mApplicationOptions); mAssemblies.Add(Assembly.GetExecutingAssembly()); mPluginPath = new List<string>(); string currentDirectory = System.IO.Directory.GetCurrentDirectory(); string exeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); mPluginPath.Add(currentDirectory); if(currentDirectory != exeDirectory) mPluginPath.Add(exeDirectory); foreach (string path in args.GetValues("--pluginFolder")) mPluginPath.Add(path); foreach (string path in mPluginPath) { FindPlugins(path); } mRegistryRoot = Registry.CurrentUser.OpenSubKey("Software\\Tantalus\\Tilde", true); if (mRegistryRoot == null) mRegistryRoot = Registry.CurrentUser.CreateSubKey("Software\\Tantalus\\Tilde"); CreatePlugins(); } public event PropertyChangeEventHandler PropertyChange; public event ProjectOpenedEventHandler ProjectOpened; public event ProjectClosingEventHandler ProjectClosing; public event ProjectClosedEventHandler ProjectClosed; public event ManagerDocumentOpenedEventHandler DocumentOpened; public event ManagerDocumentClosedEventHandler DocumentClosed; public event ActiveDocumentChangedEventHandler ActiveDocumentChanged; public event SelectionChangedEventHandler SelectionChanged; public event FindInFilesStartedEventHandler FindInFilesStarted; public event FindInFilesResultEventHandler FindInFilesResult; public event FindInFilesStoppedEventHandler FindInFilesStopped; public event GoToNextLocationEventHandler GoToNextLocation; public event GoToPreviousLocationEventHandler GoToPreviousLocation; public RegistryKey RegistryRoot { get { return mRegistryRoot; } } public List<Assembly> Assemblies { get { return mAssemblies; } } public PluginCollection Plugins { get { return mPlugins; } } public Project Project { get { return mProject; } } public Form MainWindow { get { return mMainWindow; } set { mMainWindow = (MainWindow) value; InitialisePlugins(); } } public Document ActiveDocument { get { return mActiveDocument; } set { if (mActiveDocument != value) { mActiveDocument = value; OnActiveDocumentChanged(); } } } public DocumentView ActiveView { get { return mMainWindow.ActiveView; } } public DockPanel DockPanel { get { return mMainWindow.DockPanel; } } public ReadOnlyCollection<Document> OpenDocuments { get { return mOpenDocuments.AsReadOnly(); } } public FileWatcher FileWatcher { get { return mFileWatcher; } } public OptionsManager OptionsManager { get { return mOptionsManager; } } public ApplicationOptions ApplicationOptions { get { return mApplicationOptions; } } public bool IsClosing { get { return m_closing; } } public ReadOnlyCollection<Document> Documents { get { return mOpenDocuments.AsReadOnly(); } } public ReadOnlyCollection<DocumentView> DocumentViews { get { return mMainWindow.DocumentViews; } } public object SelectedObject { get { if (mSelection != null && mSelection.Length > 0) return mSelection[0]; else return null; } set { if(mSelection == null || mSelection.Length != 1 || mSelection[0] != value) { mSelection = value == null ? null : new object[1] { value }; OnSelectionChanged(); } } } public object [] SelectedObjects { get { return mSelection; } set { if (mSelection != value) { mSelection = value; OnSelectionChanged(); } } } #region Projects private Type FindProjectLoader(string fileName) { foreach (Type projType in GetPluginImplementations(typeof(Project))) { MethodInfo method = (MethodInfo) projType.GetMember("CanLoad")[0]; if (method != null && method.IsStatic) { bool result = (bool)method.Invoke(null, new object[] { fileName }); if (result) return projType; } } return null; } public bool LoadProject(string fileName) { if (mProject != null && !CloseProject(false)) return false; Type projType = FindProjectLoader(fileName); if (projType == null) throw new ApplicationException("Couldn't find loader for project: " + fileName); mProject = (Project)Activator.CreateInstance(projType, new object[] { this, fileName }); if(mProject.VCSType == "") { if(MessageBoxEx.Show(MainWindow, "Source control has not been configured for this project. Would you like to configure it now?", "Source control configuration", new string [] {"Yes", "No"}, MessageBoxIcon.Question, "Yes" ) == "Yes") { SourceControlWindow window = new SourceControlWindow(this); window.ShowDialog(MainWindow); } } try { // Plugins might fail here OnProjectOpened(); OnPropertyChange(this, "Project", null, mProject); } catch (System.Exception e) { DestroyProject(); throw e; } return true; } public bool NewProject(Type projType) { if (mProject != null && !CloseProject(false)) return false; mProject = (Project)Activator.CreateInstance(projType, new object[] { this }); try { // Plugins might fail here OnProjectOpened(); OnPropertyChange(this, "Project", null, mProject); } catch (System.Exception e) { DestroyProject(); throw e; } return true; } public bool CloseProject(bool force) { if (mProject == null) throw new NullReferenceException("Attempt to close non-existent project"); m_closing = true; try { //.Let the listeners know the project is closing and give them a chance to cancel it if (OnProjectClosing(false) && !force) return false; if (!CloseAllDocuments(false) && !force) { // Tell the listeners the project didn't actually get closed after all OnProjectClosing(true); return false; } mProject.SaveUserConfig(); Project oldproject = mProject; DestroyProject(); OnProjectClosed(); OnPropertyChange(this, "Project", oldproject, null); } finally { m_closing = false; } return true; } private void DestroyProject() { if (mProject != null) { mProject = null; } } #endregion #region Plugins public IPlugin GetPlugin(Type type) { foreach (PluginDetails plugin in mPlugins) { if (plugin.Plugin != null && type.IsAssignableFrom(plugin.Plugin.GetType())) return plugin.Plugin; } return null; } public List<Type> GetPluginImplementations(Type interfaceType) { List<Type> result = new List<Type>(); foreach (PluginDetails details in mPlugins) { if (details.Assembly != null) { foreach (Type type in details.Assembly.GetTypes()) { if (interfaceType.IsAssignableFrom(type) && type != interfaceType && !type.IsAbstract) { result.Add(type); } } } } return result; } private void FindPlugins(string folder) { foreach(string path in Directory.GetFiles(folder, "*.plugin.dll")) { string name = Path.GetFileNameWithoutExtension(Path.GetFileNameWithoutExtension(path)); PluginDetails details = new PluginDetails(name, path); if (OptionsManager.RegistryDatabase.GetBooleanOption("Application/Plugins/" + name, true)) { try { LoadPluginInternal(details); } catch (System.Exception e) { DialogResult result = System.Windows.Forms.MessageBox.Show( "Tilde could not load the plugin:\r\n\t" + details.Path + "\r\n\r\n" + e.Message + "\r\n\r\nDo you want Tilde to attempt to load it next time?", "Plugin load error", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if(result == DialogResult.No) OptionsManager.RegistryDatabase.SetBooleanOption("Application/Plugins/" + name, false); } } } } public void LoadPlugin(PluginDetails plugin) { } /// <summary> /// Loads the assembly and looks for a class of type IPlugin. /// </summary> /// <param name="plugin">Plugin to load.</param> /// <returns>True if the assembly loaded correctly and contains a valid Tilde plugin.</returns> /// <remarks>Throws an exception if loading the assembly failed.</remarks> private bool LoadPluginInternal(PluginDetails plugin) { Assembly assembly = Assembly.LoadFile(plugin.Path); foreach(PluginDetails details in mPlugins) { if (details.Assembly.FullName == assembly.FullName) return false; } foreach (Type type in assembly.GetTypes()) { if (typeof(IPlugin).IsAssignableFrom(type) && type != typeof(IPlugin)) { plugin.Assembly = assembly; mAssemblies.Add(assembly); mPlugins.Add(plugin); return true; } } return false; } private void CreatePlugins() { foreach (PluginDetails details in mPlugins) { if (details.Assembly != null && details.Plugin == null) { foreach (Type type in details.Assembly.GetTypes()) { if (typeof(IPlugin).IsAssignableFrom(type) && type.IsClass) { IPlugin plugin = Activator.CreateInstance(type) as IPlugin; details.Plugin = plugin; } } } } } private void InitialisePlugins() { foreach (PluginDetails details in mPlugins) { if (details.Plugin != null) { details.Plugin.Initialise(this); } } foreach (Type docType in GetPluginImplementations(typeof(Document))) { DocumentClassAttribute attr = DocumentClassAttribute.ForType(docType); if (attr != null) { foreach (string docExt in attr.FileExtensions) { mFileTypes[docExt] = docType; } } } } public int Execute(string logtype, string cmd) { return Execute(logtype, cmd, null); } public int Execute(string logtype, string cmd, StringBuilder output) { Process process = new Process(); process.StartInfo.WorkingDirectory = Project.Documents[0].BaseDirectory; process.StartInfo.CreateNoWindow = true; process.StartInfo.ErrorDialog = false; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.FileName = "cmd"; process.StartInfo.Arguments = "/c " + cmd + " 2>&1"; try { AddMessage(logtype, "Executing \"" + process.StartInfo.FileName + " " + process.StartInfo.Arguments + "\"\n"); process.Start(); while(!process.StandardOutput.EndOfStream) { string line = process.StandardOutput.ReadLine() + "\n"; if (output != null) output.Append(line); AddMessage(logtype, line); } AddMessage(logtype, "\nExit code " + process.ExitCode.ToString() + "\n"); return process.ExitCode; } catch (Exception ex) { AddMessage(logtype, ex.ToString()); return -1; } } #endregion #region Documents public Document FindOpenDocument(string fileName) { System.Diagnostics.Debug.Assert(Path.IsPathRooted(fileName)); return mOpenDocuments.Find(delegate(Document item) { return PathUtils.Compare(item.FileName, fileName) == 0; }); } public Document CreateDocument(string fileName) { return CreateDocument(fileName, null, null, null); } public Document CreateDocument(string fileName, Type docType) { return CreateDocument(fileName, docType, null, null); } public Document CreateDocument(string fileName, Type docType, Stream stream) { return CreateDocument(fileName, docType, stream, null); } /// <summary> /// Creates a new (unsaved) Document by loading it from the specified Stream, rather than a file on disk. /// </summary> /// <param name="fileName">Absolute filename of new document.</param> /// <param name="docType">Type of document to create.</param> /// <param name="stream">Stream from which to load the document's contents.</param> /// <returns></returns> public Document CreateDocument(string fileName, Type docType, Stream stream, object[] args) { // Change it to a unique (not open) name while (FindOpenDocument(fileName) != null) { string name = Path.GetFileName(fileName); int dotpos = name.IndexOf('.'); string fileBase, fileExt; if (dotpos >= 0) { fileBase = name.Substring(0, dotpos); fileExt = name.Substring(dotpos, name.Length - dotpos); } else { fileBase = name; fileExt = ""; } Regex regex = new Regex("(.*)\\[(\\d+)\\]$"); Match match = regex.Match(fileBase); if(match.Success) { int val; if(!Int32.TryParse(match.Groups[2].Value, out val)) val = 1; fileBase = match.Groups[1].Value + "[" + (val + 1).ToString() + "]"; } else { fileBase = fileBase + "[2]"; } fileName = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + fileBase + fileExt; } if(docType == null) { docType = FindDocumentType(fileName); } Document doc; try { doc = CreateAndLoadDocument(fileName, docType, stream, args); } catch (Exception ex) { DialogResult result = MessageBox.Show(MainWindow, "There was an error opening the document '" + fileName + "':\r\n\r\n" + ex.ToString() + "\r\n\r\nWould you like to try opening it as a text document?", "Error opening document", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error); if(result == DialogResult.Cancel) return null; else { try { stream.Seek(0, SeekOrigin.Begin); doc = CreateAndLoadDocument(fileName, FindDocumentType(".txt"), stream, null); } catch (Exception ex2) { MessageBox.Show(MainWindow, ex2.ToString(), "Error opening document:", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } } } mOpenDocuments.Add(doc); mFileWatcher.AddFile(fileName); OnDocumentOpened(doc); return doc; } private Document CreateAndLoadDocument(string fileName, Type docType, Stream stream, object [] args) { Document doc = CreateDocumentInstance(fileName, docType, args); doc.NewDocument(stream); mOpenDocuments.Add(doc); OnDocumentOpened(doc); return doc; } public Document OpenDocument(DocumentItem docItem) { return OpenDocument(docItem.AbsoluteFileName, docItem.DocumentType); } public Document OpenDocument(string fileName) { return OpenDocument(fileName, null, null); } public Document OpenDocument(string fileName, Type docType) { return OpenDocument(fileName, docType, null); } /// <summary> /// Creates a Document for a file and loads it. /// </summary> /// <param name="fileName">The name of the file to open; it must be an absolute filename.</param> /// <param name="docType">The type of Document to instantiate, or null to guess the document type.</param> /// <param name="args">Any extra arguments to pass to the Document constructor.</param> /// <returns></returns> public Document OpenDocument(string fileName, Type docType, object [] args) { System.Diagnostics.Debug.Assert(Path.IsPathRooted(fileName), "Absolute path names required"); System.Diagnostics.Debug.Assert(args == null || docType != null, "Can't pass extra constructor arguments when guessing document type"); // Check if it's open already Document doc = FindOpenDocument(fileName); if (doc == null || (docType != null && !docType.IsAssignableFrom(doc.GetType()))) { // We need to open it then, but check if it actually exists first if (!System.IO.File.Exists(fileName)) return null; // Find out its type // Look in the project hierarchy if (docType == null && mProject != null) { DocumentItem docItem = mProject.FindDocument(fileName); if (docItem != null) { docType = docItem.DocumentType; } } // Try to choose one if(docType == null) { docType = FindDocumentType(fileName); } if (docType == null) return null; doc = CreateDocumentInstance(fileName, docType, args); doc.LoadDocument(); mOpenDocuments.Add(doc); mFileWatcher.AddFile(fileName); OnDocumentOpened(doc); } return doc; } private Document CreateDocumentInstance(string fileName, Type docType, object[] args) { object[] fullargs; if (args == null) fullargs = new object[2]; else { fullargs = new object[2 + args.Length]; Array.Copy(args, 0, fullargs, 2, args.Length); } fullargs[0] = this; fullargs[1] = fileName; Document doc = (Document)Activator.CreateInstance(docType, fullargs); doc.Saving += new DocumentSavingEventHandler(Document_Saving); doc.Saved += new DocumentSavedEventHandler(Document_Saved); doc.PropertyChange += new PropertyChangeEventHandler(Document_PropertyChange); doc.ExternallyModified += new DocumentExternallyModifiedEventHandler(Document_ExternallyModified); return doc; } // Reflect messages from Documents to our listeners void Document_PropertyChange(object sender, PropertyChangeEventArgs args) { if (PropertyChange != null) PropertyChange(sender, args); } void Document_Saving(Document sender) { mFileWatcher.EnableFile(sender.FileName, false); } void Document_Saved(Document sender, bool success) { mFileWatcher.EnableFile(sender.FileName, true); } void Document_ExternallyModified(Document doc) { DialogResult result; if (doc.Modified) { result = MessageBox.Show( MainWindow, String.Format("The file\r\n\r\n{0}\r\n\r\nhas been externally modified, however there are also unsaved changes in the editor. Do you want to reload it and discard your changes?", doc.FileName), "File Modification Detected", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); } else if (!ApplicationOptions.AutomaticallyReloadModifiedFiles) { result = MessageBox.Show( MainWindow, String.Format("The file\r\n\r\n{0}\r\n\r\nhas been externally modified. Do you want to reload it?", doc.FileName), "File Modification Detected", MessageBoxButtons.YesNo, MessageBoxIcon.Question); } else { result = DialogResult.Yes; } if (result == DialogResult.Yes) { doc.LoadDocument(); SetStatusMessage("Automatically reloaded " + doc.FileName, 10.0f); } } void FileWatcher_FileModified(object sender, string fileName) { if (MainWindow.InvokeRequired && MainWindow.IsHandleCreated && !MainWindow.IsDisposed) MainWindow.BeginInvoke(new FileModifiedEventHandler(FileWatcher_FileModified), new object[] { sender, fileName }); else { Document doc = FindOpenDocument(fileName); if (doc != null) doc.OnExternallyModified(); } } void FileWatcher_FileAttributesChanged(object sender, string fileName, FileAttributes oldAttr, FileAttributes newAttr) { if (MainWindow.InvokeRequired && MainWindow.IsHandleCreated && !MainWindow.IsDisposed) MainWindow.BeginInvoke(new FileAttributesChangedEventHandler(FileWatcher_FileAttributesChanged), new object[] { sender, fileName, oldAttr, newAttr }); else { Document doc = FindOpenDocument(fileName); if (doc != null && File.Exists(fileName)) { try { FileAttributes attr = File.GetAttributes(fileName); doc.ReadOnly = (attr & FileAttributes.ReadOnly) != 0; } catch (Exception) { } } } } private bool CheckCloseDocument(Document doc) { if (doc.Modified) { if (MessageBoxEx.Show(mMainWindow, "The file\r\n\r\n" + doc.FileName + "\r\n\r\nhas been modified; do you really want to close it?", "Are you sure?", new string[] { "Close", "Cancel" }, MessageBoxIcon.Exclamation, "Cancel") == "Cancel") return false; } return true; } private void ForceCloseDocument(Document doc) { doc.CloseDocument(); mOpenDocuments.Remove(doc); mFileWatcher.RemoveFile(doc.FileName); OnDocumentClosed(doc); } public bool CloseDocument(Document doc, bool force) { if (force || CheckCloseDocument(doc)) { ForceCloseDocument(doc); return true; } else return false; } // Returns true if all documents closed, false otherwise (and no documents closed) public bool CloseAllDocuments(bool force) { // Check all documents first if (!force) { foreach (Document doc in mOpenDocuments) { if (!CheckCloseDocument(doc)) return false; } } // If they are all allowed to be closed, then force-close them while (mOpenDocuments.Count > 0) { ForceCloseDocument(mOpenDocuments[mOpenDocuments.Count - 1]); } return true; } public int SaveProject() { if (Project != null) Project.SaveUserConfig(); return SaveAllDocuments(typeof(ProjectDocument)); } public int SaveAllDocuments() { if (Project != null) Project.SaveUserConfig(); return SaveAllDocuments(typeof(Document)); } public int SaveAllDocuments(Type docType) { int count = 0; foreach (Document doc in OpenDocuments) { if (docType.IsAssignableFrom(doc.GetType()) && doc.Modified) { if (mMainWindow.SaveDocument(doc, false)) ++count; } } if (count == 0) SetStatusMessage("No modified files", 5.0f); else SetStatusMessage(String.Format("Saved {0} file(s)", count), 5.0f); return count; } public Type FindFileDocumentType(string docName) { return FindDocumentType(docName); } internal Type FindDocumentType(string fileName) { Type result; fileName = Path.GetFileName(fileName); int dotIndex = -1; do { dotIndex = fileName.IndexOf(".", dotIndex + 1); if (dotIndex < 0) break; if (mFileTypes.TryGetValue(fileName.Substring(dotIndex), out result)) { return result; } } while (true); if (mFileTypes.TryGetValue(".*", out result)) { return result; } return null; } public DocumentView ShowDocument(DocumentItem docItem) { return ShowDocument(docItem.AbsoluteFileName); } public DocumentView ShowDocument(string fileName) { Document doc = OpenDocument(fileName); DocumentView view = (doc == null) ? null : mMainWindow.ShowDocument(doc); if(view == null) MessageBox.Show(mMainWindow, "The document '" + fileName + "'could not be opened.", "Load Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return view; } public DocumentView ShowDocument(Document doc) { return mMainWindow.ShowDocument(doc); } #endregion #region User Interface public ToolWindow GetToolWindow(Type type) { return mMainWindow.GetToolWindow(type); } public void AddToMenuStrip(ToolStripItemCollection source) { MergeMenu(source, mMainWindow.menuStrip.Items); } private void MergeMenu(ToolStripItemCollection source, ToolStripItemCollection dest) { while(source.Count > 0) { ToolStripMenuItem item = (ToolStripMenuItem) source[0]; if(item.MergeAction == MergeAction.Insert) { for(int index = 0; index < dest.Count; ++index) { if(dest[index].MergeIndex > item.MergeIndex) { dest.Insert(index, item); break; } } } else if (item.MergeAction == MergeAction.Append) { dest.Add(item); } else if (item.MergeAction == MergeAction.MatchOnly) { ToolStripMenuItem match = null; foreach(ToolStripMenuItem destitem in dest) { if(destitem.Text == item.Text) { match = destitem; break; } } if(match == null) throw new ApplicationException("Can't merge with nonexistent menu '" + item.Text + "'"); MergeMenu(item.DropDownItems, match.DropDownItems); source.Remove(item); } else { throw new ApplicationException("Unsupported menu merge action"); } } } public void AddToStatusStrip(ToolStripItemCollection toolStripItemCollection) { mMainWindow.statusStrip.Items.AddRange(toolStripItemCollection); } public void AddToolStrip(ToolStrip toolStrip, DockStyle side, int row) { if(side == DockStyle.Top) mMainWindow.toolStripPanelTop.Join(toolStrip, row); else if (side == DockStyle.Left) mMainWindow.toolStripPanelLeft.Join(toolStrip, row); else if (side == DockStyle.Right) mMainWindow.toolStripPanelRight.Join(toolStrip, row); else if (side == DockStyle.Bottom) mMainWindow.toolStripPanelBottom.Join(toolStrip, row); } public void SetStatusMessage(String message, float duration) { mMainWindow.SetStatusMessage(message, duration); } public void SetProgressBar(int progress) { mMainWindow.SetProgressBar(progress); } public void StartProgressBarMarquee() { mMainWindow.StartProgressBarMarquee(); } public void StopProgressBarMarquee() { mMainWindow.StopProgressBarMarquee(); } public void FlashMainWindow() { Win32.FlashWindow(mMainWindow.Handle); mMainWindow.Activate(); } public void ShowMessages(string type) { OutputPanel outputPanel = (OutputPanel)mMainWindow.GetToolWindow(typeof(OutputPanel)); outputPanel.Invoke(new MethodInvoker(delegate() { outputPanel.ShowLog(type); outputPanel.Show(mMainWindow.DockPanel); })); } public void AddMessage(string type, string message) { OutputPanel outputPanel = (OutputPanel) mMainWindow.GetToolWindow(typeof(OutputPanel)); outputPanel.Invoke(new MethodInvoker(delegate() { outputPanel.AddMessage(type, message); } )); } #endregion private void OnPropertyChange(object sender, string property, object oldValue, object newValue) { if (PropertyChange != null) PropertyChange(sender, new PropertyChangeEventArgs(property, oldValue, newValue)); } private void OnProjectOpened() { if (ProjectOpened != null) ProjectOpened(this, mProject); } private bool OnProjectClosing(bool cancelled) { if (ProjectClosing != null) { ProjectClosingEventArgs args = new ProjectClosingEventArgs(mProject, cancelled); ProjectClosing(this, args); return args.Cancel; } return false; } private void OnProjectClosed() { if (ProjectClosed != null) ProjectClosed(this); } private void OnDocumentOpened(Document doc) { if (DocumentOpened != null) DocumentOpened(this, doc); } private void OnDocumentClosed(Document doc) { if (DocumentClosed != null) DocumentClosed(this, doc); } private void OnActiveDocumentChanged() { if (ActiveDocumentChanged != null) ActiveDocumentChanged(this, mActiveDocument); } private void OnSelectionChanged() { if (SelectionChanged != null) SelectionChanged(this, mSelection); } public void OnFindInFilesStarted(object sender, string message) { if (FindInFilesStarted != null) FindInFilesStarted(sender, message); } public void OnFindInFilesResult(object sender, FindInFilesResultEventArgs args) { if (FindInFilesResult != null) FindInFilesResult(sender, args); } public void OnFindInFilesStopped(object sender, string message) { if (FindInFilesStopped != null) FindInFilesStopped(sender, message); } public void OnGoToNextLocation() { if (GoToNextLocation != null) { foreach (GoToNextLocationEventHandler del in ((MulticastDelegate)GoToNextLocation).GetInvocationList()) { bool consumed = false; del(this, ref consumed); if (consumed) break; } } } public void OnGoToPreviousLocation() { if (GoToPreviousLocation != null) { foreach (GoToPreviousLocationEventHandler del in ((MulticastDelegate)GoToPreviousLocation).GetInvocationList()) { bool consumed = false; del(this, ref consumed); if (consumed) break; } } } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Supports creation and modification of menus. See cef_menu_id_t for the /// command ids that have default implementations. All user-defined command ids /// should be between MENU_ID_USER_FIRST and MENU_ID_USER_LAST. The methods of /// this class can only be accessed on the browser process the UI thread. /// </summary> public sealed unsafe partial class CefMenuModel { /// <summary> /// Create a new MenuModel with the specified |delegate|. /// </summary> public static cef_menu_model_t* CreateMenuModel(cef_menu_model_delegate_t* @delegate) { throw new NotImplementedException(); // TODO: CefMenuModel.CreateMenuModel } /// <summary> /// Clears the menu. Returns true on success. /// </summary> public int Clear() { throw new NotImplementedException(); // TODO: CefMenuModel.Clear } /// <summary> /// Returns the number of items in this menu. /// </summary> public int GetCount() { throw new NotImplementedException(); // TODO: CefMenuModel.GetCount } /// <summary> /// Add a separator to the menu. Returns true on success. /// </summary> public int AddSeparator() { throw new NotImplementedException(); // TODO: CefMenuModel.AddSeparator } /// <summary> /// Add an item to the menu. Returns true on success. /// </summary> public int AddItem(int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.AddItem } /// <summary> /// Add a check item to the menu. Returns true on success. /// </summary> public int AddCheckItem(int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.AddCheckItem } /// <summary> /// Add a radio item to the menu. Only a single item with the specified /// |group_id| can be checked at a time. Returns true on success. /// </summary> public int AddRadioItem(int command_id, cef_string_t* label, int group_id) { throw new NotImplementedException(); // TODO: CefMenuModel.AddRadioItem } /// <summary> /// Add a sub-menu to the menu. The new sub-menu is returned. /// </summary> public cef_menu_model_t* AddSubMenu(int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.AddSubMenu } /// <summary> /// Insert a separator in the menu at the specified |index|. Returns true on /// success. /// </summary> public int InsertSeparatorAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.InsertSeparatorAt } /// <summary> /// Insert an item in the menu at the specified |index|. Returns true on /// success. /// </summary> public int InsertItemAt(int index, int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.InsertItemAt } /// <summary> /// Insert a check item in the menu at the specified |index|. Returns true on /// success. /// </summary> public int InsertCheckItemAt(int index, int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.InsertCheckItemAt } /// <summary> /// Insert a radio item in the menu at the specified |index|. Only a single /// item with the specified |group_id| can be checked at a time. Returns true /// on success. /// </summary> public int InsertRadioItemAt(int index, int command_id, cef_string_t* label, int group_id) { throw new NotImplementedException(); // TODO: CefMenuModel.InsertRadioItemAt } /// <summary> /// Insert a sub-menu in the menu at the specified |index|. The new sub-menu /// is returned. /// </summary> public cef_menu_model_t* InsertSubMenuAt(int index, int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.InsertSubMenuAt } /// <summary> /// Removes the item with the specified |command_id|. Returns true on success. /// </summary> public int Remove(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.Remove } /// <summary> /// Removes the item at the specified |index|. Returns true on success. /// </summary> public int RemoveAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.RemoveAt } /// <summary> /// Returns the index associated with the specified |command_id| or -1 if not /// found due to the command id not existing in the menu. /// </summary> public int GetIndexOf(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.GetIndexOf } /// <summary> /// Returns the command id at the specified |index| or -1 if not found due to /// invalid range or the index being a separator. /// </summary> public int GetCommandIdAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.GetCommandIdAt } /// <summary> /// Sets the command id at the specified |index|. Returns true on success. /// </summary> public int SetCommandIdAt(int index, int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.SetCommandIdAt } /// <summary> /// Returns the label for the specified |command_id| or empty if not found. /// </summary> public cef_string_userfree* GetLabel(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.GetLabel } /// <summary> /// Returns the label at the specified |index| or empty if not found due to /// invalid range or the index being a separator. /// </summary> public cef_string_userfree* GetLabelAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.GetLabelAt } /// <summary> /// Sets the label for the specified |command_id|. Returns true on success. /// </summary> public int SetLabel(int command_id, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.SetLabel } /// <summary> /// Set the label at the specified |index|. Returns true on success. /// </summary> public int SetLabelAt(int index, cef_string_t* label) { throw new NotImplementedException(); // TODO: CefMenuModel.SetLabelAt } /// <summary> /// Returns the item type for the specified |command_id|. /// </summary> public CefMenuItemType GetType(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.GetType } /// <summary> /// Returns the item type at the specified |index|. /// </summary> public CefMenuItemType GetTypeAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.GetTypeAt } /// <summary> /// Returns the group id for the specified |command_id| or -1 if invalid. /// </summary> public int GetGroupId(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.GetGroupId } /// <summary> /// Returns the group id at the specified |index| or -1 if invalid. /// </summary> public int GetGroupIdAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.GetGroupIdAt } /// <summary> /// Sets the group id for the specified |command_id|. Returns true on success. /// </summary> public int SetGroupId(int command_id, int group_id) { throw new NotImplementedException(); // TODO: CefMenuModel.SetGroupId } /// <summary> /// Sets the group id at the specified |index|. Returns true on success. /// </summary> public int SetGroupIdAt(int index, int group_id) { throw new NotImplementedException(); // TODO: CefMenuModel.SetGroupIdAt } /// <summary> /// Returns the submenu for the specified |command_id| or empty if invalid. /// </summary> public cef_menu_model_t* GetSubMenu(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.GetSubMenu } /// <summary> /// Returns the submenu at the specified |index| or empty if invalid. /// </summary> public cef_menu_model_t* GetSubMenuAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.GetSubMenuAt } /// <summary> /// Returns true if the specified |command_id| is visible. /// </summary> public int IsVisible(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.IsVisible } /// <summary> /// Returns true if the specified |index| is visible. /// </summary> public int IsVisibleAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.IsVisibleAt } /// <summary> /// Change the visibility of the specified |command_id|. Returns true on /// success. /// </summary> public int SetVisible(int command_id, int visible) { throw new NotImplementedException(); // TODO: CefMenuModel.SetVisible } /// <summary> /// Change the visibility at the specified |index|. Returns true on success. /// </summary> public int SetVisibleAt(int index, int visible) { throw new NotImplementedException(); // TODO: CefMenuModel.SetVisibleAt } /// <summary> /// Returns true if the specified |command_id| is enabled. /// </summary> public int IsEnabled(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.IsEnabled } /// <summary> /// Returns true if the specified |index| is enabled. /// </summary> public int IsEnabledAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.IsEnabledAt } /// <summary> /// Change the enabled status of the specified |command_id|. Returns true on /// success. /// </summary> public int SetEnabled(int command_id, int enabled) { throw new NotImplementedException(); // TODO: CefMenuModel.SetEnabled } /// <summary> /// Change the enabled status at the specified |index|. Returns true on /// success. /// </summary> public int SetEnabledAt(int index, int enabled) { throw new NotImplementedException(); // TODO: CefMenuModel.SetEnabledAt } /// <summary> /// Returns true if the specified |command_id| is checked. Only applies to /// check and radio items. /// </summary> public int IsChecked(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.IsChecked } /// <summary> /// Returns true if the specified |index| is checked. Only applies to check /// and radio items. /// </summary> public int IsCheckedAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.IsCheckedAt } /// <summary> /// Check the specified |command_id|. Only applies to check and radio items. /// Returns true on success. /// </summary> public int SetChecked(int command_id, int @checked) { throw new NotImplementedException(); // TODO: CefMenuModel.SetChecked } /// <summary> /// Check the specified |index|. Only applies to check and radio items. Returns /// true on success. /// </summary> public int SetCheckedAt(int index, int @checked) { throw new NotImplementedException(); // TODO: CefMenuModel.SetCheckedAt } /// <summary> /// Returns true if the specified |command_id| has a keyboard accelerator /// assigned. /// </summary> public int HasAccelerator(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.HasAccelerator } /// <summary> /// Returns true if the specified |index| has a keyboard accelerator assigned. /// </summary> public int HasAcceleratorAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.HasAcceleratorAt } /// <summary> /// Set the keyboard accelerator for the specified |command_id|. |key_code| can /// be any virtual key or character value. Returns true on success. /// </summary> public int SetAccelerator(int command_id, int key_code, int shift_pressed, int ctrl_pressed, int alt_pressed) { throw new NotImplementedException(); // TODO: CefMenuModel.SetAccelerator } /// <summary> /// Set the keyboard accelerator at the specified |index|. |key_code| can be /// any virtual key or character value. Returns true on success. /// </summary> public int SetAcceleratorAt(int index, int key_code, int shift_pressed, int ctrl_pressed, int alt_pressed) { throw new NotImplementedException(); // TODO: CefMenuModel.SetAcceleratorAt } /// <summary> /// Remove the keyboard accelerator for the specified |command_id|. Returns /// true on success. /// </summary> public int RemoveAccelerator(int command_id) { throw new NotImplementedException(); // TODO: CefMenuModel.RemoveAccelerator } /// <summary> /// Remove the keyboard accelerator at the specified |index|. Returns true on /// success. /// </summary> public int RemoveAcceleratorAt(int index) { throw new NotImplementedException(); // TODO: CefMenuModel.RemoveAcceleratorAt } /// <summary> /// Retrieves the keyboard accelerator for the specified |command_id|. Returns /// true on success. /// </summary> public int GetAccelerator(int command_id, int* key_code, int* shift_pressed, int* ctrl_pressed, int* alt_pressed) { throw new NotImplementedException(); // TODO: CefMenuModel.GetAccelerator } /// <summary> /// Retrieves the keyboard accelerator for the specified |index|. Returns true /// on success. /// </summary> public int GetAcceleratorAt(int index, int* key_code, int* shift_pressed, int* ctrl_pressed, int* alt_pressed) { throw new NotImplementedException(); // TODO: CefMenuModel.GetAcceleratorAt } } }
using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json; namespace Citrina { public class Messages : IMessages { /// <summary> /// Adds a new user to a chat. /// </summary> public Task<ApiRequest<bool?>> AddChatUserApi(int? chatId = null, int? userId = null) { var request = new Dictionary<string, string> { ["chat_id"] = chatId?.ToString(), ["user_id"] = userId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.addChatUser", null, request); } /// <summary> /// Allows sending messages from community to the current user. /// </summary> public Task<ApiRequest<bool?>> AllowMessagesFromGroupApi(int? groupId = null, string key = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["key"] = key, }; return RequestManager.CreateRequestAsync<bool?>("messages.allowMessagesFromGroup", null, request); } /// <summary> /// Creates a chat with several participants. /// </summary> public Task<ApiRequest<int?>> CreateChatApi(IEnumerable<int> userIds = null, string title = null) { var request = new Dictionary<string, string> { ["user_ids"] = RequestHelpers.ParseEnumerable(userIds), ["title"] = title, }; return RequestManager.CreateRequestAsync<int?>("messages.createChat", null, request); } /// <summary> /// Deletes one or more messages. /// </summary> public Task<ApiRequest<MessagesDeleteResponse>> DeleteApi(IEnumerable<int> messageIds = null, bool? spam = null, int? groupId = null, bool? deleteForAll = null) { var request = new Dictionary<string, string> { ["message_ids"] = RequestHelpers.ParseEnumerable(messageIds), ["spam"] = RequestHelpers.ParseBoolean(spam), ["group_id"] = groupId?.ToString(), ["delete_for_all"] = RequestHelpers.ParseBoolean(deleteForAll), }; return RequestManager.CreateRequestAsync<MessagesDeleteResponse>("messages.delete", null, request); } /// <summary> /// Deletes a chat's cover picture. /// </summary> public Task<ApiRequest<MessagesDeleteChatPhotoResponse>> DeleteChatPhotoApi(int? chatId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["chat_id"] = chatId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesDeleteChatPhotoResponse>("messages.deleteChatPhoto", null, request); } /// <summary> /// Deletes all private messages in a conversation. /// </summary> public Task<ApiRequest<MessagesDeleteConversationResponse>> DeleteConversationApi(int? userId = null, int? peerId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["user_id"] = userId?.ToString(), ["peer_id"] = peerId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesDeleteConversationResponse>("messages.deleteConversation", null, request); } /// <summary> /// Denies sending message from community to the current user. /// </summary> public Task<ApiRequest<bool?>> DenyMessagesFromGroupApi(int? groupId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.denyMessagesFromGroup", null, request); } /// <summary> /// Edits the message. /// </summary> public Task<ApiRequest<bool?>> EditApi(int? peerId = null, string message = null, int? messageId = null, double? lat = null, double? @long = null, string attachment = null, bool? keepForwardMessages = null, bool? keepSnippets = null, int? groupId = null, bool? dontParseLinks = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["message"] = message, ["message_id"] = messageId?.ToString(), ["lat"] = lat?.ToString(), ["long"] = @long?.ToString(), ["attachment"] = attachment, ["keep_forward_messages"] = RequestHelpers.ParseBoolean(keepForwardMessages), ["keep_snippets"] = RequestHelpers.ParseBoolean(keepSnippets), ["group_id"] = groupId?.ToString(), ["dont_parse_links"] = RequestHelpers.ParseBoolean(dontParseLinks), }; return RequestManager.CreateRequestAsync<bool?>("messages.edit", null, request); } /// <summary> /// Edits the title of a chat. /// </summary> public Task<ApiRequest<bool?>> EditChatApi(int? chatId = null, string title = null) { var request = new Dictionary<string, string> { ["chat_id"] = chatId?.ToString(), ["title"] = title, }; return RequestManager.CreateRequestAsync<bool?>("messages.editChat", null, request); } /// <summary> /// Returns messages by their IDs within the conversation. /// </summary> public Task<ApiRequest<MessagesGetByConversationMessageIdResponse>> GetByConversationMessageIdApi(int? peerId = null, IEnumerable<int> conversationMessageIds = null, bool? extended = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["conversation_message_ids"] = RequestHelpers.ParseEnumerable(conversationMessageIds), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetByConversationMessageIdResponse>("messages.getByConversationMessageId", null, request); } /// <summary> /// Returns messages by their IDs. /// </summary> public Task<ApiRequest<MessagesGetByIdResponse>> GetByIdApi(IEnumerable<int> messageIds = null, int? previewLength = null, bool? extended = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["message_ids"] = RequestHelpers.ParseEnumerable(messageIds), ["preview_length"] = previewLength?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetByIdResponse>("messages.getById", null, request); } /// <summary> /// Returns messages by their IDs. /// </summary> public Task<ApiRequest<MessagesGetByIdExtendedResponse>> GetByIdApi(IEnumerable<int> messageIds = null, int? previewLength = null, bool? extended = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["message_ids"] = RequestHelpers.ParseEnumerable(messageIds), ["preview_length"] = previewLength?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetByIdExtendedResponse>("messages.getById", null, request); } public Task<ApiRequest<MessagesGetChatPreviewResponse>> GetChatPreviewApi(int? peerId = null, string link = null, IEnumerable<UsersFields> fields = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["link"] = link, ["fields"] = RequestHelpers.ParseEnumerable(fields), }; return RequestManager.CreateRequestAsync<MessagesGetChatPreviewResponse>("messages.getChatPreview", null, request); } /// <summary> /// Returns a list of IDs of users participating in a chat. /// </summary> public Task<ApiRequest<MessagesGetConversationMembersResponse>> GetConversationMembersApi(int? peerId = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetConversationMembersResponse>("messages.getConversationMembers", null, request); } /// <summary> /// Returns a list of the current user's conversations. /// </summary> public Task<ApiRequest<MessagesGetConversationsResponse>> GetConversationsApi(int? offset = null, int? count = null, string filter = null, bool? extended = null, int? startMessageId = null, IEnumerable<BaseUserGroupFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["filter"] = filter, ["extended"] = RequestHelpers.ParseBoolean(extended), ["start_message_id"] = startMessageId?.ToString(), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetConversationsResponse>("messages.getConversations", null, request); } /// <summary> /// Returns conversations by their IDs. /// </summary> public Task<ApiRequest<MessagesGetConversationsByIdResponse>> GetConversationsByIdApi(IEnumerable<int> peerIds = null, bool? extended = null, IEnumerable<BaseUserGroupFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_ids"] = RequestHelpers.ParseEnumerable(peerIds), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetConversationsByIdResponse>("messages.getConversationsById", null, request); } /// <summary> /// Returns conversations by their IDs. /// </summary> public Task<ApiRequest<MessagesGetConversationsByIdExtendedResponse>> GetConversationsByIdApi(IEnumerable<int> peerIds = null, bool? extended = null, IEnumerable<BaseUserGroupFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_ids"] = RequestHelpers.ParseEnumerable(peerIds), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetConversationsByIdExtendedResponse>("messages.getConversationsById", null, request); } /// <summary> /// Returns message history for the specified user or group chat. /// </summary> public Task<ApiRequest<MessagesGetHistoryResponse>> GetHistoryApi(int? offset = null, int? count = null, int? userId = null, int? peerId = null, int? startMessageId = null, int? rev = null, bool? extended = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["user_id"] = userId?.ToString(), ["peer_id"] = peerId?.ToString(), ["start_message_id"] = startMessageId?.ToString(), ["rev"] = rev?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetHistoryResponse>("messages.getHistory", null, request); } /// <summary> /// Returns media files from the dialog or group chat. /// </summary> public Task<ApiRequest<MessagesGetHistoryAttachmentsResponse>> GetHistoryAttachmentsApi(int? peerId = null, string mediaType = null, string startFrom = null, int? count = null, bool? photoSizes = null, IEnumerable<UsersFields> fields = null, int? groupId = null, bool? preserveOrder = null, int? maxForwardsLevel = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["media_type"] = mediaType, ["start_from"] = startFrom, ["count"] = count?.ToString(), ["photo_sizes"] = RequestHelpers.ParseBoolean(photoSizes), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), ["preserve_order"] = RequestHelpers.ParseBoolean(preserveOrder), ["max_forwards_level"] = maxForwardsLevel?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetHistoryAttachmentsResponse>("messages.getHistoryAttachments", null, request); } public Task<ApiRequest<MessagesGetInviteLinkResponse>> GetInviteLinkApi(int? peerId = null, bool? reset = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["reset"] = RequestHelpers.ParseBoolean(reset), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesGetInviteLinkResponse>("messages.getInviteLink", null, request); } /// <summary> /// Returns a user's current status and date of last activity. /// </summary> public Task<ApiRequest<MessagesLastActivity>> GetLastActivityApi(int? userId = null) { var request = new Dictionary<string, string> { ["user_id"] = userId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesLastActivity>("messages.getLastActivity", null, request); } /// <summary> /// Returns updates in user's private messages. /// </summary> public Task<ApiRequest<MessagesGetLongPollHistoryResponse>> GetLongPollHistoryApi(int? ts = null, int? pts = null, int? previewLength = null, bool? onlines = null, IEnumerable<UsersFields> fields = null, int? eventsLimit = null, int? msgsLimit = null, int? maxMsgId = null, int? groupId = null, int? lpVersion = null, int? lastN = null, bool? credentials = null) { var request = new Dictionary<string, string> { ["ts"] = ts?.ToString(), ["pts"] = pts?.ToString(), ["preview_length"] = previewLength?.ToString(), ["onlines"] = RequestHelpers.ParseBoolean(onlines), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["events_limit"] = eventsLimit?.ToString(), ["msgs_limit"] = msgsLimit?.ToString(), ["max_msg_id"] = maxMsgId?.ToString(), ["group_id"] = groupId?.ToString(), ["lp_version"] = lpVersion?.ToString(), ["last_n"] = lastN?.ToString(), ["credentials"] = RequestHelpers.ParseBoolean(credentials), }; return RequestManager.CreateRequestAsync<MessagesGetLongPollHistoryResponse>("messages.getLongPollHistory", null, request); } /// <summary> /// Returns data required for connection to a Long Poll server. /// </summary> public Task<ApiRequest<MessagesLongpollParams>> GetLongPollServerApi(bool? needPts = null, int? groupId = null, int? lpVersion = null) { var request = new Dictionary<string, string> { ["need_pts"] = RequestHelpers.ParseBoolean(needPts), ["group_id"] = groupId?.ToString(), ["lp_version"] = lpVersion?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesLongpollParams>("messages.getLongPollServer", null, request); } /// <summary> /// Returns information whether sending messages from the community to current user is allowed. /// </summary> public Task<ApiRequest<MessagesIsMessagesFromGroupAllowedResponse>> IsMessagesFromGroupAllowedApi(int? groupId = null, int? userId = null) { var request = new Dictionary<string, string> { ["group_id"] = groupId?.ToString(), ["user_id"] = userId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesIsMessagesFromGroupAllowedResponse>("messages.isMessagesFromGroupAllowed", null, request); } public Task<ApiRequest<MessagesJoinChatByInviteLinkResponse>> JoinChatByInviteLinkApi(string link = null) { var request = new Dictionary<string, string> { ["link"] = link, }; return RequestManager.CreateRequestAsync<MessagesJoinChatByInviteLinkResponse>("messages.joinChatByInviteLink", null, request); } /// <summary> /// Marks and unmarks conversations as unanswered. /// </summary> public Task<ApiRequest<bool?>> MarkAsAnsweredConversationApi(int? peerId = null, bool? answered = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["answered"] = RequestHelpers.ParseBoolean(answered), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.markAsAnsweredConversation", null, request); } /// <summary> /// Marks and unmarks messages as important (starred). /// </summary> public Task<ApiRequest<IEnumerable<int>>> MarkAsImportantApi(IEnumerable<int> messageIds = null, int? important = null) { var request = new Dictionary<string, string> { ["message_ids"] = RequestHelpers.ParseEnumerable(messageIds), ["important"] = important?.ToString(), }; return RequestManager.CreateRequestAsync<IEnumerable<int>>("messages.markAsImportant", null, request); } /// <summary> /// Marks and unmarks conversations as important. /// </summary> public Task<ApiRequest<bool?>> MarkAsImportantConversationApi(int? peerId = null, bool? important = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["important"] = RequestHelpers.ParseBoolean(important), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.markAsImportantConversation", null, request); } /// <summary> /// Marks messages as read. /// </summary> public Task<ApiRequest<bool?>> MarkAsReadApi(IEnumerable<int> messageIds = null, int? peerId = null, int? startMessageId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["message_ids"] = RequestHelpers.ParseEnumerable(messageIds), ["peer_id"] = peerId?.ToString(), ["start_message_id"] = startMessageId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.markAsRead", null, request); } /// <summary> /// Pin a message. /// </summary> public Task<ApiRequest<MessagesPinnedMessage>> PinApi(int? peerId = null, int? messageId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["message_id"] = messageId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesPinnedMessage>("messages.pin", null, request); } /// <summary> /// Allows the current user to leave a chat or, if the current user started the chat, allows the user to remove another user from the chat. /// </summary> public Task<ApiRequest<bool?>> RemoveChatUserApi(int? chatId = null, int? userId = null, int? memberId = null) { var request = new Dictionary<string, string> { ["chat_id"] = chatId?.ToString(), ["user_id"] = userId?.ToString(), ["member_id"] = memberId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.removeChatUser", null, request); } /// <summary> /// Restores a deleted message. /// </summary> public Task<ApiRequest<bool?>> RestoreApi(int? messageId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["message_id"] = messageId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.restore", null, request); } /// <summary> /// Returns a list of the current user's private messages that match search criteria. /// </summary> public Task<ApiRequest<MessagesSearchResponse>> SearchApi(string q = null, int? peerId = null, int? date = null, int? previewLength = null, int? offset = null, int? count = null, bool? extended = null, IEnumerable<string> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["q"] = q, ["peer_id"] = peerId?.ToString(), ["date"] = date?.ToString(), ["preview_length"] = previewLength?.ToString(), ["offset"] = offset?.ToString(), ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesSearchResponse>("messages.search", null, request); } /// <summary> /// Returns a list of the current user's conversations that match search criteria. /// </summary> public Task<ApiRequest<MessagesSearchConversationsResponse>> SearchConversationsApi(string q = null, int? count = null, bool? extended = null, IEnumerable<UsersFields> fields = null, int? groupId = null) { var request = new Dictionary<string, string> { ["q"] = q, ["count"] = count?.ToString(), ["extended"] = RequestHelpers.ParseBoolean(extended), ["fields"] = RequestHelpers.ParseEnumerable(fields), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<MessagesSearchConversationsResponse>("messages.searchConversations", null, request); } /// <summary> /// Sends a message. /// </summary> public Task<ApiRequest<int?>> SendApi(int? userId = null, int? randomId = null, int? peerId = null, string domain = null, int? chatId = null, IEnumerable<int> userIds = null, string message = null, double? lat = null, double? @long = null, string attachment = null, int? replyTo = null, IEnumerable<int> forwardMessages = null, string forward = null, int? stickerId = null, int? groupId = null, string keyboard = null, string payload = null, bool? dontParseLinks = null, bool? disableMentions = null) { var request = new Dictionary<string, string> { ["user_id"] = userId?.ToString(), ["random_id"] = randomId?.ToString(), ["peer_id"] = peerId?.ToString(), ["domain"] = domain, ["chat_id"] = chatId?.ToString(), ["user_ids"] = RequestHelpers.ParseEnumerable(userIds), ["message"] = message, ["lat"] = lat?.ToString(), ["long"] = @long?.ToString(), ["attachment"] = attachment, ["reply_to"] = replyTo?.ToString(), ["forward_messages"] = RequestHelpers.ParseEnumerable(forwardMessages), ["forward"] = forward, ["sticker_id"] = stickerId?.ToString(), ["group_id"] = groupId?.ToString(), ["keyboard"] = keyboard, ["payload"] = payload, ["dont_parse_links"] = RequestHelpers.ParseBoolean(dontParseLinks), ["disable_mentions"] = RequestHelpers.ParseBoolean(disableMentions), }; return RequestManager.CreateRequestAsync<int?>("messages.send", null, request); } /// <summary> /// Sends a message. /// </summary> public Task<ApiRequest<IEnumerable<object>>> SendApi(int? userId = null, int? randomId = null, int? peerId = null, string domain = null, int? chatId = null, IEnumerable<int> userIds = null, string message = null, double? lat = null, double? @long = null, string attachment = null, int? replyTo = null, IEnumerable<int> forwardMessages = null, string forward = null, int? stickerId = null, int? groupId = null, string keyboard = null, string payload = null, bool? dontParseLinks = null, bool? disableMentions = null) { var request = new Dictionary<string, string> { ["user_id"] = userId?.ToString(), ["random_id"] = randomId?.ToString(), ["peer_id"] = peerId?.ToString(), ["domain"] = domain, ["chat_id"] = chatId?.ToString(), ["user_ids"] = RequestHelpers.ParseEnumerable(userIds), ["message"] = message, ["lat"] = lat?.ToString(), ["long"] = @long?.ToString(), ["attachment"] = attachment, ["reply_to"] = replyTo?.ToString(), ["forward_messages"] = RequestHelpers.ParseEnumerable(forwardMessages), ["forward"] = forward, ["sticker_id"] = stickerId?.ToString(), ["group_id"] = groupId?.ToString(), ["keyboard"] = keyboard, ["payload"] = payload, ["dont_parse_links"] = RequestHelpers.ParseBoolean(dontParseLinks), ["disable_mentions"] = RequestHelpers.ParseBoolean(disableMentions), }; return RequestManager.CreateRequestAsync<IEnumerable<object>>("messages.send", null, request); } /// <summary> /// Changes the status of a user as typing in a conversation. /// </summary> public Task<ApiRequest<bool?>> SetActivityApi(int? userId = null, string type = null, int? peerId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["user_id"] = userId?.ToString(), ["type"] = type, ["peer_id"] = peerId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.setActivity", null, request); } /// <summary> /// Sets a previously-uploaded picture as the cover picture of a chat. /// </summary> public Task<ApiRequest<MessagesSetChatPhotoResponse>> SetChatPhotoApi(string file = null) { var request = new Dictionary<string, string> { ["file"] = file, }; return RequestManager.CreateRequestAsync<MessagesSetChatPhotoResponse>("messages.setChatPhoto", null, request); } public Task<ApiRequest<bool?>> UnpinApi(int? peerId = null, int? groupId = null) { var request = new Dictionary<string, string> { ["peer_id"] = peerId?.ToString(), ["group_id"] = groupId?.ToString(), }; return RequestManager.CreateRequestAsync<bool?>("messages.unpin", null, request); } } }
/* * Copyright (c) 2012 Stephen A. Pratt * * 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 UnityEngine; using UnityEditor; using org.critterai.u3d.editor; using org.critterai.geom; using org.critterai.nmbuild.u3d.editor; using org.critterai.u3d; /// <summary> /// <see cref="TerrainCompiler"/> editor. /// </summary> /// <exclude /> [CustomEditor(typeof(TerrainCompiler))] public sealed class TerrainCompilerEditor : Editor { private const float CheckDelay = 5; private static bool mDebugEnabled; private static int mDebugZoneSize = 10; private static float mDebugOffset = 0; private Terrain mDebugTerrain = null; private Vector3 mDebugPosition; private double mLastCheck = 0; private TerrainData mLastSource = null; void OnEnable() { SceneView.onSceneGUIDelegate += this.OnSceneGUI; } void OnDisable() { SceneView.onSceneGUIDelegate -= this.OnSceneGUI; } /// <summary> /// Controls behavior of the inspector. /// </summary> public override void OnInspectorGUI() { TerrainCompiler targ = (TerrainCompiler)target; EditorGUILayout.Separator(); GUILayout.Label("Priority: " + targ.Priority); EditorGUILayout.Separator(); targ.terrainData = (TerrainData)EditorGUILayout.ObjectField("Terrain Data" , targ.terrainData , typeof(TerrainData) , false); targ.includeTrees = EditorGUILayout.Toggle("Include Trees", targ.includeTrees); float res = EditorGUILayout.Slider("Resolution (%)", targ.Resolution * 100, 0.01f, 100); targ.Resolution = (float)System.Math.Round(Mathf.Max(0.001f, res * 0.01f), 3); EditorGUILayout.Separator(); OnGUIDebug(targ); GUI.enabled = true; EditorGUILayout.Separator(); GUILayout.Box("Input Build Processor\n\nLoads and compiles a " + typeof(Terrain).Name + " component if it references the specified " + typeof(TerrainData).Name + " object." , EditorUtil.HelpStyle , GUILayout.ExpandWidth(true)); EditorGUILayout.Separator(); if (GUI.changed) EditorUtility.SetDirty(target); } private void OnGUIDebug(TerrainCompiler targ) { // Getting the terrain requires a full terrain search. So only check // for it occationally. if (mDebugEnabled) { double time = EditorApplication.timeSinceStartup; if (targ.terrainData != mLastSource || mLastCheck + CheckDelay > time) { Terrain terrain = targ.GetTerrain(); mLastSource = targ.terrainData; mLastCheck = time; if (mDebugTerrain != terrain) { mDebugTerrain = terrain; SceneView.RepaintAll(); } } } else { mDebugTerrain = null; mLastCheck = 0; mLastSource = null; } EditorGUILayout.Separator(); GUI.enabled = targ.terrainData; bool origChanged = GUI.changed; mDebugEnabled = EditorGUILayout.Toggle("Enable Preview", mDebugEnabled); if (!mDebugEnabled || !targ.terrainData) return; GUILayout.Label("Size"); mDebugZoneSize = (int)GUILayout.HorizontalSlider(mDebugZoneSize, 10, 50); GUILayout.Label("Offset"); mDebugOffset = GUILayout.HorizontalSlider(mDebugOffset, 0, 10); EditorGUILayout.Separator(); string helpText; if (mDebugTerrain == null) helpText = "There is no enabled terrain in the scene using the source terrain data."; else { int xc; int zc; Vector3 scale = TerrainUtil.DeriveScale(mDebugTerrain, targ.Resolution, out xc, out zc); int triCount = (xc - 1) * (zc - 1) * 2; helpText = string.Format("Mouse-over the terrain in the scene to see a " + " triangulation preview. Trees are not included in the preview.\n\n" + "Total surface triangles: {0:N0}\n" + "Sample distance: {1:F1} x {2:F1}" , triCount, scale.x, scale.z); } GUILayout.Box(helpText, EditorUtil.HelpStyle, GUILayout.ExpandWidth(true)); if (GUI.changed) SceneView.RepaintAll(); GUI.changed = origChanged; } void OnSceneGUI(SceneView view) { TerrainCompiler targ = (TerrainCompiler)target; if (!mDebugEnabled || mDebugTerrain == null) // Nothing to do. return; Vector3 mousePos = Event.current.mousePosition; Camera cam = Camera.current; Ray ray = cam.ScreenPointToRay(new Vector3(mousePos.x, -mousePos.y + cam.pixelHeight)); Vector3 point = Vector3.zero; RaycastHit hit; if (Physics.Raycast(ray, out hit, 1000.0f)) { Terrain terrain = hit.collider.gameObject.GetComponent<Terrain>(); if (terrain == mDebugTerrain) point = hit.point; } if (mDebugPosition != point) { mDebugPosition = point; SceneView.RepaintAll(); } if (mDebugPosition == Vector3.zero) return; Color c = Color.yellow; c.a = 0.25f; int trash; Vector3 scale = TerrainUtil.DeriveScale(mDebugTerrain, targ.Resolution, out trash, out trash); float xmin = mDebugPosition.x - scale.x * mDebugZoneSize; float zmin = mDebugPosition.z - scale.z * mDebugZoneSize; float xmax = mDebugPosition.x + scale.x * mDebugZoneSize; float zmax = mDebugPosition.z + scale.z * mDebugZoneSize; TriangleMesh mesh = TerrainUtil.TriangulateSurface(mDebugTerrain , xmin, zmin, xmax, zmax , targ.Resolution , mDebugOffset); if (mesh != null) DebugDraw.TriangleMesh(mesh.verts, mesh.tris, mesh.triCount, true, c); } [MenuItem(EditorUtil.NMGenAssetMenu + "Compiler : Terrain", false, NMBEditorUtil.CompilerGroup)] static void CreateAsset() { TerrainCompiler item = EditorUtil.CreateAsset<TerrainCompiler>(NMBEditorUtil.AssetLabel); EditorUtility.FocusProjectWindow(); Selection.activeObject = item; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new float[8] { 22, -5, -50, 0, 22, -1, -50, 0 }, new float[8])) using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 1, 1, 50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); var vf3 = Avx.Compare(vf1, vf2, FloatComparisonMode.EqualOrderedNonSignaling); Unsafe.Write(floatTable.outArrayPtr, vf3); var vd1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vd2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); var vd3 = Avx.Compare(vd1, vd2, FloatComparisonMode.EqualOrderedNonSignaling); Unsafe.Write(doubleTable.outArrayPtr, vd3); for (int i = 0; i < floatTable.outArray.Length; i++) { if (BitConverter.SingleToInt32Bits(floatTable.outArray[i]) != (floatTable.inArray1[i] == floatTable.inArray2[i] ? -1 : 0)) { Console.WriteLine("Avx Compare failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } for (int i = 0; i < doubleTable.outArray.Length; i++) { if (BitConverter.DoubleToInt64Bits(doubleTable.outArray[i]) != (doubleTable.inArray1[i] == doubleTable.inArray2[i] ? -1 : 0)) { Console.WriteLine("Avx Compare failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } var svf1 = Unsafe.Read<Vector128<float>>(floatTable.inArray1Ptr); var svf2 = Unsafe.Read<Vector128<float>>(floatTable.inArray2Ptr); var svf3 = Avx.Compare(svf1, svf2, FloatComparisonMode.EqualOrderedNonSignaling); Unsafe.Write(floatTable.outArrayPtr, svf3); var svd1 = Unsafe.Read<Vector128<double>>(doubleTable.inArray1Ptr); var svd2 = Unsafe.Read<Vector128<double>>(doubleTable.inArray2Ptr); var svd3 = Avx.Compare(svd1, svd2, FloatComparisonMode.EqualOrderedNonSignaling); Unsafe.Write(doubleTable.outArrayPtr, svd3); for (int i = 0; i < floatTable.outArray.Length/2; i++) { if (BitConverter.SingleToInt32Bits(floatTable.outArray[i]) != (floatTable.inArray1[i] == floatTable.inArray2[i] ? -1 : 0)) { Console.WriteLine("Avx Compare Vector128 failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } for (int i = 0; i < doubleTable.outArray.Length/2; i++) { if (BitConverter.DoubleToInt64Bits(doubleTable.outArray[i]) != (doubleTable.inArray1[i] == doubleTable.inArray2[i] ? -1 : 0)) { Console.WriteLine("Avx Compare Vector128 failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); return Fail; } } try { var ve = Avx.Compare(vf1, vf2, (FloatComparisonMode)32); Unsafe.Write(floatTable.outArrayPtr, ve); Console.WriteLine("Avx Compare failed on float with out-of-range argument:"); return Fail; } catch (ArgumentOutOfRangeException e) { testResult = Pass; } try { var ve = Avx.Compare(vd1, vd2, (FloatComparisonMode)32); Unsafe.Write(floatTable.outArrayPtr, ve); Console.WriteLine("Avx Compare failed on double with out-of-range argument:"); return Fail; } catch (ArgumentOutOfRangeException e) { testResult = Pass; } try { var ve = typeof(Avx).GetMethod(nameof(Avx.Compare), new Type[] { typeof(Vector256<Single>), typeof(Vector256<Single>), typeof(FloatComparisonMode) }) .Invoke(null, new object[] {vf1, vf2, (FloatComparisonMode)32}); Console.WriteLine("Indirect-calling Avx Compare failed on float with out-of-range argument:"); return Fail; } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is ArgumentOutOfRangeException) { testResult = Pass; } else { Console.WriteLine("Indirect-calling Avx Compare failed on float with out-of-range argument:"); return Fail; } } try { var ve = typeof(Avx).GetMethod(nameof(Avx.Compare), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(FloatComparisonMode) }) .Invoke(null, new object[] {vd1, vd2, (FloatComparisonMode)32}); Console.WriteLine("Indirect-calling Avx Compare failed on double with out-of-range argument:"); return Fail; } catch (System.Reflection.TargetInvocationException e) { if (e.InnerException is ArgumentOutOfRangeException) { testResult = Pass; } else { Console.WriteLine("Indirect-calling Avx Compare failed on double with out-of-range argument:"); return Fail; } } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T, T, T, bool> check) { for (int i = 0; i < inArray1.Length; i++) { if (!check(inArray1[i], inArray2[i], outArray[i])) { return false; } } return true; } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
using UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.IO; #endif using System.Collections; using System.Collections.Generic; using UMA; public class UMARecipeCrowd : MonoBehaviour { public UMAContext context; public UMAGeneratorBase generator; public RuntimeAnimatorController animationController; public float atlasScale = 0.5f; public bool hideWhileGenerating; public bool stressTest; public Vector2 crowdSize; public float space = 1f; private int spawnX; private int spawnY; private bool generating = false; public bool saveCrowd = false; private string saveFolderPath; public SharedColorTable[] sharedColors; public UMARecipeMixer[] recipeMixers; public UMADataEvent CharacterCreated; public UMADataEvent CharacterDestroyed; public UMADataEvent CharacterUpdated; void Awake() { if (space <= 0) space = 1f; if (atlasScale > 1f) atlasScale = 1f; if (atlasScale < 0.0625f) atlasScale = 0.0625f; if ((crowdSize.x > 0) && (crowdSize.y > 0)) generating = true; #if UNITY_EDITOR if (saveCrowd) { saveFolderPath = "Saved Crowd " + System.DateTime.Now.ToString().Replace('/', '_'); saveFolderPath = saveFolderPath.Replace(':', '_'); string folderGUID = AssetDatabase.CreateFolder("Assets", saveFolderPath); saveFolderPath = AssetDatabase.GUIDToAssetPath(folderGUID); Debug.LogWarning("Saving all generated recipes into: " + saveFolderPath); } #endif } void Update() { if (generator.IsIdle()) { if (generating) { GenerateOneCharacter(); } else if (stressTest) { RandomizeAll(); } } } void CharacterCreatedCallback(UMAData umaData) { if (hideWhileGenerating) { if (umaData.animator != null) umaData.animator.enabled = false; if (umaData.myRenderer != null) umaData.myRenderer.enabled = false; } } public GameObject GenerateOneCharacter() { if ((recipeMixers == null) || (recipeMixers.Length == 0)) return null; Vector3 umaPos = new Vector3((spawnX - crowdSize.x / 2f) * space, 0f, (spawnY - crowdSize.y / 2f) * space); if (spawnY < crowdSize.y) { spawnX++; if (spawnX >= crowdSize.x) { spawnX = 0; spawnY++; } } else { if (hideWhileGenerating) { UMAData[] generatedCrowd = GetComponentsInChildren<UMAData>(); foreach (UMAData generatedData in generatedCrowd) { if (generatedData.animator != null) generatedData.animator.enabled = true; if (generatedData.myRenderer != null) generatedData.myRenderer.enabled = true; } } spawnX = 0; spawnY = 0; generating = false; return null; } GameObject newGO = new GameObject("Generated Character"); newGO.transform.parent = transform; newGO.transform.localPosition = umaPos; newGO.transform.localRotation = Quaternion.identity; UMADynamicAvatar umaAvatar = newGO.AddComponent<UMADynamicAvatar>(); umaAvatar.context = context; umaAvatar.umaGenerator = generator; umaAvatar.Initialize(); UMAData umaData = umaAvatar.umaData; umaData.atlasResolutionScale = atlasScale; umaData.CharacterCreated = new UMADataEvent(CharacterCreated); umaData.OnCharacterCreated += CharacterCreatedCallback; umaData.CharacterDestroyed = new UMADataEvent(CharacterDestroyed); umaData.CharacterUpdated = new UMADataEvent(CharacterUpdated); RandomizeRecipe(umaData); RandomizeDNA(umaData); if (animationController != null) { umaAvatar.animationController = animationController; } umaAvatar.Show(); return newGO; } public void ReplaceAll() { if (generating) { Debug.LogWarning("Can't replace while generating."); return; } int childCount = gameObject.transform.childCount; while(--childCount >= 0) { Transform child = gameObject.transform.GetChild(childCount); Destroy(child.gameObject); } generating = true; } public virtual void RandomizeRecipe(UMAData umaData) { UMARecipeMixer mixer = recipeMixers[Random.Range(0, recipeMixers.Length)]; mixer.FillUMARecipe(umaData.umaRecipe, context); OverlayColorData[] recipeColors = umaData.umaRecipe.sharedColors; if ((recipeColors != null) && (recipeColors.Length > 0)) { foreach (var sharedColor in sharedColors) { if (sharedColor == null) continue; int index = Random.Range(0, sharedColor.colors.Length); for (int i = 0; i < recipeColors.Length; i++) { if (recipeColors[i].name == sharedColor.sharedColorName) { recipeColors[i].color = sharedColor.colors[index].color; } } } } // This is a HACK - maybe there should be a clean way // of removing a conflicting slot via the recipe? int maleJeansIndex = -1; int maleLegsIndex = -1; SlotData[] slots = umaData.umaRecipe.GetAllSlots(); for (int i = 0; i < slots.Length; i++) { SlotData slot = slots[i]; if (slot == null) continue; if (slot.asset.name == null) continue; if (slot.asset.slotName == "MaleJeans01") maleJeansIndex = i; else if (slot.asset.slotName == "MaleLegs") maleLegsIndex = i; } if ((maleJeansIndex >= 0) && (maleLegsIndex >= 0)) { umaData.umaRecipe.SetSlot(maleLegsIndex, null); } #if UNITY_EDITOR if (saveCrowd) { SaveRecipe(umaData, context); } #endif } #if UNITY_EDITOR protected void SaveRecipe(UMAData umaData, UMAContext context) { string assetPath = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(saveFolderPath, umaData.umaRecipe.raceData.raceName + ".asset")); var asset = ScriptableObject.CreateInstance<UMATextRecipe>(); asset.Save(umaData.umaRecipe, context); AssetDatabase.CreateAsset(asset, assetPath); AssetDatabase.SaveAssets(); } #endif public virtual void RandomizeDNA(UMAData umaData) { RaceData race = umaData.umaRecipe.GetRace(); if ((race != null) && (race.dnaRanges != null)) { foreach (DNARangeAsset dnaRange in race.dnaRanges) { dnaRange.RandomizeDNA(umaData); } } } public virtual void RandomizeDNAGaussian(UMAData umaData) { RaceData race = umaData.umaRecipe.GetRace(); if ((race != null) && (race.dnaRanges != null)) { foreach (DNARangeAsset dnaRange in race.dnaRanges) { dnaRange.RandomizeDNAGaussian(umaData); } } } public void RandomizeAll() { if (generating) { Debug.LogWarning("Can't randomize while generating."); return; } int childCount = gameObject.transform.childCount; for (int i = 0; i < childCount; i++) { Transform child = gameObject.transform.GetChild(i); UMADynamicAvatar umaAvatar = child.gameObject.GetComponent<UMADynamicAvatar>(); if (umaAvatar == null) continue; UMAData umaData = umaAvatar.umaData; umaData.umaRecipe = new UMAData.UMARecipe(); RandomizeRecipe(umaData); RandomizeDNA(umaData); if (animationController != null) { umaAvatar.animationController = animationController; } umaAvatar.Show(); } } }
// JavaDocDocumenter.cs - a JavaDoc-like documenter // Copyright (C) 2001 Jason Diamond // // 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 using System; using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Reflection; using System.Collections; using NDoc.Core; using NDoc.Core.Reflection; namespace NDoc.Documenter.JavaDoc { /// <summary>The JavaDoc documenter.</summary> public class JavaDocDocumenter : BaseReflectionDocumenter { /// <summary>Initializes a new instance of the JavaDocDocumenter class.</summary> public JavaDocDocumenter( JavaDocDocumenterConfig config ) : base( config ) { } private Workspace workspace = null; /// <summary>See <see cref="IDocumenter"/>.</summary> public override string MainOutputFile { get { return Path.Combine(this.WorkingPath, "overview-summary.html"); } } string tempFileName; /// <summary>See <see cref="IDocumenter"/>.</summary> public override void Build(Project project) { this.workspace = new JavaDocWorkspace( this.WorkingPath ); workspace.Clean(); workspace.Prepare(); workspace.AddResourceDirectory( "xslt" ); workspace.AddResourceDirectory( "css" ); // Define this when you want to edit the stylesheets // without having to shutdown the application to rebuild. #if NO_RESOURCES // copy all of the xslt source files into the workspace DirectoryInfo xsltSource = new DirectoryInfo( Path.GetFullPath(Path.Combine( System.Windows.Forms.Application.StartupPath, @"..\..\..\Documenter\JavaDoc\xslt") ) ); foreach ( FileInfo f in xsltSource.GetFiles( "*.xslt" ) ) { string fname = Path.Combine( Path.Combine( workspace.ResourceDirectory, "xslt" ), f.Name ); f.CopyTo( fname, true ); File.SetAttributes( fname, FileAttributes.Normal ); } DirectoryInfo cssSource = new DirectoryInfo( Path.GetFullPath(Path.Combine( System.Windows.Forms.Application.StartupPath, @"..\..\..\Documenter\JavaDoc\css") ) ); foreach ( FileInfo f in cssSource.GetFiles( "*.css" ) ) { string cssname = Path.Combine( Path.Combine( workspace.ResourceDirectory, "css" ), f.Name ); f.CopyTo( cssname, true ); File.SetAttributes( cssname, FileAttributes.Normal ); } #else EmbeddedResources.WriteEmbeddedResources( this.GetType().Module.Assembly, "NDoc.Documenter.JavaDoc.css", Path.Combine( this.workspace.ResourceDirectory, "css" ) ); EmbeddedResources.WriteEmbeddedResources( this.GetType().Module.Assembly, "NDoc.Documenter.JavaDoc.xslt", Path.Combine( this.workspace.ResourceDirectory, "xslt") ); #endif string outcss = Path.Combine(MyConfig.OutputDirectory, "JavaDoc.css"); File.Copy(Path.Combine(workspace.ResourceDirectory, @"css\JavaDoc.css"), outcss, true); File.SetAttributes(outcss, FileAttributes.Archive); try { // determine temp file name tempFileName = Path.GetTempFileName(); // Let the Documenter base class do it's thing. MakeXmlFile(project, tempFileName); WriteOverviewSummary(); WriteNamespaceSummaries(); } finally { if (tempFileName != null && File.Exists(tempFileName)) { File.Delete(tempFileName); } workspace.RemoveResourceDirectory(); } } private string WorkingPath { get { if ( Path.IsPathRooted( MyConfig.OutputDirectory ) ) return MyConfig.OutputDirectory; return Path.GetFullPath( MyConfig.OutputDirectory ); } } private JavaDocDocumenterConfig MyConfig { get { return (JavaDocDocumenterConfig)Config; } } private void TransformAndWriteResult( string transformFilename, XsltArgumentList args, string resultDirectory, string resultFilename) { #if DEBUG int start = Environment.TickCount; #endif XslTransform transform = new XslTransform(); transform.Load(Path.Combine(this.workspace.ResourceDirectory, @"xslt\" + transformFilename)); if (args == null) { args = new XsltArgumentList(); } string pathToRoot = ""; if (resultDirectory != null) { string[] directories = resultDirectory.Split('\\'); int count = directories.Length; while (count-- > 0) { pathToRoot += "../"; } } args.AddParam("global-path-to-root", String.Empty, pathToRoot); if (resultDirectory != null) { resultFilename = Path.Combine(resultDirectory, resultFilename); } string resultPath = Path.Combine(MyConfig.OutputDirectory, resultFilename); string resultPathDirectory = Path.GetDirectoryName(resultPath); if (!Directory.Exists(resultPathDirectory)) { Directory.CreateDirectory(resultPathDirectory); } TextWriter writer = new StreamWriter(resultPath); XPathDocument doc = GetCachedXPathDocument(); #if(NET_1_0) //Use overload that is obsolete in v1.1 transform.Transform(doc, args, writer); #else //Use new overload so we don't get obsolete warnings - clean compile :) transform.Transform(doc, args, writer, null); #endif writer.Close(); #if DEBUG Trace.WriteLine("Making " + transformFilename + " Html: " + ((Environment.TickCount - start)).ToString() + " ms."); #endif } private XPathDocument cachedXPathDocument = null; /// <summary> /// Gets the XPathDocument, but caches it and returns the cached value. /// </summary> /// <remarks> /// <c>GetXPathDocument</c> can be very slow for large Assemblies, so this is /// designed to speed things up. As long as the XPathDocument does not ever get /// changed internally by other transforms, this should just speed up the performance /// of the application. /// </remarks> /// <returns></returns> protected XPathDocument GetCachedXPathDocument() { if(cachedXPathDocument == null) { Stream tempFile=null; try { tempFile=File.Open(tempFileName,FileMode.Open,FileAccess.Read); cachedXPathDocument = new XPathDocument(tempFile); } finally { if (tempFile!=null) tempFile.Close(); } } return cachedXPathDocument; } private void WriteOverviewSummary() { XsltArgumentList args = new XsltArgumentList(); string title = MyConfig.Title; if (title == null) title = string.Empty; args.AddParam("global-title", String.Empty, title); TransformAndWriteResult( "overview-summary.xslt", args, null, "overview-summary.html"); } private void WriteNamespaceSummaries() { XmlDocument doc = new XmlDocument(); Stream tempFile=null; try { tempFile=File.Open(tempFileName,FileMode.Open,FileAccess.Read); doc.Load(tempFile); } finally { if (tempFile!=null) tempFile.Close(); } XmlNodeList namespaceNodes = doc.SelectNodes("/ndoc/assembly/module/namespace"); foreach (XmlElement namespaceElement in namespaceNodes) { if (namespaceElement.ChildNodes.Count > 0) { string name = namespaceElement.GetAttribute("name"); WriteNamespaceSummary(name); WriteTypes(namespaceElement); } } } private void WriteNamespaceSummary(string name) { XsltArgumentList args = new XsltArgumentList(); args.AddParam("global-namespace-name", String.Empty, name); TransformAndWriteResult( "namespace-summary.xslt", args, name.Replace('.', '\\'), "namespace-summary.html"); } private void WriteTypes(XmlElement namespaceElement) { XmlNodeList typeNodes = namespaceElement.SelectNodes("interface|class|structure"); foreach (XmlElement typeElement in typeNodes) { WriteType(namespaceElement, typeElement); } } private void WriteType(XmlElement namespaceElement, XmlElement typeElement) { string id = typeElement.GetAttribute("id"); XsltArgumentList args = new XsltArgumentList(); args.AddParam("global-type-id", String.Empty, id); string namespaceName = namespaceElement.GetAttribute("name"); string name = typeElement.GetAttribute("name"); TransformAndWriteResult( "type.xslt", args, namespaceName.Replace('.', '\\'), name + ".html"); } } }
using System; using Microsoft.Extensions.Logging; using System.Linq; using System.Collections.Generic; using System.Text; using NBitcoin; using System.IO; using System.Net; using NBXplorer.Logging; using NBitcoin.Protocol; using NBitcoin.DataEncoders; using NBitcoin.RPC; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Ini; namespace NBXplorer.Configuration { public class ChainConfiguration { public bool Rescan { get; set; } public DateTimeOffset? RescanIfTimeBefore { get; internal set; } public RPCClient RPC { get; internal set; } public EndPoint NodeEndpoint { get; internal set; } public int StartHeight { get; internal set; } public Money MinUtxoValue { get; internal set; } public string CryptoCode { get; set; } public bool HasTxIndex { get; set; } public bool ExposeRPC { get; set; } } public class ExplorerConfiguration { public string ConfigurationFile { get; set; } public string BaseDataDir { get; set; } public string DataDir { get; set; } public string SignalFilesDir { get; set; } public NBXplorerNetworkProvider NetworkProvider { get; set; } public RPCArgs RPC { get; set; } public int MinGapSize { get; set; } = 20; public int MaxGapSize { get; set; } = 30; public int DBCache { get; set; } public List<ChainConfiguration> ChainConfigurations { get; set; } = new List<ChainConfiguration>(); public ExplorerConfiguration LoadArgs(IConfiguration config) { NetworkProvider = new NBXplorerNetworkProvider(DefaultConfiguration.GetNetworkType(config)); var defaultSettings = NBXplorerDefaultSettings.GetDefaultSettings(NetworkProvider.NetworkType); BaseDataDir = config.GetOrDefault<string>("datadir", null); if(BaseDataDir == null) { BaseDataDir = Path.GetDirectoryName(defaultSettings.DefaultDataDirectory); if(!Directory.Exists(BaseDataDir)) Directory.CreateDirectory(BaseDataDir); if(!Directory.Exists(defaultSettings.DefaultDataDirectory)) Directory.CreateDirectory(defaultSettings.DefaultDataDirectory); } Logs.Configuration.LogInformation("Network: " + NetworkProvider.NetworkType.ToString()); var supportedChains = config.GetOrDefault<string>("chains", "btc") .Split(',', StringSplitOptions.RemoveEmptyEntries) .Select(t => t.ToUpperInvariant()); var validChains = new List<string>(); var exposeRPCGlobal = config.GetOrDefault<bool>("exposerpc", false); foreach(var network in NetworkProvider.GetAll()) { if(supportedChains.Contains(network.CryptoCode)) { validChains.Add(network.CryptoCode); var chainConfiguration = new ChainConfiguration(); chainConfiguration.Rescan = config.GetOrDefault<bool>($"{network.CryptoCode}.rescan", false); var rescanIfTimeBefore = config.GetOrDefault<long>($"{network.CryptoCode}.rescaniftimebefore", 0); if (rescanIfTimeBefore != 0) { chainConfiguration.RescanIfTimeBefore = NBitcoin.Utils.UnixTimeToDateTime(rescanIfTimeBefore); } chainConfiguration.CryptoCode = network.CryptoCode; var args = RPCArgs.Parse(config, network.NBitcoinNetwork, network.CryptoCode); chainConfiguration.RPC = args.ConfigureRPCClient(network); if (chainConfiguration.RPC.Address.Port == network.NBitcoinNetwork.DefaultPort) { Logs.Configuration.LogWarning($"{network.CryptoCode}: It seems that the RPC port ({chainConfiguration.RPC.Address.Port}) is equal to the default P2P port ({network.NBitcoinNetwork.DefaultPort}), this is probably a misconfiguration."); } if((chainConfiguration.RPC.CredentialString.CookieFile != null || chainConfiguration.RPC.CredentialString.UseDefault) && !network.SupportCookieAuthentication) { throw new ConfigException($"Chain {network.CryptoCode} does not support cookie file authentication,\n" + $"Please use {network.CryptoCode.ToLowerInvariant()}rpcuser and {network.CryptoCode.ToLowerInvariant()}rpcpassword settings in NBXplorer" + $"And configure rpcuser and rpcpassword in the configuration file or in commandline or your node"); } chainConfiguration.NodeEndpoint = NBitcoin.Utils.ParseEndpoint(config.GetOrDefault<string>($"{network.CryptoCode}.node.endpoint", "127.0.0.1"), network.NBitcoinNetwork.DefaultPort); if (GetPort(chainConfiguration.NodeEndpoint) == network.NBitcoinNetwork.RPCPort) { Logs.Configuration.LogWarning($"{network.CryptoCode}: It seems that the node endpoint port ({GetPort(chainConfiguration.NodeEndpoint)}) is equal to the default RPC port ({network.NBitcoinNetwork.RPCPort}), this is probably a misconfiguration."); } chainConfiguration.StartHeight = config.GetOrDefault<int>($"{network.CryptoCode}.startheight", -1); if (!(network is NBXplorer.NBXplorerNetworkProvider.LiquidNBXplorerNetwork)) { if (config.GetOrDefault<int>($"{network.CryptoCode}.minutxovalue", -1) is int v && v != -1) { chainConfiguration.MinUtxoValue = Money.Satoshis(v); } } chainConfiguration.HasTxIndex = config.GetOrDefault<bool>($"{network.CryptoCode}.hastxindex", false); chainConfiguration.ExposeRPC = config.GetOrDefault<bool>($"{network.CryptoCode}.exposerpc", exposeRPCGlobal); ChainConfigurations.Add(chainConfiguration); } } var invalidChains = String.Join(',', supportedChains.Where(s => !validChains.Contains(s)).ToArray()); if(!string.IsNullOrEmpty(invalidChains)) throw new ConfigException($"Invalid chains {invalidChains} for {NetworkProvider.NetworkType}"); Logs.Configuration.LogInformation("Supported chains: " + String.Join(',', supportedChains.ToArray())); MinGapSize = config.GetOrDefault<int>("mingapsize", 20); MaxGapSize = config.GetOrDefault<int>("maxgapsize", 30); DBCache = config.GetOrDefault<int>("dbcache", 50); if (DBCache > 0) Logs.Configuration.LogInformation($"DBCache: {DBCache} MB"); if (MinGapSize >= MaxGapSize) throw new ConfigException("mingapsize should be equal or lower than maxgapsize"); if(!Directory.Exists(BaseDataDir)) Directory.CreateDirectory(BaseDataDir); DataDir = Path.Combine(BaseDataDir, NBXplorerDefaultSettings.GetFolderName(NetworkProvider.NetworkType)); if (!Directory.Exists(DataDir)) Directory.CreateDirectory(DataDir); SignalFilesDir = config.GetOrDefault<string>("signalfilesdir", null); SignalFilesDir = SignalFilesDir ?? DataDir; if (!Directory.Exists(SignalFilesDir)) Directory.CreateDirectory(SignalFilesDir); CacheChain = config.GetOrDefault<bool>("cachechain", true); NoAuthentication = config.GetOrDefault<bool>("noauth", false); InstanceName = config.GetOrDefault<string>("instancename", ""); TrimEvents = config.GetOrDefault<int>("trimevents", -1); var customKeyPathTemplate = config.GetOrDefault<string>("customkeypathtemplate", null); if (!string.IsNullOrEmpty(customKeyPathTemplate)) { if (!KeyPathTemplate.TryParse(customKeyPathTemplate, out var v)) throw new ConfigException("Invalid customKeyPathTemplate"); if (v.PostIndexes.IsHardened || v.PreIndexes.IsHardened) throw new ConfigException("customKeyPathTemplate should not be an hardened path"); CustomKeyPathTemplate = v; } AzureServiceBusConnectionString = config.GetOrDefault<string>("asbcnstr", ""); AzureServiceBusBlockQueue = config.GetOrDefault<string>("asbblockq", ""); AzureServiceBusTransactionQueue = config.GetOrDefault<string>("asbtranq", ""); AzureServiceBusBlockTopic = config.GetOrDefault<string>("asbblockt", ""); AzureServiceBusTransactionTopic = config.GetOrDefault<string>("asbtrant", ""); RabbitMqHostName = config.GetOrDefault<string>("rmqhost", ""); RabbitMqVirtualHost = config.GetOrDefault<string>("rmqvirtual", ""); RabbitMqUsername = config.GetOrDefault<string>("rmquser", ""); RabbitMqPassword = config.GetOrDefault<string>("rmqpass", ""); RabbitMqTransactionExchange = config.GetOrDefault<string>("rmqtranex", ""); RabbitMqBlockExchange = config.GetOrDefault<string>("rmqblockex", ""); return this; } private int GetPort(EndPoint nodeEndpoint) { if (nodeEndpoint is IPEndPoint endPoint) return endPoint.Port; else if (nodeEndpoint is DnsEndPoint dnsEndPoint) return dnsEndPoint.Port; throw new NotSupportedException(); } public bool Supports(NBXplorerNetwork network) { return ChainConfigurations.Any(c => network.CryptoCode == c.CryptoCode); } public bool CacheChain { get; set; } public bool NoAuthentication { get; set; } public string InstanceName { get; set; } public int TrimEvents { get; set; } public string AzureServiceBusConnectionString { get; set; } public string AzureServiceBusBlockQueue { get; set; } public string AzureServiceBusBlockTopic { get; set; } public string AzureServiceBusTransactionQueue { get; set; } public string AzureServiceBusTransactionTopic { get; set; } public string RabbitMqHostName { get; set; } public string RabbitMqVirtualHost { get; set; } public string RabbitMqUsername { get; set; } public string RabbitMqPassword { get; set; } public string RabbitMqTransactionExchange { get; set; } public string RabbitMqBlockExchange { get; set; } public KeyPathTemplate CustomKeyPathTemplate { get; set; } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace NorthwindAccess { /// <summary> /// Strongly-typed collection for the Category class. /// </summary> [Serializable] public partial class CategoryCollection : ActiveList<Category, CategoryCollection> { public CategoryCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>CategoryCollection</returns> public CategoryCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { Category o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Categories table. /// </summary> [Serializable] public partial class Category : ActiveRecord<Category>, IActiveRecord { #region .ctors and Default Settings public Category() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public Category(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public Category(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public Category(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Categories", TableType.Table, DataService.GetInstance("NorthwindAccess")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema); colvarCategoryID.ColumnName = "CategoryID"; colvarCategoryID.DataType = DbType.Int32; colvarCategoryID.MaxLength = 0; colvarCategoryID.AutoIncrement = true; colvarCategoryID.IsNullable = false; colvarCategoryID.IsPrimaryKey = true; colvarCategoryID.IsForeignKey = false; colvarCategoryID.IsReadOnly = false; colvarCategoryID.DefaultSetting = @""; colvarCategoryID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoryID); TableSchema.TableColumn colvarCategoryName = new TableSchema.TableColumn(schema); colvarCategoryName.ColumnName = "CategoryName"; colvarCategoryName.DataType = DbType.String; colvarCategoryName.MaxLength = 15; colvarCategoryName.AutoIncrement = false; colvarCategoryName.IsNullable = false; colvarCategoryName.IsPrimaryKey = false; colvarCategoryName.IsForeignKey = false; colvarCategoryName.IsReadOnly = false; colvarCategoryName.DefaultSetting = @""; colvarCategoryName.ForeignKeyTableName = ""; schema.Columns.Add(colvarCategoryName); TableSchema.TableColumn colvarDescription = new TableSchema.TableColumn(schema); colvarDescription.ColumnName = "Description"; colvarDescription.DataType = DbType.String; colvarDescription.MaxLength = 0; colvarDescription.AutoIncrement = false; colvarDescription.IsNullable = true; colvarDescription.IsPrimaryKey = false; colvarDescription.IsForeignKey = false; colvarDescription.IsReadOnly = false; colvarDescription.DefaultSetting = @""; colvarDescription.ForeignKeyTableName = ""; schema.Columns.Add(colvarDescription); TableSchema.TableColumn colvarPicture = new TableSchema.TableColumn(schema); colvarPicture.ColumnName = "Picture"; colvarPicture.DataType = DbType.Binary; colvarPicture.MaxLength = 0; colvarPicture.AutoIncrement = false; colvarPicture.IsNullable = true; colvarPicture.IsPrimaryKey = false; colvarPicture.IsForeignKey = false; colvarPicture.IsReadOnly = false; colvarPicture.DefaultSetting = @""; colvarPicture.ForeignKeyTableName = ""; schema.Columns.Add(colvarPicture); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["NorthwindAccess"].AddSchema("Categories",schema); } } #endregion #region Props [XmlAttribute("CategoryID")] [Bindable(true)] public int CategoryID { get { return GetColumnValue<int>(Columns.CategoryID); } set { SetColumnValue(Columns.CategoryID, value); } } [XmlAttribute("CategoryName")] [Bindable(true)] public string CategoryName { get { return GetColumnValue<string>(Columns.CategoryName); } set { SetColumnValue(Columns.CategoryName, value); } } [XmlAttribute("Description")] [Bindable(true)] public string Description { get { return GetColumnValue<string>(Columns.Description); } set { SetColumnValue(Columns.Description, value); } } [XmlAttribute("Picture")] [Bindable(true)] public byte[] Picture { get { return GetColumnValue<byte[]>(Columns.Picture); } set { SetColumnValue(Columns.Picture, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public NorthwindAccess.ProductCategoryMapCollection ProductCategoryMapRecords() { return new NorthwindAccess.ProductCategoryMapCollection().Where(ProductCategoryMap.Columns.CategoryID, CategoryID).Load(); } public NorthwindAccess.ProductCollection Products() { return new NorthwindAccess.ProductCollection().Where(Product.Columns.CategoryID, CategoryID).Load(); } #endregion //no foreign key tables defined (0) #region Many To Many Helpers public NorthwindAccess.ProductCollection GetProductCollection() { return Category.GetProductCollection(this.CategoryID); } public static NorthwindAccess.ProductCollection GetProductCollection(int varCategoryID) { SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [Products] INNER JOIN [Product_Category_Map] ON [Products].[ProductID] = [Product_Category_Map].[ProductID] WHERE [Product_Category_Map].[CategoryID] = PARM__CategoryID", Category.Schema.Provider.Name); cmd.AddParameter("PARM__CategoryID", varCategoryID, DbType.Int32); IDataReader rdr = SubSonic.DataService.GetReader(cmd); ProductCollection coll = new ProductCollection(); coll.LoadAndCloseReader(rdr); return coll; } public static void SaveProductMap(int varCategoryID, ProductCollection items) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = PARM__CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("PARM__CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (Product item in items) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", item.GetPrimaryKeyValue()); varProductCategoryMap.Save(); } } public static void SaveProductMap(int varCategoryID, System.Web.UI.WebControls.ListItemCollection itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = PARM__CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("PARM__CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (System.Web.UI.WebControls.ListItem l in itemList) { if (l.Selected) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", l.Value); varProductCategoryMap.Save(); } } } public static void SaveProductMap(int varCategoryID , int[] itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = PARM__CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("PARM__CategoryID", varCategoryID, DbType.Int32); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (int item in itemList) { ProductCategoryMap varProductCategoryMap = new ProductCategoryMap(); varProductCategoryMap.SetColumnValue("CategoryID", varCategoryID); varProductCategoryMap.SetColumnValue("ProductID", item); varProductCategoryMap.Save(); } } public static void DeleteProductMap(int varCategoryID) { QueryCommand cmdDel = new QueryCommand("DELETE FROM [Product_Category_Map] WHERE [Product_Category_Map].[CategoryID] = PARM__CategoryID", Category.Schema.Provider.Name); cmdDel.AddParameter("PARM__CategoryID", varCategoryID, DbType.Int32); DataService.ExecuteQuery(cmdDel); } #endregion #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCategoryName,string varDescription,byte[] varPicture) { Category item = new Category(); item.CategoryName = varCategoryName; item.Description = varDescription; item.Picture = varPicture; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varCategoryID,string varCategoryName,string varDescription,byte[] varPicture) { Category item = new Category(); item.CategoryID = varCategoryID; item.CategoryName = varCategoryName; item.Description = varDescription; item.Picture = varPicture; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn CategoryIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CategoryNameColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn DescriptionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn PictureColumn { get { return Schema.Columns[3]; } } #endregion #region Columns Struct public struct Columns { public static string CategoryID = @"CategoryID"; public static string CategoryName = @"CategoryName"; public static string Description = @"Description"; public static string Picture = @"Picture"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Zio.Tests { public class TestUPath { [Theory] // Test empty [InlineData("", "")] // Tests with regular paths [InlineData("/", "/")] [InlineData("\\", "/")] [InlineData("a", "a")] [InlineData("a/b", "a/b")] [InlineData("a\\b", "a/b")] [InlineData("a/b/", "a/b")] [InlineData("a\\b\\", "a/b")] [InlineData("a///b/c//d", "a/b/c/d")] [InlineData("///a///b/c//", "/a/b/c")] [InlineData("a/b/c", "a/b/c")] [InlineData("/a/b", "/a/b")] // Tests with "." [InlineData(".", ".")] [InlineData("/./a", "/a")] [InlineData("/a/./b", "/a/b")] [InlineData("./a/b", "a/b")] // Tests with ".." [InlineData("..", "..")] [InlineData("../../a/..", "../..")] [InlineData("a/../c", "c")] [InlineData("a/b/..", "a")] [InlineData("a/b/c/../..", "a")] [InlineData("a/b/c/../../..", "")] [InlineData("./..", "..")] [InlineData("../.", "..")] [InlineData("../..", "../..")] [InlineData("../../", "../..")] [InlineData(".a", ".a")] [InlineData(".a/b/..", ".a")] [InlineData("...a/b../", "...a/b..")] [InlineData("...a/..", "")] [InlineData("...a/b/..", "...a")] public void TestNormalize(string pathAsText, string expectedResult) { var path = new UPath(pathAsText); Assert.Equal(expectedResult, path.FullName); // Check Equatable var expectedPath = new UPath(expectedResult); Assert.Equal(expectedPath, path); Assert.True(expectedPath.Equals((object)path)); Assert.Equal(expectedPath.GetHashCode(), path.GetHashCode()); Assert.True(path == expectedPath); Assert.False(path != expectedPath); // Check TryParse UPath result; Assert.True(UPath.TryParse(path.FullName, out result)); } [Fact] public void TestEquals() { var pathInfo = new UPath("x"); Assert.False(pathInfo.Equals((object)"no")); Assert.False(pathInfo.Equals(null)); } [Fact] public void TestAbsoluteAndRelative() { var path = new UPath("x"); Assert.True(path.IsRelative); Assert.False(path.IsAbsolute); path = new UPath(".."); Assert.True(path.IsRelative); Assert.False(path.IsAbsolute); path = new UPath("/x"); Assert.False(path.IsRelative); Assert.True(path.IsAbsolute); Assert.Equal(path, path.ToAbsolute()); path = new UPath(); Assert.True(path.IsNull); } [Theory] [InlineData("", "", "")] [InlineData("/", "", "/")] [InlineData("\\", "", "/")] [InlineData("//", "", "/")] [InlineData("\\\\", "", "/")] [InlineData("/", "/", "/")] [InlineData("\\", "\\", "/")] [InlineData("//", "//", "/")] [InlineData("", "/", "/")] [InlineData("a", "b", "a/b")] [InlineData("a/b", "c", "a/b/c")] [InlineData("", "b", "b")] [InlineData("a", "", "a")] [InlineData("a/b", "", "a/b")] [InlineData("/a", "b/", "/a/b")] [InlineData("/a", "/b", "/b")] [InlineData("/a", "", "/a")] [InlineData("//a", "", "/a")] [InlineData("a/", "", "a")] [InlineData("a//", "", "a")] [InlineData("a/", "b", "a/b")] [InlineData("a/", "b/", "a/b")] [InlineData("a//", "b//", "a/b")] [InlineData("a", "../b", "b")] [InlineData("a/../", "b", "b")] [InlineData("/a/..", "b", "/b")] [InlineData("/a/..", "", "/")] [InlineData("//a//..//", "", "/")] [InlineData("\\a", "", "/a")] [InlineData("\\\\a", "", "/a")] public void TestCombine(string path1, string path2, string expectedResult) { var path = UPath.Combine(path1, path2); Assert.Equal(expectedResult, (string)path); path = new UPath(path1) / new UPath(path2); Assert.Equal(expectedResult, (string)path); // Compare path info directly var expectedPath = new UPath(expectedResult); Assert.Equal(expectedPath, path); Assert.Equal(expectedPath.GetHashCode(), path.GetHashCode()); } [Theory] [InlineData("", "", "", "")] [InlineData("a", "b", "c", "a/b/c")] [InlineData("a/b", "c", "d", "a/b/c/d")] [InlineData("", "b", "", "b")] [InlineData("a", "", "", "a")] [InlineData("a/b", "", "", "a/b")] [InlineData("/a", "b/", "c/", "/a/b/c")] [InlineData("/a", "/b", "/c", "/c")] public void TestCombine3(string path1, string path2, string path3, string expectedResult) { var path = UPath.Combine(path1, path2, path3); Assert.Equal(expectedResult, (string)path); // Compare path info directly var expectedPath = new UPath(expectedResult); Assert.Equal(expectedPath, path); Assert.Equal(expectedPath.GetHashCode(), path.GetHashCode()); } [Theory] [InlineData("", "", "", "", "")] [InlineData("a", "b", "c", "d", "a/b/c/d")] [InlineData("a/b", "c", "d/e", "f", "a/b/c/d/e/f")] [InlineData("", "b", "", "", "b")] [InlineData("a", "", "", "", "a")] [InlineData("a/b", "", "", "", "a/b")] [InlineData("/a", "b/", "c/", "", "/a/b/c")] [InlineData("/a", "/b", "/c", "/d", "/d")] [InlineData("a", "b", "..", "c", "a/c")] public void TestCombine4(string path1, string path2, string path3, string path4, string expectedResult) { var path = UPath.Combine(path1, path2, path3, path4); Assert.Equal(expectedResult, (string)path); // Compare path info directly var expectedPath = new UPath(expectedResult); Assert.Equal(expectedPath, path); Assert.Equal(expectedPath.GetHashCode(), path.GetHashCode()); } [Theory] [InlineData(new[] { "", "" }, "")] [InlineData(new[] { "a", "b", "c", "d", "e" }, "a/b/c/d/e")] [InlineData(new[] { "a", "..", "c", "..", "e" }, "e")] [InlineData(new[] { "a", "b", "c", "/d", "e" }, "/d/e")] [InlineData(new[] { "a", "", "", "", "e" }, "a/e")] public void TestCombineN(string[] parts, string expectedResult) { var path = UPath.Combine(parts.Select(a => (UPath)a).ToArray()); Assert.Equal(expectedResult, (string)path); // Compare path info directly var expectedPath = new UPath(expectedResult); Assert.Equal(expectedPath, path); Assert.Equal(expectedPath.GetHashCode(), path.GetHashCode()); } [Theory] [InlineData("", "")] [InlineData("/", "")] [InlineData("/a", "a")] [InlineData("/a/b", "b")] [InlineData("/a/b/c.txt", "c.txt")] [InlineData("a", "a")] [InlineData("../a", "a")] [InlineData("../../a/b", "b")] public void TestGetName(string path1, string expectedName) { var path = (UPath) path1; var result = path.GetName(); Assert.Equal(expectedName, result); } [Theory] [InlineData("", "")] [InlineData("/", "")] [InlineData("/a", "a")] [InlineData("/a/b", "b")] [InlineData("/a/b/c.txt", "c")] [InlineData("a", "a")] [InlineData("../a", "a")] [InlineData("../../a/b", "b")] public void TestGetNameWithoutExtension(string path1, string expectedName) { var path = (UPath)path1; var result = path.GetNameWithoutExtension(); Assert.Equal(expectedName, result); } [Theory] [InlineData("", "")] [InlineData("/", "")] [InlineData("/a.txt", ".txt")] [InlineData("/a.", "")] [InlineData("/a.txt.bak", ".bak")] [InlineData("a.txt", ".txt")] [InlineData("a.", "")] [InlineData("a.txt.bak", ".bak")] public void TestGetExtension(string path1, string expectedName) { var path = (UPath)path1; var result = path.GetExtensionWithDot(); Assert.Equal(expectedName, result); } [Theory] [InlineData("", "")] [InlineData("/", null)] [InlineData("/a", "/")] [InlineData("/a/b", "/a")] [InlineData("/a/b/c.txt", "/a/b")] [InlineData("a", "")] [InlineData("../a", "..")] [InlineData("../../a/b", "../../a")] public void TestGetDirectory(string path1, string expectedDir) { var path = (UPath)path1; var result = path.GetDirectory(); Assert.Equal(expectedDir, result); } [Theory] [InlineData("", ".txt", "")] [InlineData("/", ".txt", "/.txt")] [InlineData("/a", ".txt", "/a.txt")] [InlineData("/a/b", ".txt", "/a/b.txt")] [InlineData("/a/b/c.bin", ".txt", "/a/b/c.txt")] [InlineData("a", ".txt", "a.txt")] [InlineData("../a", ".txt", "../a.txt")] [InlineData("../../a/b", ".txt", "../../a/b.txt")] public void TestChangeExtension(string path1, string newExt, string expectedPath) { var path = (UPath)path1; var result = path.ChangeExtension(newExt); Assert.Equal(expectedPath, result); } [Theory] // Test automatic separator insertion [InlineData("/a/b/c", "/a/b", false, true)] [InlineData("/a/bc", "/a/b", false, false)] // Test trailing separator [InlineData("/a/b/", "/a", false, true)] [InlineData("/a/b", "/a/", false, true)] [InlineData("/a/b/", "/a/", false, true)] // Test recursive option [InlineData("/a/b/c", "/a", true, true)] [InlineData("/a/b/c", "/a", false, false)] // Test relative paths [InlineData("a/b", "a", false, true)] // Test exact match [InlineData("/a/b/", "/a/b/", false, true)] [InlineData("/a/b/", "/a/b/", true, true)] [InlineData("/a/b", "/a/b", false, true)] [InlineData("/a/b", "/a/b", true, true)] public void TestIsInDirectory(string path1, string directory, bool recursive, bool expected) { var path = (UPath)path1; var result = path.IsInDirectory(directory, recursive); Assert.Equal(expected, result); } [Fact] public void TestSplit() { Assert.Equal(new List<string>(), ((UPath)"").Split()); Assert.Equal(new List<string>(), ((UPath)"/").Split()); Assert.Equal(new List<string>() { "a" }, ((UPath)"/a").Split()); Assert.Equal(new List<string>() {"a", "b", "c"}, ((UPath) "/a/b/c").Split()); Assert.Equal(new List<string>() { "a" }, ((UPath)"a").Split()); Assert.Equal(new List<string>() { "a", "b" }, ((UPath)"a/b").Split()); Assert.Equal(new List<string>() { "a", "b", "c" }, ((UPath)"a/b/c").Split()); } [Fact] public void TestExpectedException() { Assert.Throws<ArgumentException>(() => new UPath("/../a")); Assert.Throws<ArgumentException>(() => new UPath("...")); Assert.Throws<ArgumentException>(() => new UPath("a/...")); Assert.Throws<ArgumentException>(() => new UPath(".../a")); Assert.Throws<ArgumentException>(() => UPath.Combine("/", "..")); Assert.Equal("path1", Assert.Throws<ArgumentNullException>(() => UPath.Combine(null, "")).ParamName); Assert.Equal("path2", Assert.Throws<ArgumentNullException>(() => UPath.Combine("", null)).ParamName); Assert.Throws<ArgumentException>(() => UPathExtensions.IsInDirectory("/a", "b", true)); Assert.Throws<ArgumentException>(() => UPathExtensions.IsInDirectory("a", "/b", true)); } [Fact] public void TestComparers() { { var list = new SortedSet<UPath>(UPath.DefaultComparer) { "/C.txt", "/b.txt", "/do.txt", "/A.txt", "/a.txt" }; Assert.Equal(new List<UPath>() { "/A.txt", "/C.txt", "/a.txt", "/b.txt", "/do.txt" }, list.ToList()); } { var list = new List<UPath>() { "/C.txt", "/b.txt", "/do.txt", "/A.txt", "/a.txt" }; list.Sort(UPath.DefaultComparerIgnoreCase); Assert.Equal(new List<UPath>() { "/A.txt", "/a.txt", "/b.txt", "/C.txt", "/do.txt" }, list.ToList()); } } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange (mailto:[email protected]) // // Copyright (c) 2005-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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.Diagnostics; using System.Runtime.InteropServices; using System.ComponentModel; using System.IO; #if GDI using System.Drawing; using System.Drawing.Drawing2D; #endif #if WPF using System.Windows; using System.Windows.Media; #endif using PdfSharp.Internal; using PdfSharp.Fonts.OpenType; using PdfSharp.Pdf; using PdfSharp.Pdf.Advanced; namespace PdfSharp.Drawing { /// <summary> /// Temporary hack to implement PrivateFontCollection. /// </summary> class XTypefaceHack { public XTypefaceHack(string typefaceName) : this(typefaceName, XFontStyle.Regular, XFontWeights.Normal, new XFontStretch()) { } public XTypefaceHack(string typefaceName, XFontStyle style, XFontWeight weight) : this(typefaceName, style, weight, new XFontStretch()) { } public XTypefaceHack(string fontFamilyName, XFontStyle style, XFontWeight weight, XFontStretch stretch) { if (String.IsNullOrEmpty(fontFamilyName)) throw new ArgumentNullException("fontFamilyName"); this.fontFamilyName = fontFamilyName; this.style = style; this.weight = weight; this.stretch = stretch; } public string FontFamilyName { get { return this.fontFamilyName; } } string fontFamilyName; public XFontWeight Weight { get { return this.weight; } } private XFontWeight weight; public XFontStyle Style { get { return this.style; } } private XFontStyle style; public XFontStretch Stretch { get { return this.stretch; } } private XFontStretch stretch; } /// <summary> /// NYI /// </summary> internal class XTypeface { // /// <summary> // /// Construct a typeface // /// </summary> // /// <param name="typefaceName">font typeface name</param> // public Typeface( // string typefaceName // ) // // assume face name is family name until we get face name resolved properly. // : this( // new FontFamily(typefaceName), // FontStyles.Normal, // FontWeights.Normal, // FontStretches.Normal // ) // { } // /// <summary> // /// Construct a typeface // /// </summary> // /// <param name="fontFamily">Font family</param> // /// <param name="style">Font style</param> // /// <param name="weight">Boldness of font</param> // /// <param name="stretch">Width of characters</param> // public Typeface( // FontFamily fontFamily, // FontStyle style, // FontWeight weight, // FontStretch stretch // ) // : this( // fontFamily, // style, // weight, // stretch, // FontFamily.FontFamilyGlobalUI // ) // { } // /// <summary> // /// Construct a typeface // /// </summary> // /// <param name="fontFamily">Font family</param> // /// <param name="style">Font style</param> // /// <param name="weight">Boldness of font</param> // /// <param name="stretch">Width of characters</param> // /// <param name="fallbackFontFamily">fallback font family</param> // public Typeface( // FontFamily fontFamily, // FontStyle style, // FontWeight weight, // FontStretch stretch, // FontFamily fallbackFontFamily // ) // { // if (fontFamily == null) // { // throw new ArgumentNullException("fontFamily"); // } // _fontFamily = fontFamily; // _style = style; // _weight = weight; // _stretch = stretch; // _fallbackFontFamily = fallbackFontFamily; // } // private FontFamily _fontFamily; // // these _style, _weight and _stretch are only used for storing what was passed into the constructor. // // Since FontFamily may change these values when it includes a style name implicitly, // private FontStyle _style; // private FontWeight _weight; // private FontStretch _stretch; // /// <summary> // /// Font family // /// </summary> // public FontFamily FontFamily // { // get { return _fontFamily; } // } // /// <summary> // /// Font weight (light, bold, etc.) // /// </summary> // public FontWeight Weight // { // get { return _weight; } // } // /// <summary> // /// Font style (italic, oblique) // /// </summary> // public FontStyle Style // { // get { return _style; } // } // /// <summary> // /// Font Stretch (narrow, wide, etc.) // /// </summary> // public FontStretch Stretch // { // get { return _stretch; } // } // private FontFamily _fallbackFontFamily; // // Cached canonical values of the typeface. // private CachedTypeface _cachedTypeface; // /// <summary> // /// Returns true if FontStyle.Oblique is algorithmically simulated by // /// slanting glyphs. Returns false otherwise. // /// </summary> // public bool IsObliqueSimulated // { // get // { // return (CachedTypeface.TypefaceMetrics.StyleSimulations & StyleSimulations.ItalicSimulation) != 0; // } // } // /// <summary> // /// Returns true if FontStyle.Bold is algorithmically simulated by // /// thickening glyphs. Returns false otherwise. // /// </summary> // public bool IsBoldSimulated // { // get // { // return (CachedTypeface.TypefaceMetrics.StyleSimulations & StyleSimulations.BoldSimulation) != 0; // } // } // /// <summary> // /// Obtain a glyph typeface that corresponds to the Typeface object constructed from an OpenType font family. // /// If the Typeface was constructed from a composite font family, returns null. // /// </summary> // /// <param name="glyphTypeface">GlyphTypeface object that corresponds to this Typeface, or null if the Typeface // /// was constructed from a composite font.</param> // /// <returns>Whether glyphTypeface is not null.</returns> // public bool TryGetGlyphTypeface(out GlyphTypeface glyphTypeface) // { // glyphTypeface = CachedTypeface.TypefaceMetrics as GlyphTypeface; // return glyphTypeface != null; // } // /// <summary> // /// Fallback font family // /// </summary> // internal FontFamily FallbackFontFamily // { // get { return _fallbackFontFamily; } // } // /// <summary> // /// (Western) x-height relative to em size. // /// </summary> // public double XHeight // { // get // { // return CachedTypeface.TypefaceMetrics.XHeight; // } // } // /// <summary> // /// Distance from baseline to top of English capital, relative to em size. // /// </summary> // public double CapsHeight // { // get // { // return CachedTypeface.TypefaceMetrics.CapsHeight; // } // } // /// <summary> // /// Distance from baseline to underline position // /// </summary> // public double UnderlinePosition // { // get // { // return CachedTypeface.TypefaceMetrics.UnderlinePosition; // } // } // /// <summary> // /// Underline thickness // /// </summary> // public double UnderlineThickness // { // get // { // return CachedTypeface.TypefaceMetrics.UnderlineThickness; // } // } // /// <summary> // /// Distance from baseline to strike-through position // /// </summary> // public double StrikethroughPosition // { // get // { // return CachedTypeface.TypefaceMetrics.StrikethroughPosition; // } // } // /// <summary> // /// strike-through thickness // /// </summary> // public double StrikethroughThickness // { // get // { // return CachedTypeface.TypefaceMetrics.StrikethroughThickness; // } // } // /// <summary> // /// Collection of culture-dependant face names. // /// </summary> // public LanguageSpecificStringDictionary FaceNames // { // get // { // return new LanguageSpecificStringDictionary(CachedTypeface.TypefaceMetrics.AdjustedFaceNames); // } // } // /// <summary> // /// Distance from character cell top to English baseline relative to em size. // /// </summary> // internal double Baseline // { // get // { // return CachedTypeface.FirstFontFamily.Baseline; // } // } // /// <summary> // /// Baseline to baseline distance relative to em size // /// </summary> // internal double LineSpacing // { // get // { // return CachedTypeface.FirstFontFamily.LineSpacing; // } // } // /// <summary> // /// Flag indicating if the typeface is of symbol type // /// </summary> // internal bool Symbol // { // get // { // return CachedTypeface.TypefaceMetrics.Symbol; // } // } // internal bool NullFont // { // get // { // return CachedTypeface.NullFont; // } // } // // Tries to get a GlyphTypeface based on the Typeface properties. The // // return value can be null. However, if CheckFastPathNominalGlyphs // // returns true, then one can expect this function to return a valid // // GlyphTypeface that maps all the specified text. // internal GlyphTypeface TryGetGlyphTypeface() // { // return CachedTypeface.TypefaceMetrics as GlyphTypeface; // } // internal FontStyle CanonicalStyle // { // get // { // return CachedTypeface.CanonicalStyle; // } // } // internal FontWeight CanonicalWeight // { // get // { // return CachedTypeface.CanonicalWeight; // } // } // internal FontStretch CanonicalStretch // { // get // { // return CachedTypeface.CanonicalStretch; // } // } // /// <summary> // /// Scan through specified character string checking for valid character // /// nominal glyph. // /// </summary> // /// <param name="charBufferRange">character buffer range</param> // /// <param name="emSize">height of Em</param> // /// <param name="widthMax">maximum width allowed</param> // /// <param name="keepAWord">do not stop arbitrarily in the middle of a word</param> // /// <param name="numberSubstitution">digits require complex shaping</param> // /// <param name="cultureInfo">CultureInfo of the text</param> // /// <param name="stringLengthFit">number of character fit in given width</param> // /// <returns>whether the specified string can be optimized by nominal glyph lookup</returns> // internal bool CheckFastPathNominalGlyphs( // CharacterBufferRange charBufferRange, // double emSize, // double widthMax, // bool keepAWord, // bool numberSubstitution, // CultureInfo cultureInfo, // out int stringLengthFit // ) // { // stringLengthFit = 0; // if (CachedTypeface.NullFont) return false; // GlyphTypeface glyphTypeface = TryGetGlyphTypeface(); // if (glyphTypeface == null) return false; // stringLengthFit = 0; // IDictionary<int, ushort> cmap = glyphTypeface.CharacterToGlyphMap; // double totalWidth = 0; // int i = 0; // ushort blankGlyph = glyphTypeface.BlankGlyphIndex; // ushort glyph = blankGlyph; // ushort charFlagsMask = numberSubstitution ? // (ushort)(CharacterAttributeFlags.CharacterComplex | CharacterAttributeFlags.CharacterDigit) : // (ushort)CharacterAttributeFlags.CharacterComplex; // ushort charFlags = 0; // ushort charFastTextCheck = (ushort)(CharacterAttributeFlags.CharacterFastText | CharacterAttributeFlags.CharacterIdeo); // bool symbolTypeface = glyphTypeface.Symbol; // if (symbolTypeface) // { // // we don't care what code points are present if it's a non-Unicode font such as Symbol or Wingdings; // // the code points don't have any standardized meanings, and we always want to bypass shaping // charFlagsMask = 0; // } // if (keepAWord) // { // do // { // char ch = charBufferRange[i++]; // int charClass = (int)Classification.GetUnicodeClassUTF16(ch); // charFlags = Classification.CharAttributeOf(charClass).Flags; // charFastTextCheck &= charFlags; // cmap.TryGetValue(ch, out glyph); // totalWidth += emSize * glyphTypeface.GetAdvanceWidth(glyph); // } while ( // i < charBufferRange.Length // && ((charFlags & charFlagsMask) == 0) // && (glyph != 0 || symbolTypeface) // && glyph != blankGlyph // ); // // i is now at a character immediately following a leading blank // } // while ( // i < charBufferRange.Length // && totalWidth <= widthMax // && ((charFlags & charFlagsMask) == 0) // && (glyph != 0 || symbolTypeface) // ) // { // char ch = charBufferRange[i++]; // int charClass = (int)Classification.GetUnicodeClassUTF16(ch); // charFlags = Classification.CharAttributeOf(charClass).Flags; // charFastTextCheck &= charFlags; // cmap.TryGetValue(ch, out glyph); // totalWidth += emSize * glyphTypeface.GetAdvanceWidth(glyph); // } // if (symbolTypeface) // { // // always optimize for non-Unicode font as we don't support shaping or typographic features; // // we also don't fall back from non-Unicode fonts so we don't care if there are missing glyphs // stringLengthFit = i; // return true; // } // if (glyph == 0) // { // // character is not supported by the font // return false; // } // if ((charFlags & charFlagsMask) != 0) // { // // complex character encountered, exclude it // Debug.Assert(i > 0); // if (--i <= 0) // { // // first char is complex, fail the call // return false; // } // } // stringLengthFit = i; // TypographyAvailabilities typography = glyphTypeface.FontFaceLayoutInfo.TypographyAvailabilities; // if ((charFastTextCheck & (byte)CharacterAttributeFlags.CharacterFastText) != 0) // { // // all input code points are Fast Text // if ((typography & // (TypographyAvailabilities.FastTextTypographyAvailable // | TypographyAvailabilities.FastTextMajorLanguageLocalizedFormAvailable // ) // ) != 0 // ) // { // // Considered too risky to optimize. It is either because the font // // has required features or the font has 'locl' lookup for major languages. // return false; // } // else if ((typography & TypographyAvailabilities.FastTextExtraLanguageLocalizedFormAvailable) != 0) // { // // The font has 'locl' lookup for FastText code points for non major languages. // // Check whether the input is major langauge. If it is, we are still good to optimize. // return MajorLanguages.Contains(cultureInfo); // } // else // { // // No FastText flags are present, safe to optimize // return true; // } // } // else if ((charFastTextCheck & (byte)CharacterAttributeFlags.CharacterIdeo) != 0) // { // // The input are all ideographs, check the IdeoTypographyAvailable bit. It is safe if // // the bit is not set. // return ((typography & TypographyAvailabilities.IdeoTypographyAvailable) == 0); // } // else // { // // for all the rest of the cases, just check whether there is any required typography // // present at all. If none exists, it is optimizable. We might under-optimize here but // // it will be non-major languages. // return ((typography & TypographyAvailabilities.Available) == 0); // } // } // /// <summary> // /// Lookup characters nominal glyphs and width // /// </summary> // /// <param name="charBufferRange">character buffer range</param> // /// <param name="emSize">height of Em</param> // /// <param name="toIdeal"> scaling factor from real to ideal unit </param> // /// <param name="nominalWidths">glyph nominal advances in ideal units</param> // /// <param name="idealWidth">total width in ideal units</param> // /// <returns>true for success</returns> // /// <remarks>This function is only used in fast path, and can only be called // /// if CheckFastPathNominalGlyphs has previously returned true.</remarks> // internal void GetCharacterNominalWidthsAndIdealWidth( // CharacterBufferRange charBufferRange, // double emSize, // double toIdeal, // out int[] nominalWidths, // out int idealWidth // ) // { // // This function should only be called if CheckFastPathNominalGlyphs has // // returned true so we can assume the ITypefaceMetrics is a GlyphTypeface. // GlyphTypeface glyphTypeface = TryGetGlyphTypeface(); // Invariant.Assert(glyphTypeface != null); // IDictionary<int, ushort> cmap = glyphTypeface.CharacterToGlyphMap; // nominalWidths = new int[charBufferRange.Length]; // idealWidth = 0; // for (int i = 0; i < charBufferRange.Length; i++) // { // ushort glyphIndex; // cmap.TryGetValue(charBufferRange[i], out glyphIndex); // double advance = emSize * glyphTypeface.GetAdvanceWidth(glyphIndex); // nominalWidths[i] = (int)Math.Round(advance * toIdeal); // idealWidth += nominalWidths[i]; // } // } // /// <summary> // /// Create correspondent hash code for the object // /// </summary> // /// <returns>object hash code</returns> // public override int GetHashCode() // { // int hash = _fontFamily.GetHashCode(); // if (_fallbackFontFamily != null) // hash = HashFn.HashMultiply(hash) + _fallbackFontFamily.GetHashCode(); // hash = HashFn.HashMultiply(hash) + _style.GetHashCode(); // hash = HashFn.HashMultiply(hash) + _weight.GetHashCode(); // hash = HashFn.HashMultiply(hash) + _stretch.GetHashCode(); // return HashFn.HashScramble(hash); // } // /// <summary> // /// Equality check // /// </summary> // public override bool Equals(object o) // { // Typeface t = o as Typeface; // if (t == null) // return false; // return _style == t._style // && _weight == t._weight // && _stretch == t._stretch // && _fontFamily.Equals(t._fontFamily) // && CompareFallbackFontFamily(t._fallbackFontFamily); // } // internal bool CompareFallbackFontFamily(FontFamily fallbackFontFamily) // { // if (fallbackFontFamily == null || _fallbackFontFamily == null) // return fallbackFontFamily == _fallbackFontFamily; // return _fallbackFontFamily.Equals(fallbackFontFamily); // } // //---------------------------------------- // // Private method // //---------------------------------------- // private CachedTypeface CachedTypeface // { // get // { // if (_cachedTypeface == null) // { // CachedTypeface cachedTypeface = TypefaceMetricsCache.ReadonlyLookup(this) as CachedTypeface; // if (cachedTypeface == null) // { // cachedTypeface = ConstructCachedTypeface(); // TypefaceMetricsCache.Add(this, cachedTypeface); // } // // For thread-safety, set the _cachedTypeface field only after we have a fully // // initialized CachedTypeface object. // _cachedTypeface = cachedTypeface; // } // return _cachedTypeface; // } // } // private CachedTypeface ConstructCachedTypeface() // { // FontStyle canonicalStyle = _style; // FontWeight canonicalWeight = _weight; // FontStretch canonicalStretch = _stretch; // // // // We always call FontFamily.FindFirstFontFamilyAndFace() method to resolve the // // canonical styles since the implied styles in FontFamily name will override // // the given styles in the Typeface. But we don't always use the IFontFamily // // instance returned from this method because an equal instance might already be // // cached. // // // FontFamily sourceFontFamily = FontFamily; // IFontFamily firstFontFamily = sourceFontFamily.FindFirstFontFamilyAndFace( // ref canonicalStyle, // ref canonicalWeight, // ref canonicalStretch // ); // if (firstFontFamily == null) // { // if (FallbackFontFamily != null) // { // sourceFontFamily = FallbackFontFamily; // firstFontFamily = sourceFontFamily.FindFirstFontFamilyAndFace( // ref canonicalStyle, // ref canonicalWeight, // ref canonicalStretch // ); // } // if (firstFontFamily == null) // { // sourceFontFamily = null; // firstFontFamily = FontFamily.LookupFontFamily(FontFamily.NullFontFamilyCanonicalName); // } // } // // If it's a named font, map all occurrences of the same name to one cached IFontFamily. // if (sourceFontFamily != null && sourceFontFamily.Source != null) // { // // We lookup in the cache to see if there is cached IFontFamily instance of the source FontFamily. Otherwise, // // this IFontFamily value is added to the TypefaceMetrics cache. // IFontFamily cachedValue = TypefaceMetricsCache.ReadonlyLookup(sourceFontFamily.FamilyIdentifier) as IFontFamily; // if (cachedValue != null) // { // firstFontFamily = cachedValue; // } // else // { // TypefaceMetricsCache.Add(sourceFontFamily.FamilyIdentifier, firstFontFamily); // } // } // ITypefaceMetrics typefaceMetrics = firstFontFamily.GetTypefaceMetrics(canonicalStyle, canonicalWeight, canonicalStretch); // return new CachedTypeface( // canonicalStyle, // canonicalWeight, // canonicalStretch, // firstFontFamily, // typefaceMetrics, // sourceFontFamily == null // ); // } //} } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D12_CityRoad (editable child object).<br/> /// This is a generated base class of <see cref="D12_CityRoad"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D11_CityRoadColl"/> collection. /// </remarks> [Serializable] public partial class D12_CityRoad : BusinessBase<D12_CityRoad> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="CityRoad_ID"/> property. /// </summary> public static readonly PropertyInfo<int> CityRoad_IDProperty = RegisterProperty<int>(p => p.CityRoad_ID, "CityRoads ID"); /// <summary> /// Gets the CityRoads ID. /// </summary> /// <value>The CityRoads ID.</value> public int CityRoad_ID { get { return GetProperty(CityRoad_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="CityRoad_Name"/> property. /// </summary> public static readonly PropertyInfo<string> CityRoad_NameProperty = RegisterProperty<string>(p => p.CityRoad_Name, "CityRoads Name"); /// <summary> /// Gets or sets the CityRoads Name. /// </summary> /// <value>The CityRoads Name.</value> public string CityRoad_Name { get { return GetProperty(CityRoad_NameProperty); } set { SetProperty(CityRoad_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D12_CityRoad"/> object. /// </summary> /// <returns>A reference to the created <see cref="D12_CityRoad"/> object.</returns> internal static D12_CityRoad NewD12_CityRoad() { return DataPortal.CreateChild<D12_CityRoad>(); } /// <summary> /// Factory method. Loads a <see cref="D12_CityRoad"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="D12_CityRoad"/> object.</returns> internal static D12_CityRoad GetD12_CityRoad(SafeDataReader dr) { D12_CityRoad obj = new D12_CityRoad(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D12_CityRoad"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D12_CityRoad() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D12_CityRoad"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(CityRoad_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D12_CityRoad"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(CityRoad_IDProperty, dr.GetInt32("CityRoad_ID")); LoadProperty(CityRoad_NameProperty, dr.GetString("CityRoad_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D12_CityRoad"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D10_City parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<ID12_CityRoadDal>(); using (BypassPropertyChecks) { int cityRoad_ID = -1; dal.Insert( parent.City_ID, out cityRoad_ID, CityRoad_Name ); LoadProperty(CityRoad_IDProperty, cityRoad_ID); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="D12_CityRoad"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<ID12_CityRoadDal>(); using (BypassPropertyChecks) { dal.Update( CityRoad_ID, CityRoad_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="D12_CityRoad"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<ID12_CityRoadDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(CityRoad_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <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 } }
// *********************************************************************** // Copyright (c) 2018 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Compatibility; namespace NUnit.Framework.Internal { internal abstract class ValueGenerator<T> : ValueGenerator { private static Exception CreateNotSupportedException(string description) { return new NotSupportedException($"{typeof(T)} is using the default value generator which does not support {description}."); } public virtual int Compare(T x, T y) { if (!typeof(IComparable<T>).IsAssignableFrom(typeof(T))) throw CreateNotSupportedException("comparisons"); return Comparer<T>.Default.Compare(x, y); } public IEnumerable<T> GenerateRange(T start, T end, Step step) { var startToEnd = Compare(start, end); if (startToEnd == 0) { yield return start; } else if ((startToEnd < 0 && !step.IsPositive) || (startToEnd > 0 && !step.IsNegative)) { throw new ArgumentException("Step must be in the direction of the end."); } else { for (var current = start;;) { yield return current; T next; try { next = step.Apply(current); } catch (OverflowException) { // We overflowed which means we tried to step past the end. break; } if (startToEnd < 0) { if (Compare(next, end) > 0) break; // We stepped past the end of the range. if (Compare(next, current) <= 0) throw new InvalidOperationException("The step must strictly increase."); } else { if (Compare(next, end) < 0) break; // We stepped past the end of the range. if (Compare(next, current) >= 0) throw new InvalidOperationException("The step must strictly decrease."); } current = next; } } } public sealed override IEnumerable GenerateRange(object start, object end, ValueGenerator.Step step) { return GenerateRange((T)start, (T)end, (Step)step); } /// <summary> /// Provides a convenient shorthand when <typeparamref name="TStep"/> is <see cref="IComparable{TStep}"/> /// and the default value of <typeparamref name="TStep"/> represents zero. /// </summary> public sealed class ComparableStep<TStep> : Step where TStep : IComparable<TStep> { private readonly TStep _step; private readonly Func<T, TStep, T> _apply; /// <summary> /// Initializes a new instance of the <see cref="ComparableStep{TStep}"/> class. /// </summary> /// <param name="value">The amount by which to increment each time this step is applied.</param> /// <param name="apply"> /// Must increment the given value and return the result. /// If the result is outside the range representable by <typeparamref name="T"/>, /// must throw <see cref="OverflowException"/>. If the result does not change due to lack /// of precision representable by <typeparamref name="T"/>, must throw <see cref="ArithmeticException"/>. /// </param> public ComparableStep(TStep value, Func<T, TStep, T> apply) { if (apply == null) throw new ArgumentNullException(nameof(apply)); _step = value; _apply = apply; } public override bool IsPositive => Comparer<TStep>.Default.Compare(default(TStep), _step) < 0; public override bool IsNegative => Comparer<TStep>.Default.Compare(_step, default(TStep)) < 0; /// <summary> /// Increments the given value and returns the result. /// If the result is outside the range representable by <typeparamref name="T"/>, /// throws <see cref="OverflowException"/>. If the result does not change due to lack /// of precision representable by <typeparamref name="T"/>, throws <see cref="ArithmeticException"/>. /// </summary> /// <exception cref="OverflowException"/> /// <exception cref="ArithmeticException"/> public override T Apply(T value) => _apply.Invoke(value, _step); } /// <summary> /// Encapsulates the ability to increment a <typeparamref name="T"/> value by an amount /// which may be of a different type. /// </summary> public new abstract class Step : ValueGenerator.Step { /// <summary> /// Increments the given value and returns the result. /// If the result is outside the range representable by <typeparamref name="T"/>, /// throws <see cref="OverflowException"/>. If the result does not change due to lack /// of precision representable by <typeparamref name="T"/>, throws <see cref="ArithmeticException"/>. /// </summary> /// <exception cref="OverflowException"/> /// <exception cref="ArithmeticException"/> public abstract T Apply(T value); } /// <summary> /// Creates a <see cref="Step"/> from the specified value if the current instance is able to /// use it to increment values of type <typeparamref name="T"/>. If the creation fails, /// <see cref="NotSupportedException"/> is thrown. /// </summary> /// <exception cref="NotSupportedException"/> public sealed override ValueGenerator.Step CreateStep(object value) { ValueGenerator.Step step; if (TryCreateStep(value, out step)) return step; throw CreateNotSupportedException($"creating a step of type {value.GetType()}"); } /// <summary> /// Creates a <see cref="Step"/> from the specified value if the current instance is able to /// use it to increment values of type <typeparamref name="T"/>. A return value indicates /// whether the creation succeeded. /// </summary> public override bool TryCreateStep(object value, out ValueGenerator.Step step) { Guard.ArgumentNotNull(value, nameof(value)); step = null; return false; } } internal abstract partial class ValueGenerator { public abstract IEnumerable GenerateRange(object start, object end, Step step); private static readonly MethodInfo GenericCreateMethod = typeof(ValueGenerator) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Single(method => method.Name == nameof(Create) && method.IsGenericMethod); public static ValueGenerator Create(Type valueType) { var genericInstantiation = GenericCreateMethod.MakeGenericMethod(valueType); var @delegate = (Func<ValueGenerator>)genericInstantiation.CreateDelegate(typeof(Func<ValueGenerator>)); return @delegate.Invoke(); } public static ValueGenerator<T> Create<T>() { // The JIT removes all branches which do not match T since it generates a separate version // of this method at runtime for every value type T. if (typeof(T) == typeof(sbyte)) return (ValueGenerator<T>)(object)new SByteValueGenerator(); if (typeof(T) == typeof(byte)) return (ValueGenerator<T>)(object)new ByteValueGenerator(); if (typeof(T) == typeof(short)) return (ValueGenerator<T>)(object)new Int16ValueGenerator(); if (typeof(T) == typeof(ushort)) return (ValueGenerator<T>)(object)new UInt16ValueGenerator(); if (typeof(T) == typeof(int)) return (ValueGenerator<T>)(object)new Int32ValueGenerator(); if (typeof(T) == typeof(uint)) return (ValueGenerator<T>)(object)new UInt32ValueGenerator(); if (typeof(T) == typeof(long)) return (ValueGenerator<T>)(object)new Int64ValueGenerator(); if (typeof(T) == typeof(ulong)) return (ValueGenerator<T>)(object)new UInt64ValueGenerator(); if (typeof(T) == typeof(float)) return (ValueGenerator<T>)(object)new SingleValueGenerator(); if (typeof(T) == typeof(double)) return (ValueGenerator<T>)(object)new DoubleValueGenerator(); if (typeof(T) == typeof(decimal)) return (ValueGenerator<T>)(object)new DecimalValueGenerator(); return new DefaultValueGenerator<T>(); } /// <summary> /// Encapsulates the ability to increment a value by an amount which may be of a different type. /// </summary> public abstract class Step { public abstract bool IsPositive { get; } public abstract bool IsNegative { get; } } /// <summary> /// Creates a <see cref="Step"/> from the specified value if the current instance is able to /// use it to increment the on values which it operates. If the creation fails, /// <see cref="NotSupportedException"/> is thrown. /// </summary> /// <exception cref="NotSupportedException"/> public abstract Step CreateStep(object value); /// <summary> /// Creates a <see cref="Step"/> from the specified value if the current instance is able to /// use it to increment values on which it operates. A return value indicates /// whether the creation succeeded. /// </summary> public abstract bool TryCreateStep(object value, out Step step); } }
// Copyright(c) 2016 Andrei Streltsov <[email protected]> // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; namespace Discriminated { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes", Justification = "Multiple type parameters are necessary.")] public class Union<T1, T2, T3, T4 > { int tag; T1 case1; T2 case2; T3 case3; T4 case4; public Union(T1 value) { this.case1 = value; tag = 1; } public Union(T2 value) { this.case2 = value; tag = 2; } public Union(T3 value) { this.case3 = value; tag = 3; } public Union(T4 value) { this.case4 = value; tag = 4; } public virtual TResult Match<TResult>( Func<T1, TResult> case1Handler, Func<T2, TResult> case2Handler, Func<T3, TResult> case3Handler, Func<T4, TResult> case4Handler ) { if (case1Handler == null) throw new ArgumentNullException("case1Handler"); if (case2Handler == null) throw new ArgumentNullException("case2Handler"); if (case3Handler == null) throw new ArgumentNullException("case3Handler"); if (case4Handler == null) throw new ArgumentNullException("case4Handler"); switch (tag) { case 1: return case1Handler(case1); case 2: return case2Handler(case2); case 3: return case3Handler(case3); case 4: return case4Handler(case4); default: throw new InvalidOperationException(); } } public virtual void Match( Action<T1> case1Handler, Action<T2> case2Handler, Action<T3> case3Handler, Action<T4> case4Handler ) { if (case1Handler == null) throw new ArgumentNullException("case1Handler"); if (case2Handler == null) throw new ArgumentNullException("case2Handler"); if (case3Handler == null) throw new ArgumentNullException("case3Handler"); if (case4Handler == null) throw new ArgumentNullException("case4Handler"); switch (tag) { case 1: case1Handler(case1); break; case 2: case2Handler(case2); break; case 3: case3Handler(case3); break; case 4: case4Handler(case4); break; default: throw new InvalidOperationException(); } } public static bool operator ==( Union<T1, T2, T3, T4 > instanceA, Union<T1, T2, T3, T4 > instanceB ) { if (ReferenceEquals(instanceA, null)) return ReferenceEquals(instanceB, null); return instanceA.Equals(instanceB); } public static bool operator !=( Union<T1, T2, T3, T4 > instanceA, Union<T1, T2, T3, T4 > instanceB) { return !(instanceA == instanceB); } public override bool Equals(object obj) { if (obj == null) return false; var other = obj as Union<T1, T2, T3, T4 >; if (other == null) return false; if (this.tag != other.tag) return false; return Case(this).Equals(Case(other)); } private static object Case(Union<T1, T2, T3, T4 > u) { switch (u.tag) { case 1: return u.case1; case 2: return u.case2; case 3: return u.case3; case 4: return u.case4; default: throw new InvalidOperationException(); } } public override int GetHashCode() { return 17 * this.tag + Case(this).GetHashCode(); } public string CaseToString() { switch (tag) { case 1: return case1.ToString(); case 2: return case2.ToString(); case 3: return case3.ToString(); case 4: return case4.ToString(); default: throw new InvalidOperationException(); } } public Type CaseType() { switch (tag) { case 1: return case1.GetType(); case 2: return case2.GetType(); case 3: return case3.GetType(); case 4: return case4.GetType(); default: throw new InvalidOperationException(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NExpect; using NUnit.Framework; using PeanutButter.RandomGenerators; using PeanutButter.TestUtils.Generic; using PeanutButter.Utils.Dictionaries; using static NExpect.Expectations; // ReSharper disable InconsistentNaming // ReSharper disable CollectionNeverUpdated.Local namespace PeanutButter.Utils.Tests.Dictionaries { [TestFixture] public class TestDefaultDictionary { [Test] public void Type_ShouldImplement_IDictionary() { // Arrange var sut = typeof(DefaultDictionary<string, bool>); // Pre-assert // Act sut.ShouldImplement<IDictionary<string, bool>>(); // Assert } [Test] public void IndexedValue_GivenNoDefaultResolverAtConstruction_WhenAskedForMissingValue_ShouldReturnDefaultOfT() { // Arrange var sut = Create<string, bool>(); var key = RandomValueGen.GetRandomString(); // Pre-assert // Act var result = sut[key]; // Assert Expect(result).To.Equal(default(bool)); } [Test] public void IndexedValue_GivenDefaultResolverAtConstruction_ShouldReturnThatValue() { // Arrange var expected = RandomValueGen.GetRandomString(); var key = RandomValueGen.GetRandomString(); var sut = Create<string, string>(() => expected); // Pre-assert // Act var result = sut[key]; // Assert Expect(result).To.Equal(expected); } [Test] public void IEnumerableEnumerator() { // Arrange var sut = Create<string, string>(() => "moo"); // Pre-assert // Act sut["cow"] = "beef"; var result = new List<KeyValuePair<string, string>>(); foreach (KeyValuePair<string, string> kvp in (sut as IEnumerable)) { result.Add(kvp); } // Assert Expect(result).To.Contain.Only(1) .Deep.Equal.To(new KeyValuePair<string, string>("cow", "beef")); } [Test] public void IndexedValue_WhenKeyExists_ShouldReturnThatValue() { // Arrange var expected = RandomValueGen.GetRandomString(); var key = RandomValueGen.GetRandomString(); var unexpected = RandomValueGen.GetAnother(expected); var sut = Create<string, string>(() => unexpected); // Pre-assert // Act sut[key] = expected; var result = sut[key]; // Assert Expect(result).To.Equal(expected); } [Test] public void ContainsKey_ShouldReturnTrue() { // Arrange var haveKey = RandomValueGen.GetRandomString(); var missingKey = RandomValueGen.GetAnother(haveKey); var sut = Create<string, string>(); sut[haveKey] = RandomValueGen.GetRandomString(); // Pre-assert // Act var haveResult = sut.ContainsKey(haveKey); var missingResult = sut.ContainsKey(missingKey); // Assert Expect(haveResult).To.Be.True(); Expect(missingResult).To.Be.True(); } [Test] public void Enumeration_ShouldPassThrough() { // Arrange var k1 = RandomValueGen.GetRandomString(); var k2 = RandomValueGen.GetAnother(k1); var v1 = RandomValueGen.GetRandomString(); var v2 = RandomValueGen.GetAnother(v1); var sut = Create<string, string>(); sut[k1] = v1; sut[k2] = v2; var collector = new List<KeyValuePair<string, string>>(); // Pre-assert // Act foreach (var kvp in sut) { collector.Add(kvp); } // Assert Expect(collector.Count).To.Equal(2); Expect(collector).To.Contain.Exactly(1).Equal.To(new KeyValuePair<string, string>(k1, v1)); Expect(collector).To.Contain.Exactly(1).Equal.To(new KeyValuePair<string, string>(k2, v2)); } [Test] public void Add_GivenKeyValuePair_ShouldPassThrough() { // Arrange var sut = Create<string, string>(); var kvp = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); // Pre-assert // Act sut.Add(kvp); // Assert Expect(sut[kvp.Key]).To.Equal(kvp.Value); } [Test] public void Clear_ShouldPassThrough() { // Arrange var sut = Create<string, string>(); var item = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); sut.Add(item); // Pre-assert Expect(sut[item.Key]).To.Equal(item.Value); // Act sut.Clear(); // Assert Expect(sut[item.Key]).To.Be.Null(); } [Test] public void Contains_ShouldReturnTrue() { // Arrange var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); var missing = RandomValueGen.GetAnother(have); var sut = Create<string, string>(); sut.Add(have); // Pre-assert // Act var haveResult = sut.Contains(have); var missingResult = sut.Contains(missing); // Assert Expect(haveResult).To.Be.True(); Expect(missingResult).To.Be.True(); } [Test] public void Remove_GivenKeyValuePair_ShouldPassThrough_SortOf() { // Arrange var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); var missing = RandomValueGen.GetAnother(have); var sut = Create<string, string>(); sut.Add(have); // Pre-assert Expect(sut[have.Key]).Not.To.Be.Null(); // Act var haveResult = sut.Remove(have); var missingResult = sut.Remove(missing); // Assert Expect(haveResult).To.Be.True(); Expect(missingResult).To.Be.False(); Expect(sut[have.Key]).To.Be.Null(); } [Test] public void Remove_GivenKey_ShouldPassThrough() { // Arrange var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); var missing = RandomValueGen.GetAnother(have); var sut = Create<string, string>(); sut.Add(have); Expect(sut[have.Key]).Not.To.Be.Null(); // Pre-assert // Act var haveResult = sut.Remove(have.Key); var missingResult = sut.Remove(missing.Key); // Assert Expect(haveResult).To.Be.True(); Expect(missingResult).To.Be.False(); Expect(sut[have.Key]).To.Be.Null(); } [Test] public void Add_GivenKeyAndValue_ShouldPassThrough() { // Arrange var sut = Create<string, string>(); var kvp = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); // Pre-assert // Act sut.Add(kvp.Key, kvp.Value); // Assert Expect(sut[kvp.Key]).To.Equal(kvp.Value); } [Test] public void TryGetValue_WhenKeyIsKnown_ShouldReturnThatValue() { // Arrange var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>(); var sut = Create<string, string>(); sut.Add(have); // Pre-assert // Act var result = sut.TryGetValue(have.Key, out var found); // Assert Expect(result).To.Be.True(); Expect(found).To.Equal(have.Value); } [Test] public void TryGetValue_WhenKeyIsUnknown_ShouldReturnDefault() { // Arrange var expected = RandomValueGen.GetRandomString(); var sut = Create<string, string>(() => expected); // Pre-assert // Act var result = sut.TryGetValue(RandomValueGen.GetRandomString(), out var found); // Assert Expect(result).To.Be.True(); Expect(found).To.Equal(expected); } [Test] public void CopyTo_ShouldCopyKnownKeyValuePairs() { // Arrange var start = RandomValueGen.GetRandomInt(2, 4); var arraySize = RandomValueGen.GetRandomInt(10, 15); var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>(2, 4); var target = new KeyValuePair<string, string>[arraySize]; var sut = Create<string, string>(); items.ForEach(sut.Add); // Pre-assert // Act sut.CopyTo(target, start); // Assert var defaultValue = default(KeyValuePair<string, string>); PyLike.Range(start).ForEach(i => Expect(target[i]).To.Equal(defaultValue)); PyLike.Range(start + items.Length, arraySize).ForEach( i => Expect(target[i]).To.Equal(defaultValue)); items.ForEach(i => Expect(target).To.Contain.Exactly(1).Equal.To(i)); } [Test] public void Count_ShouldReturnActualCount() { // Arrange var sut = Create<string, bool>(); var items = RandomValueGen.GetRandomArray<KeyValuePair<string, bool>>(); items.ForEach(sut.Add); // Pre-assert // Act var result = sut.Count; // Assert Expect(result).To.Equal(items.Length); } [Test] public void IsReadonly_ShouldReturnFalse() { // Arrange var sut = Create<int, bool>(); // Pre-assert // Act var result = sut.IsReadOnly; // Assert Expect(result).To.Be.False(); } [Test] public void Keys_ShouldReturnKnownKeys() { // Arrange var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>(); var sut = Create<string, string>(); items.ForEach(sut.Add); // Pre-assert // Act var result = sut.Keys; // Assert // TODO: swap out with To.Be.Equivalent.To() when the syntax is available in NExpect Assert.That(result, Is.EquivalentTo(items.Select(i => i.Key))); } [Test] public void Values_ShouldReturnKnownValues() { // Arrange var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>(); var sut = Create<string, string>(); items.ForEach(sut.Add); // Pre-assert // Act var result = sut.Values; // Assert // TODO: swap out with To.Be.Equivalent.To() when the syntax is available in NExpect Assert.That(result, Is.EquivalentTo(items.Select(i => i.Value))); } [Test] public void IndexFetch_WithSmartResolver_ShouldReturnExpectedValue() { // Arrange var sut = new DefaultDictionary<string, string>(s => s + "moo"); var index = RandomValueGen.GetRandomString(); var expected = index + "moo"; // Pre-Assert // Act var result = sut[index]; // Assert Expect(result).To.Equal(expected); } [Test] public void Instance_ShouldAppearToBeCaseInsensitive() { // Arrange var dict = new DefaultDictionary<string, object>(); // Pre-Assert // Act var result = dict.GetPropertyValue("Comparer"); // Assert Expect(result).To.Equal(StringComparer.OrdinalIgnoreCase); } private IDictionary<TKey, TValue> Create<TKey, TValue>( Func<TValue> defaultResolver = null ) { return defaultResolver == null ? new DefaultDictionary<TKey, TValue>() : new DefaultDictionary<TKey, TValue>( defaultResolver ); } } }
using System; namespace OpenCTM { public class MG2Encoder : MG1Encoder { public const float STANDARD_NORMAL_PRECISION = 1f / 256f; public const float STANDARD_VERTEX_PRECISION = 1f / 1024f; public readonly float vertexPrecision, normalPrecision; public MG2Encoder (float vertexPrecision = STANDARD_VERTEX_PRECISION, float normalPrecision = STANDARD_NORMAL_PRECISION) { this.vertexPrecision = vertexPrecision; this.normalPrecision = normalPrecision; } public override int getTag () { return MG2Decoder.MG2_Tag; } public override void encode (Mesh m, CtmOutputStream output) { Grid grid = setupGrid (m.vertices); SortableVertex[] sorted = sortVertices (grid, m.vertices); int[] vdeltas = makeVertexDeltas (m.vertices, sorted, grid); int[] gridIndicies = new int[m.getVertexCount ()]; gridIndicies [0] = sorted [0].gridIndex; for (int i = 1; i < m.getVertexCount(); ++i) { gridIndicies [i] = sorted [i].gridIndex - sorted [i - 1].gridIndex; } output.writeLittleInt (MG2Decoder.MG2_HEADER_TAG); output.writeLittleFloat (vertexPrecision); output.writeLittleFloat (normalPrecision); grid.writeToStream (output); output.writeLittleInt (MeshDecoder.VERT); output.writePackedInts (vdeltas, m.getVertexCount (), Mesh.CTM_POSITION_ELEMENT_COUNT, false); output.writeLittleInt (MG2Decoder.GIDX); output.writePackedInts (gridIndicies, m.getVertexCount (), 1, false); output.writeLittleInt (MeshDecoder.INDX); int[] indices = reIndexIndices (sorted, m.indices); rearrangeTriangles (indices); //write indicies { int[] deltas = new int[indices.Length]; Array.Copy(indices, deltas, indices.Length); makeIndexDeltas (deltas); output.writePackedInts (deltas, m.getTriangleCount (), 3, false); } if (m.hasNormals ()) { for (int i = 1; i < m.getVertexCount(); i++) { gridIndicies [i] += gridIndicies [i - 1]; } float[] restoredv = CommonAlgorithm.restoreVertices (vdeltas, gridIndicies, grid, vertexPrecision); output.writeLittleInt (MeshDecoder.NORM); int[] intNormals = makeNormalDeltas (restoredv, m.normals, indices, sorted); output.writePackedInts (intNormals, m.getVertexCount (), Mesh.CTM_NORMAL_ELEMENT_COUNT, false); } foreach (AttributeData ad in m.texcoordinates) { output.writeLittleInt (MeshDecoder.TEXC); output.writeString (ad.name); output.writeString (ad.materialName); output.writeLittleFloat (ad.precision); int[] deltas = makeUVCoordDeltas (ad, sorted); output.writePackedInts (deltas, m.getVertexCount (), Mesh.CTM_UV_ELEMENT_COUNT, true); } foreach (AttributeData ad in m.attributs) { output.writeLittleInt (MeshDecoder.ATTR); output.writeString (ad.name); output.writeLittleFloat (ad.precision); int[] deltas = makeAttribDeltas (ad, sorted); output.writePackedInts (deltas, m.getVertexCount (), Mesh.CTM_ATTR_ELEMENT_COUNT, true); } } /** * Setup the 3D space subdivision grid. */ public Grid setupGrid (float[] vertices) { int vc = vertices.Length / 3; //CTM_POSITION_ELEMENT_COUNT == 3 // Calculate the mesh boundinggrid. box float[] min = new float[3]; float[] max = new float[3]; int[] division = new int[3]; for (int i = 0; i < 3; ++i) { min [i] = max [i] = vertices [i]; } for (int i = 1; i < vc; ++i) { for (int j = 0; j < 3; j++) { min [j] = Math.Min (min [j], vertices [i * 3 + j]); max [j] = Math.Max (max [j], vertices [i * 3 + j]); } } // Determine optimal grid resolution, based on the number of vertices and // the bounding box. // NOTE: This algorithm is quite crude, and could very well be optimized for // better compression levels in the future without affecting the file format // or backward compatibility at all. float[] factor = new float[3]; for (int i = 0; i < 3; ++i) { factor [i] = max [i] - min [i]; } float sum = factor [0] + factor [1] + factor [2]; if (sum > 1e-30f) { sum = 1.0f / sum; for (int i = 0; i < 3; ++i) { factor [i] *= sum; } double wantedGrids = Math.Pow (100.0f * vc, 1.0f / 3.0f); for (int i = 0; i < 3; ++i) { division [i] = (int)Math.Ceiling (wantedGrids * factor [i]); if (division [i] < 1) { division [i] = 1; } } } else { division [0] = 4; division [1] = 4; division [2] = 4; } return new Grid (min, max, division); } /** * Convert a point to a grid index. */ private int pointToGridIdx (Grid grid, float[] point) { int[] idx = new int[3]; float[] size = grid.getSize (); for (int i = 0; i < 3; ++i) { idx [i] = (int)Math.Floor ((point [i] - grid.getMin () [i]) / size [i]); if (idx [i] >= grid.getDivision () [i]) { idx [i] = grid.getDivision () [i] - 1; } } return idx [0] + grid.getDivision () [0] * (idx [1] + grid.getDivision () [1] * idx [2]); } public SortableVertex[] sortVertices (Grid grid, float[] v) { // Prepare sort vertex array int vc = v.Length / Mesh.CTM_POSITION_ELEMENT_COUNT; SortableVertex[] sortVertices = new SortableVertex[vc]; for (int i = 0; i < vc; ++i) { // Store vertex properties in the sort vertex array float[] point = new float[]{v [i * 3], v [i * 3 + 1], v [i * 3 + 2]}; int p2g = pointToGridIdx (grid, point); sortVertices [i] = new SortableVertex (v [i * 3], p2g, i); } // Sort vertices. The elements are first sorted by their grid indices, and // scondly by their x coordinates. Array.Sort (sortVertices); return sortVertices; } /** * Re-index all indices, based on the sorted vertices. */ private int[] reIndexIndices (SortableVertex[] sortVertices, int[] indices) { // Create temporary lookup-array, O(n) int[] indexLUT = new int[sortVertices.Length]; int[] newIndices = new int[indices.Length]; for (int i = 0; i < sortVertices.Length; ++i) { indexLUT [sortVertices [i].originalIndex] = i; } // Convert old indices to new indices, O(n) for (int i = 0; i < indices.Length; ++i) { newIndices [i] = indexLUT [indices [i]]; } return newIndices; } /** * Calculate various forms of derivatives in order to reduce data entropy. */ private int[] makeVertexDeltas (float[] vertices, SortableVertex[] sortVertices, Grid grid) { int vc = sortVertices.Length; // Vertex scaling factor float scale = 1.0f / vertexPrecision; float prevGridIndex = 0x7fffffff; int prevDeltaX = 0; int[] intVertices = new int[vc * Mesh.CTM_POSITION_ELEMENT_COUNT]; for (int i = 0; i < vc; ++i) { // Get grid box origin int gridIdx = sortVertices [i].gridIndex; float[] gridOrigin = CommonAlgorithm.gridIdxToPoint (grid, gridIdx); // Get old vertex coordinate index (before vertex sorting) int oldIdx = sortVertices [i].originalIndex; // Store delta to the grid box origin in the integer vertex array. For the // X axis (which is sorted) we also do the delta to the previous coordinate // in the box. int deltaX = (int)Math.Floor (scale * (vertices [oldIdx * 3] - gridOrigin [0]) + 0.5f); if (gridIdx == prevGridIndex) { intVertices [i * 3] = deltaX - prevDeltaX; } else { intVertices [i * 3] = deltaX; } intVertices [i * 3 + 1] = (int)Math.Floor (scale * (vertices [oldIdx * 3 + 1] - gridOrigin [1]) + 0.5f); intVertices [i * 3 + 2] = (int)Math.Floor (scale * (vertices [oldIdx * 3 + 2] - gridOrigin [2]) + 0.5f); prevGridIndex = gridIdx; prevDeltaX = deltaX; } return intVertices; } /** * Convert the normals to a new coordinate system: magnitude, phi, theta * (relative to predicted smooth normals). */ private int[] makeNormalDeltas (float[] vertices, float[] normals, int[] indices, SortableVertex[] sortVertices) { // Calculate smooth normals (Note: aVertices and aIndices use the sorted // index space, so smoothNormals will too) float[] smoothNormals = CommonAlgorithm.calcSmoothNormals (vertices, indices); // Normal scaling factor float scale = 1.0f / normalPrecision; int vc = vertices.Length / Mesh.CTM_POSITION_ELEMENT_COUNT; int[] intNormals = new int[vc * Mesh.CTM_NORMAL_ELEMENT_COUNT]; for (int i = 0; i < vc; ++i) { // Get old normal index (before vertex sorting) int oldIdx = sortVertices [i].originalIndex; // Calculate normal magnitude (should always be 1.0 for unit length normals) float magn = (float)Math.Sqrt (normals [oldIdx * 3] * normals [oldIdx * 3] + normals [oldIdx * 3 + 1] * normals [oldIdx * 3 + 1] + normals [oldIdx * 3 + 2] * normals [oldIdx * 3 + 2]); if (magn < 1e-10f) { magn = 1.0f; } // Invert magnitude if the normal is negative compared to the predicted // smooth normal if ((smoothNormals [i * 3] * normals [oldIdx * 3] + smoothNormals [i * 3 + 1] * normals [oldIdx * 3 + 1] + smoothNormals [i * 3 + 2] * normals [oldIdx * 3 + 2]) < 0.0f) { magn = -magn; } // Store the magnitude in the first element of the three normal elements intNormals [i * 3] = (int)Math.Floor (scale * magn + 0.5f); // Normalize the normal (1 / magn) - and flip it if magn < 0 magn = 1.0f / magn; float[] n = new float[3]; for (int j = 0; j < 3; ++j) { n [j] = normals [oldIdx * 3 + j] * magn; } // Convert the normal to angular representation (phi, theta) in a coordinate // system where the nominal (smooth) normal is the Z-axis float[] basisAxes = CommonAlgorithm.makeNormalCoordSys (smoothNormals, i * 3); float[] n2 = new float[3]; for (int j = 0; j < 3; ++j) { n2 [j] = basisAxes [j * 3] * n [0] + basisAxes [j * 3 + 1] * n [1] + basisAxes [j * 3 + 2] * n [2]; } double phi, theta, thetaScale; if (n2 [2] >= 1.0f) { phi = 0.0f; } else { phi = Math.Acos (n2 [2]); } theta = Math.Atan2 (n2 [1], n2 [0]); // Round phi and theta (spherical coordinates) to integers. Note: We let the // theta resolution vary with the x/y circumference (roughly phi). int intPhi = (int)Math.Floor (phi * (scale / (0.5 * Math.PI)) + 0.5); if (intPhi == 0) { thetaScale = 0.0; } else if (intPhi <= 4) { thetaScale = 2.0 / Math.PI; } else { thetaScale = intPhi / (2.0 * Math.PI); } intNormals [i * 3 + 1] = intPhi; intNormals [i * 3 + 2] = (int)Math.Floor ((theta + Math.PI) * thetaScale + 0.5f); } return intNormals; } /** * Calculate various forms of derivatives in order to reduce data entropy. */ private int[] makeUVCoordDeltas (AttributeData map, SortableVertex[] sortVertices) { // UV coordinate scaling factor float scale = 1.0f / map.precision; int vc = sortVertices.Length; int prevU = 0, prevV = 0; int[] intUVCoords = new int[vc * Mesh.CTM_UV_ELEMENT_COUNT]; for (int i = 0; i < vc; ++i) { // Get old UV coordinate index (before vertex sorting) int oldIdx = sortVertices [i].originalIndex; // Convert to fixed point int u = (int)Math.Floor (scale * map.values [oldIdx * 2] + 0.5f); int v = (int)Math.Floor (scale * map.values [oldIdx * 2 + 1] + 0.5f); // Calculate delta and store it in the converted array. NOTE: Here we rely // on the fact that vertices are sorted, and usually close to each other, // which means that UV coordinates should also be close to each other... intUVCoords [i * 2] = u - prevU; intUVCoords [i * 2 + 1] = v - prevV; prevU = u; prevV = v; } return intUVCoords; } /** * Calculate various forms of derivatives in order to reduce data entropy. */ private int[] makeAttribDeltas (AttributeData map, SortableVertex[] sortVertices) { // Attribute scaling factor float scale = 1.0f / map.precision; int[] prev = new int[4]; int vc = sortVertices.Length; int[] intAttribs = new int[vc * Mesh.CTM_ATTR_ELEMENT_COUNT]; for (int i = 0; i < vc; ++i) { // Get old attribute index (before vertex sorting) int oldIdx = sortVertices [i].originalIndex; // Convert to fixed point, and calculate delta and store it in the converted // array. NOTE: Here we rely on the fact that vertices are sorted, and // usually close to each other, which means that attributes should also // be close to each other (and we assume that they somehow vary slowly with // the geometry)... for (int j = 0; j < 4; ++j) { int value = (int)Math.Floor (scale * map.values [oldIdx * 4 + j] + 0.5f); intAttribs [i * 4 + j] = value - prev [j]; prev [j] = value; } } return intAttribs; } } }
using System; using System.Collections.Generic; using System.Linq; namespace RMArt.Core { public static class TagsHelper { public const string TagmeTagName = "tagme"; public static readonly char[] TagSeparators = new[] { ';', ',' }; public static readonly char[] SearchTagSeparators = TagSeparators.Concat(new[] { ' ' }).ToArray(); public const int MaxTagNameLength = 200; public const string NotExistingTagName = "[deleted]"; private const char _escapeCharacter = '"'; public static TagsParsingResult ParseTagNames(string tags, bool allowTagme = true) { var res = new TagsParsingResult(); if (string.IsNullOrEmpty(tags)) return res; foreach (var t in tags.Split(TagSeparators).Select(t => t.Trim()).Where(t => t != "")) if (string.Equals(t, TagmeTagName, StringComparison.OrdinalIgnoreCase)) if (allowTagme) res.TagmeIncluded = true; else res.InvalidNames.Add(t); else if (IsValidTagName(t)) res.Names.Add(t); else res.InvalidNames.Add(t); return res; } public static string EncodeTagName(string tag) { if (tag == null) throw new ArgumentNullException("tag"); return tag.IndexOfAny(SearchTagSeparators) > -1 ? _escapeCharacter + tag + _escapeCharacter : tag; } public static TagType? ParseTagType(string tagName, out string tagNameWithoutPrefix) { if (tagName == null) throw new ArgumentNullException("tagName"); tagName = tagName.Trim(); TagType? tagType = null; if (tagName.StartsWith(TagType.Copyright + ":", StringComparison.OrdinalIgnoreCase)) tagType = TagType.Copyright; else if (tagName.StartsWith(TagType.Character + ":", StringComparison.OrdinalIgnoreCase)) tagType = TagType.Character; else if (tagName.StartsWith(TagType.Artist + ":", StringComparison.OrdinalIgnoreCase)) tagType = TagType.Artist; else if (tagName.StartsWith(TagType.General + ":", StringComparison.OrdinalIgnoreCase)) tagType = TagType.General; tagNameWithoutPrefix = tagType != null ? tagName.Substring(tagName.IndexOf(':') + 1).TrimStart() : tagName; return tagType; } public static bool IsValidTagName(string tag) { if (string.IsNullOrWhiteSpace(tag) || tag.Length > MaxTagNameLength) return false; if (tag.Equals(TagmeTagName, StringComparison.OrdinalIgnoreCase)) return false; return tag.IndexOf(_escapeCharacter) < 0; } public static string GetDisplayName(this Tag tag) { return tag == null ? NotExistingTagName : tag.Name; } public static int? GetIDByName(this ITagsService tagsService, string name) { return tagsService .Find(new TagsQuery { Name = name }) .Select(t => (int?)t.ID) .SingleOrDefault(); } public static ISet<int> GetSearchTagIDs(this ITagsService tagsService, IEnumerable<string> names) { bool dummy; return GetSearchTagIDs(tagsService, names, out dummy); } public static ISet<int> GetSearchTagIDs(this ITagsService tagsService, IEnumerable<string> names, out bool notFound) { var res = new HashSet<int>(); notFound = false; foreach (var tagID in names.Select(tagsService.GetIDByName)) { if (tagID != null) res.Add(tagID.Value); else notFound = true; } res.TrimExcess(); return res; } public static ISet<int> GetAssignTagIDs(this ITagsService tagsService, IEnumerable<string> tagNames, ModerationStatus status, Identity identity, bool withParents) { if (tagsService == null) throw new ArgumentNullException("tagsService"); if (tagNames == null) throw new ArgumentNullException("tagNames"); if (identity == null) throw new ArgumentNullException("identity"); var res = new HashSet<int>(); foreach (var name in tagNames) { string nameWithoutPrefix; var type = ParseTagType(name, out nameWithoutPrefix); int tagID; var exsistingTagID = tagsService.GetIDByName(nameWithoutPrefix); if (exsistingTagID != null) { var exsisting = tagsService.LoadTag(exsistingTagID.Value); if (exsisting.Status == ModerationStatus.Declined || (type != null && exsisting.Type != type.Value)) continue; tagID = exsisting.ID; } else { tagID = tagsService.Create(nameWithoutPrefix, type ?? TagType.General, status, identity); if (status == ModerationStatus.Declined) continue; } if (withParents) GetParentsRecursive(tagsService, tagID, res); res.Add(tagID); } res.TrimExcess(); return res; } public static void Merge(this ITagsService tagsService, int sourceID, int destantionID, Identity identity) { if (tagsService == null) throw new ArgumentNullException("tagsService"); if (sourceID == destantionID) throw new InvalidOperationException("Source and destantion are equls."); var source = tagsService.LoadTag(sourceID); var destantion = tagsService.LoadTag(destantionID); if (source == null) throw new ArgumentException("Source tag does non exists.", "sourceID"); if (destantion == null) throw new ArgumentException("Destantion tag does non exists.", "destantionID"); tagsService.Delete(source.ID); tagsService.Update( destantionID, new TagUpdate { AddAliases = new[] { source.Name }.Concat(source.AliasNames).ToArray(), AddParents = source.ParentIDs }, identity); foreach (var childrenID in source.ChildrenIDs) tagsService.Update(childrenID, new TagUpdate { AddParents = new[] { destantionID } }, identity); } public static void DeleteDeclined(this ITagsService tagsService, IPicturesService picturesService, Identity identity) { var declinedTags = tagsService.Find(new TagsQuery { AllowedStatuses = new SortedSet<ModerationStatus> { ModerationStatus.Declined } }).Select(t => t.ID); foreach (var tid in declinedTags) { picturesService.RemoveTag(tid, identity); tagsService.Delete(tid); } } public static bool IsChildren(this ITagsService tagsService, int parentTagID, int childrenTagID, bool recursive) { var childs = tagsService.GetChildsOf(parentTagID, false); return childs.Contains(childrenTagID) || (recursive && childs.Any(tid => tagsService.IsChildren(tid, childrenTagID, true))); } public static ICollection<int> GetChildsOf(this ITagsService tagsService, int tagID, bool recursive) { if (recursive) { var res = new HashSet<int>(); GetChildrensRecursive(tagsService, tagID, res); res.TrimExcess(); return res; } return tagsService.LoadTag(tagID).ChildrenIDs; } public static ICollection<int> GetParentsOf(this ITagsService tagsService, int tagID, bool recursive) { if (recursive) { var res = new HashSet<int>(); GetParentsRecursive(tagsService, tagID, res); res.TrimExcess(); return res; } return tagsService.LoadTag(tagID).ParentIDs; } private static void GetChildrensRecursive(ITagsService tagsService, int id, ISet<int> output) { foreach (var c in tagsService.LoadTag(id).ChildrenIDs) if (output.Add(c)) GetChildrensRecursive(tagsService, c, output); } private static void GetParentsRecursive(ITagsService tagsService, int id, ISet<int> output) { foreach (var p in tagsService.LoadTag(id).ParentIDs) if (output.Add(p)) GetParentsRecursive(tagsService, p, output); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using OpenLiveWriter.Localization; namespace OpenLiveWriter.CoreServices { public class StringHelper { public static Encoding GetEncoding(string charset, Encoding defaultEncoding) { if (!String.IsNullOrEmpty(charset)) { if (string.Compare(Encoding.UTF8.WebName, charset, StringComparison.OrdinalIgnoreCase) == 0) { return new UTF8Encoding(false, false); } else { try { return Encoding.GetEncoding(charset); } catch (ArgumentException e) { Debug.WriteLine("BUG: Failed getting encoding for charset " + charset + "with error: " + e); } } } return defaultEncoding; } public static string Join(object[] anArray) { if (anArray == null) return null; return Join(anArray, ", "); } public static string Join(object[] anArray, string delimiter) { return Join(anArray, delimiter, false); } public static string Join(object[] anArray, string delimiter, bool removeEmpty) { StringBuilder o = new StringBuilder(); string delim = ""; foreach (object obj in anArray) { string str = String.Empty; if (obj != null) str = obj.ToString().Trim(); if (!removeEmpty || (str != String.Empty)) { o.Append(delim); if (obj != null) { o.Append(str); delim = delimiter; } } } return o.ToString(); } public static string[] Split(string aString, string delimiter) { if (aString.Length == 0) return new string[0]; ArrayList list = new ArrayList(); int start = 0; int next; int delimLength = delimiter.Length; while (start < aString.Length && (next = aString.IndexOf(delimiter, start, StringComparison.CurrentCulture)) != -1) { string chunk = aString.Substring(start, (next - start)).Trim(); if (chunk != "") list.Add(chunk); start = next + delimLength; } if (start == 0) { // short circuit when none found return new string[] { aString }; } if (start < aString.Length) { string chunk = aString.Substring(start).Trim(); if (chunk != "") list.Add(chunk); } return (string[])list.ToArray(typeof(string)); } // strips spaces and tabs from around hard returns private static LazyLoader<Regex> _stripSpaces; private static Regex StripSpacesRegex { get { return _stripSpaces.Value; } } // turns single hard return into a space private static LazyLoader<Regex> _stripSingleLineFeeds; private static Regex StripSingleLineFeedsRegex { get { return _stripSingleLineFeeds.Value; } } static StringHelper() { _stripSingleLineFeeds = new LazyLoader<Regex>(() => new Regex(@"(?<=\S)\r?\n(?=\S)")); _stripSpaces = new LazyLoader<Regex>(() => new Regex(@"[ \t]*\r?\n[ \t]*")); } public static string StripSingleLineFeeds(string val) { return StripSingleLineFeedsRegex.Replace(StripSpacesRegex.Replace(val, "\r\n"), " "); } public static string Ellipsis(string val, int threshold) { /* * Some edge cases that are somewhat bogus: * Ellipsis(".........", 8) => "..." * Ellipsis(". . . . .", 8) => "..." */ if (val.Length > threshold) { return string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.WithEllipses), val.Substring(0, threshold).TrimEnd(' ', '\r', '\n', '\t', '.')); } else return val; } /// <summary> /// Splits a string at a specified delimiter, with escape logic. For example: /// /// SplitWithEscape("one/two/three", '/', '_') => ["one", "two", "three"] /// SplitWithEscape("one_/two/three_/four", '/', '_') => ["one/two", "three/four"] /// SplitWithEscape("one__two/three", '/', '_') => ["one_two", "three"] /// SplitWithEscape("one/two/three_", '/', '_') => ["one", "two", "three_"] /// SplitWithEscape("", '/', '_') => [] /// </summary> public static string[] SplitWithEscape(string val, char delimiter, char escapeChar) { if (delimiter == escapeChar) throw new ArgumentException("Delimiter and escape characters cannot be identical."); ArrayList results = new ArrayList(); char[] buffer = new char[val.Length]; // no element can be longer than the original string int pos = 0; // our pointer into the buffer bool escaped = false; foreach (char thisChar in val.ToCharArray()) { if (escaped) { // the last character was the escape char; this char // should not be evaluated, just written buffer[pos++] = thisChar; escaped = false; } else { if (thisChar == escapeChar) { // encountering escape char; do nothing, just make // sure next character is written escaped = true; } else if (thisChar == delimiter) { // encountering delimiter; add current buffer to results results.Add(new string(buffer, 0, pos)); pos = 0; } else { // normal character; just print buffer[pos++] = thisChar; } } } // If last char was the escape char, add it to the end of the last string. // If this happens, the string was actually malformed, but whatever. if (escaped) buffer[pos++] = escapeChar; // add the last string to the collection if (pos != 0) results.Add(new string(buffer, 0, pos)); return (string[])results.ToArray(typeof(string)); } public static string RestrictLength(string val, int maxLen) { if (val.Length <= maxLen) return val; else return val.Substring(0, maxLen); } public static string RestrictLengthAtWords(string content, int maxSize) { if (maxSize == 0) return string.Empty; //chop off the word at the last space before index maxSize. if (content != null && content.Length > maxSize) { int lastWordIndex = content.LastIndexOfAny(Whitespace, maxSize - 1, maxSize); if (lastWordIndex != -1) { return content.Substring(0, lastWordIndex).TrimEnd(Whitespace); } } return content; } public static string GetLastWord(string content) { if (String.IsNullOrEmpty(content)) return string.Empty; // Any whitespace at the end is not considered part of the last word. content = content.TrimEnd(Whitespace); if (String.IsNullOrEmpty(content)) return string.Empty; int beforeLastWord = content.LastIndexOfAny(Whitespace); if (beforeLastWord > -1 && beforeLastWord < content.Length - 1) { content = content.Substring(beforeLastWord + 1); } return content; } private static readonly char[] Whitespace = new char[] { ' ', '\r', '\n', '\t' }; private const long KB = 1024L; private const long MB = KB * KB; private const long GB = KB * KB * KB; private const string PATTERN = "{0:#,##0.0000}"; /// <summary> /// Same as FormatByteCount, but negative values will be /// interpreted as (not available). /// </summary> public static string FormatByteCountNoNegatives(long bytes, string naString) { if (bytes < 0) return naString; else return FormatByteCount(bytes); } /// <summary> /// Format a bytecount in a nice, pretty way. Similar to the /// way Windows Explorer displays sizes. /// /// 1) Decide what the units will be. /// 2) Scale the bytecount to the chosen unit, as a double. /// 3) Format the double, to a relatively high degree of precision. /// 4) Truncate the number of digits shown to the greater of: /// a) the number of digits in the whole-number part /// b) 3 /// </summary> public static string FormatByteCount(long bytes) { string num; string format; if (bytes < KB) { num = bytes.ToString("N", CultureInfo.CurrentCulture); format = Res.Get(StringId.BytesFormat); } else if (bytes < (MB * 0.97)) // this is what Windows does { num = FormatNum((double)bytes / KB); format = Res.Get(StringId.KilobytesFormat); } else if (bytes < (GB * 0.97)) // this is what Windows does { num = FormatNum((double)bytes / MB); format = Res.Get(StringId.MegabytesFormat); } else { num = FormatNum((double)bytes / GB); format = Res.Get(StringId.GigabytesFormat); } return string.Format(CultureInfo.CurrentCulture, format, num); } private static string FormatNum(double num) { NumberFormatInfo nf = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); if (num >= 100) nf.NumberDecimalDigits = 0; else if (num >= 10) nf.NumberDecimalDigits = 1; else if (num >= 1) nf.NumberDecimalDigits = 2; else nf.NumberDecimalDigits = 3; return num.ToString("N", nf); } /// <summary> /// Returns the longest common prefix that is shared by the /// two strings. /// </summary> public static string CommonPrefix(string one, string two) { int minLen = Math.Min(one.Length, two.Length); for (int i = 0; i < minLen; i++) if (one[i] != two[i]) return one.Substring(0, i); return one.Length < two.Length ? one : two; } /// <summary> /// Should be faster than string.StartsWith(string) because this /// ignores culture info /// </summary> public static bool StartsWith(string stringValue, string prefix) { if (stringValue.Length < prefix.Length) return false; for (int i = 0; i < prefix.Length; i++) if (stringValue[i] != prefix[i]) return false; return true; } /// <summary> /// Strips any occurrences of A, An, The, and whitespace from the beginning of the string. /// </summary> public static string GetSignificantSubstring(string title) { if (title == null || title == string.Empty) return title; string pattern = @"^\s*((the|a|an)($|\s+))*\s*"; Match match = Regex.Match(title, pattern, RegexOptions.IgnoreCase); if (!match.Success) return title; else return title.Substring(match.Length); } private static string GetIndent(string strVal) { int pos; for (pos = 0; pos < strVal.Length; pos++) { switch (strVal[pos]) { case ' ': case '\t': break; default: return strVal.Substring(0, pos); } } return strVal; // all whitespace } public static string Reverse(string strVal) { char[] chars = strVal.ToCharArray(); Array.Reverse(chars); return new string(chars); } public static string CompressExcessWhitespace(string str) { // RegexOptions.Multiline only works with \n, not \r\n str = LineEndingHelper.Normalize(str, LineEnding.LF); // trim lines made up of only spaces and tabs (but keep the line breaks) //str = Regex.Replace(str, @"[ \t]+(?=\r\n|$)", ""); str = Regex.Replace(str, @"[ \t]+$", "", RegexOptions.Multiline); //str = Regex.Replace(str, @"(?<=^|\n)[ \t]+(?=\r\n|$)", ""); str = str.TrimStart('\n'); str = str.TrimEnd('\n'); str = Regex.Replace(str, @"\n{3,}", "\n\n"); str = LineEndingHelper.Normalize(str, LineEnding.CRLF); return str; } public static bool ToBool(string boolValue, bool defaultValue) { if (boolValue != null) { switch (boolValue.Trim().ToUpperInvariant()) { case "YES": case "TRUE": case "1": return true; case "NO": case "FALSE": case "0": return false; } } return defaultValue; } public static string Replace(string value, int offset, int length, string replacement) { StringBuilder output = new StringBuilder(value.Length + (replacement.Length - length)); if (offset > 0) output.Append(value.Substring(0, offset)); output.Append(replacement); if (offset + length < value.Length) output.Append(value.Substring(offset + length)); return output.ToString(); } /// <summary> /// Gets a hashcode for a string that is stable across multiple versions of .NET /// This implementation was taken from .NET 2.0 /// http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx /// </summary> public static unsafe int GetHashCodeStable(String stringToHash) { fixed (char* str = stringToHash) { char* chPtr = str; int num = 0x15051505; int num2 = num; int* numPtr = (int*)chPtr; for (int i = stringToHash.Length; i > 0; i -= 4) { num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0]; if (i <= 2) { break; } num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ numPtr[1]; numPtr += 2; } return (num + (num2 * 0x5d588b65)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Serialization { using System; using System.Text; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; internal class XmlAttributeComparer : IComparer { public int Compare(object o1, object o2) { XmlAttribute a1 = (XmlAttribute)o1; XmlAttribute a2 = (XmlAttribute)o2; int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal); if (ns == 0) { return string.Compare(a1.Name, a2.Name, StringComparison.Ordinal); } return ns; } } internal class XmlFacetComparer : IComparer { public int Compare(object o1, object o2) { XmlSchemaFacet f1 = (XmlSchemaFacet)o1; XmlSchemaFacet f2 = (XmlSchemaFacet)o2; return string.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal); } } internal class QNameComparer : IComparer { public int Compare(object o1, object o2) { XmlQualifiedName qn1 = (XmlQualifiedName)o1; XmlQualifiedName qn2 = (XmlQualifiedName)o2; int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal); if (ns == 0) { return string.Compare(qn1.Name, qn2.Name, StringComparison.Ordinal); } return ns; } } internal class XmlSchemaObjectComparer : IComparer { private QNameComparer _comparer = new QNameComparer(); public int Compare(object o1, object o2) { return _comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2)); } internal static XmlQualifiedName NameOf(XmlSchemaObject o) { if (o is XmlSchemaAttribute) { return ((XmlSchemaAttribute)o).QualifiedName; } else if (o is XmlSchemaAttributeGroup) { return ((XmlSchemaAttributeGroup)o).QualifiedName; } else if (o is XmlSchemaComplexType) { return ((XmlSchemaComplexType)o).QualifiedName; } else if (o is XmlSchemaSimpleType) { return ((XmlSchemaSimpleType)o).QualifiedName; } else if (o is XmlSchemaElement) { return ((XmlSchemaElement)o).QualifiedName; } else if (o is XmlSchemaGroup) { return ((XmlSchemaGroup)o).QualifiedName; } else if (o is XmlSchemaGroupRef) { return ((XmlSchemaGroupRef)o).RefName; } else if (o is XmlSchemaNotation) { return ((XmlSchemaNotation)o).QualifiedName; } else if (o is XmlSchemaSequence) { XmlSchemaSequence s = (XmlSchemaSequence)o; if (s.Items.Count == 0) return new XmlQualifiedName(".sequence", Namespace(o)); return NameOf(s.Items[0]); } else if (o is XmlSchemaAll) { XmlSchemaAll a = (XmlSchemaAll)o; if (a.Items.Count == 0) return new XmlQualifiedName(".all", Namespace(o)); return NameOf(a.Items); } else if (o is XmlSchemaChoice) { XmlSchemaChoice c = (XmlSchemaChoice)o; if (c.Items.Count == 0) return new XmlQualifiedName(".choice", Namespace(o)); return NameOf(c.Items); } else if (o is XmlSchemaAny) { return new XmlQualifiedName("*", SchemaObjectWriter.ToString(((XmlSchemaAny)o).NamespaceList)); } else if (o is XmlSchemaIdentityConstraint) { return ((XmlSchemaIdentityConstraint)o).QualifiedName; } return new XmlQualifiedName("?", Namespace(o)); } internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) { ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(NameOf(items[i])); } list.Sort(new QNameComparer()); return (XmlQualifiedName)list[0]; } internal static string Namespace(XmlSchemaObject o) { while (o != null && !(o is XmlSchema)) { o = o.Parent; } return o == null ? "" : ((XmlSchema)o).TargetNamespace; } } internal class SchemaObjectWriter { private StringBuilder _w = new StringBuilder(); private int _indentLevel = -1; private void WriteIndent() { for (int i = 0; i < _indentLevel; i++) { _w.Append(" "); } } protected void WriteAttribute(string localName, string ns, string value) { if (value == null || value.Length == 0) return; _w.Append(","); _w.Append(ns); if (ns != null && ns.Length != 0) _w.Append(":"); _w.Append(localName); _w.Append("="); _w.Append(value); } protected void WriteAttribute(string localName, string ns, XmlQualifiedName value) { if (value.IsEmpty) return; WriteAttribute(localName, ns, value.ToString()); } protected void WriteStartElement(string name) { NewLine(); _indentLevel++; _w.Append("["); _w.Append(name); } protected void WriteEndElement() { _w.Append("]"); _indentLevel--; } protected void NewLine() { _w.Append(Environment.NewLine); WriteIndent(); } protected string GetString() { return _w.ToString(); } private void WriteAttribute(XmlAttribute a) { if (a.Value != null) { WriteAttribute(a.Name, a.NamespaceURI, a.Value); } } private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) { if (a == null) return; ArrayList attrs = new ArrayList(); for (int i = 0; i < a.Length; i++) { attrs.Add(a[i]); } attrs.Sort(new XmlAttributeComparer()); for (int i = 0; i < attrs.Count; i++) { XmlAttribute attribute = (XmlAttribute)attrs[i]; WriteAttribute(attribute); } } internal static string ToString(NamespaceList list) { if (list == null) return null; switch (list.Type) { case NamespaceList.ListType.Any: return "##any"; case NamespaceList.ListType.Other: return "##other"; case NamespaceList.ListType.Set: ArrayList ns = new ArrayList(); foreach (string s in list.Enumerate) { ns.Add(s); } ns.Sort(); StringBuilder sb = new StringBuilder(); bool first = true; foreach (string s in ns) { if (first) { first = false; } else { sb.Append(" "); } if (s.Length == 0) { sb.Append("##local"); } else { sb.Append(s); } } return sb.ToString(); default: return list.ToString(); } } internal string WriteXmlSchemaObject(XmlSchemaObject o) { if (o == null) return string.Empty; Write3_XmlSchemaObject((XmlSchemaObject)o); return GetString(); } private void WriteSortedItems(XmlSchemaObjectCollection items) { if (items == null) return; ArrayList list = new ArrayList(); for (int i = 0; i < items.Count; i++) { list.Add(items[i]); } list.Sort(new XmlSchemaObjectComparer()); for (int i = 0; i < list.Count; i++) { Write3_XmlSchemaObject((XmlSchemaObject)list[i]); } } private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) { if ((object)o == null) return; WriteStartElement("attribute"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); WriteAttribute(@"default", @"", ((string)o.@DefaultValue)); WriteAttribute(@"fixed", @"", ((string)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } WriteAttribute(@"name", @"", ((string)o.@Name)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use; WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType); WriteEndElement(); } private void Write3_XmlSchemaObject(XmlSchemaObject o) { if ((object)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaComplexType)) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o); return; } else if (t == typeof(XmlSchemaSimpleType)) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o); return; } else if (t == typeof(XmlSchemaElement)) { Write46_XmlSchemaElement((XmlSchemaElement)o); return; } else if (t == typeof(XmlSchemaAppInfo)) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)o); return; } else if (t == typeof(XmlSchemaDocumentation)) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)o); return; } else if (t == typeof(XmlSchemaAnnotation)) { Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o); return; } else if (t == typeof(XmlSchemaGroup)) { Write57_XmlSchemaGroup((XmlSchemaGroup)o); return; } else if (t == typeof(XmlSchemaXPath)) { Write49_XmlSchemaXPath("xpath", "", (XmlSchemaXPath)o); return; } else if (t == typeof(XmlSchemaIdentityConstraint)) { Write48_XmlSchemaIdentityConstraint((XmlSchemaIdentityConstraint)o); return; } else if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } else if (t == typeof(XmlSchemaGroupRef)) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o); return; } else if (t == typeof(XmlSchemaAny)) { Write53_XmlSchemaAny((XmlSchemaAny)o); return; } else if (t == typeof(XmlSchemaSequence)) { Write54_XmlSchemaSequence((XmlSchemaSequence)o); return; } else if (t == typeof(XmlSchemaChoice)) { Write52_XmlSchemaChoice((XmlSchemaChoice)o); return; } else if (t == typeof(XmlSchemaAll)) { Write43_XmlSchemaAll((XmlSchemaAll)o); return; } else if (t == typeof(XmlSchemaComplexContentRestriction)) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o); return; } else if (t == typeof(XmlSchemaComplexContentExtension)) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o); return; } else if (t == typeof(XmlSchemaSimpleContentRestriction)) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleContentExtension)) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o); return; } else if (t == typeof(XmlSchemaComplexContent)) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o); return; } else if (t == typeof(XmlSchemaSimpleContent)) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o); return; } else if (t == typeof(XmlSchemaAnyAttribute)) { Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o); return; } else if (t == typeof(XmlSchemaAttributeGroupRef)) { Write32_XmlSchemaAttributeGroupRef((XmlSchemaAttributeGroupRef)o); return; } else if (t == typeof(XmlSchemaAttributeGroup)) { Write31_XmlSchemaAttributeGroup((XmlSchemaAttributeGroup)o); return; } else if (t == typeof(XmlSchemaSimpleTypeRestriction)) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o); return; } else if (t == typeof(XmlSchemaSimpleTypeList)) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o); return; } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o); return; } else if (t == typeof(XmlSchemaAttribute)) { Write1_XmlSchemaAttribute((XmlSchemaAttribute)o); return; } } private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o) { if ((object)o == null) return; WriteStartElement("annotation"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAppInfo) { Write7_XmlSchemaAppInfo((XmlSchemaAppInfo)ai); } else if (ai is XmlSchemaDocumentation) { Write6_XmlSchemaDocumentation((XmlSchemaDocumentation)ai); } } } WriteEndElement(); } private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) { if ((object)o == null) return; WriteStartElement("documentation"); WriteAttribute(@"source", @"", ((string)o.@Source)); WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string)o.@Language)); XmlNode[] a = (XmlNode[])o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) { if ((object)o == null) return; WriteStartElement("appinfo"); WriteAttribute("source", "", o.Source); XmlNode[] a = (XmlNode[])o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) { XmlNode ai = (XmlNode)a[ia]; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } } WriteEndElement(); } private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o) { if ((object)o == null) return; WriteStartElement("simpleType"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaSimpleTypeUnion) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeRestriction) { Write15_XmlSchemaSimpleTypeRestriction((XmlSchemaSimpleTypeRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleTypeList) { Write14_XmlSchemaSimpleTypeList((XmlSchemaSimpleTypeList)o.@Content); } WriteEndElement(); } private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) { return v.ToString(); } private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) { if ((object)o == null) return; WriteStartElement("union"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if (o.MemberTypes != null) { ArrayList list = new ArrayList(); for (int i = 0; i < o.MemberTypes.Length; i++) { list.Add(o.MemberTypes[i]); } list.Sort(new QNameComparer()); _w.Append(","); _w.Append("memberTypes="); for (int i = 0; i < list.Count; i++) { XmlQualifiedName q = (XmlQualifiedName)list[i]; _w.Append(q.ToString()); _w.Append(","); } } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@BaseTypes); WriteEndElement(); } private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) { if ((object)o == null) return; WriteStartElement("list"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"itemType", @"", o.@ItemTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType); WriteEndElement(); } private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); WriteFacets(o.Facets); WriteEndElement(); } private void WriteFacets(XmlSchemaObjectCollection facets) { if (facets == null) return; ArrayList a = new ArrayList(); for (int i = 0; i < facets.Count; i++) { a.Add(facets[i]); } a.Sort(new XmlFacetComparer()); for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaMinExclusiveFacet) { Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxInclusiveFacet) { Write_XmlSchemaFacet("maxInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxExclusiveFacet) { Write_XmlSchemaFacet("maxExclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinInclusiveFacet) { Write_XmlSchemaFacet("minInclusive", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaLengthFacet) { Write_XmlSchemaFacet("length", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaEnumerationFacet) { Write_XmlSchemaFacet("enumeration", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMinLengthFacet) { Write_XmlSchemaFacet("minLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaPatternFacet) { Write_XmlSchemaFacet("pattern", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaTotalDigitsFacet) { Write_XmlSchemaFacet("totalDigits", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaMaxLengthFacet) { Write_XmlSchemaFacet("maxLength", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaWhiteSpaceFacet) { Write_XmlSchemaFacet("whiteSpace", (XmlSchemaFacet)ai); } else if (ai is XmlSchemaFractionDigitsFacet) { Write_XmlSchemaFacet("fractionDigit", (XmlSchemaFacet)ai); } } } private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) { if ((object)o == null) return; WriteStartElement(name); WriteAttribute("id", "", o.Id); WriteAttribute("value", "", o.Value); if (o.IsFixed) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private string Write30_XmlSchemaUse(XmlSchemaUse v) { string s = null; switch (v) { case XmlSchemaUse.@Optional: s = @"optional"; break; case XmlSchemaUse.@Prohibited: s = @"prohibited"; break; case XmlSchemaUse.@Required: s = @"required"; break; default: break; } return s; } private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o) { if ((object)o == null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o) { if ((object)o == null) return; WriteStartElement("attributeGroup"); WriteAttribute(@"id", @"", ((string)o.@Id)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o) { if ((object)o == null) return; WriteStartElement("anyAttribute"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { string s = null; switch (v) { case XmlSchemaContentProcessing.@Skip: s = @"skip"; break; case XmlSchemaContentProcessing.@Lax: s = @"lax"; break; case XmlSchemaContentProcessing.@Strict: s = @"strict"; break; default: break; } return s; } private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { if ((object)o == null) return; WriteStartElement("complexType"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); if (((bool)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); if (((bool)o.@IsMixed) != false) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); } else if (o.@ContentModel is XmlSchemaSimpleContent) { Write36_XmlSchemaSimpleContent((XmlSchemaSimpleContent)o.@ContentModel); } if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o) { if ((object)o == null) return; WriteStartElement("simpleContent"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaSimpleContentExtension) { Write38_XmlSchemaSimpleContentExtension((XmlSchemaSimpleContentExtension)o.@Content); } WriteEndElement(); } private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExtension o) { if ((object)o == null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); WriteFacets(o.Facets); WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) { if ((object)o == null) return; WriteStartElement("complexContent"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); } else if (o.@Content is XmlSchemaComplexContentExtension) { Write42_XmlSchemaComplexContentExtension((XmlSchemaComplexContentExtension)o.@Content); } WriteEndElement(); } private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o) { if ((object)o == null) return; WriteStartElement("extension"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write43_XmlSchemaAll(XmlSchemaAll o) { if ((object)o == null) return; WriteStartElement("all"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } private void Write46_XmlSchemaElement(XmlSchemaElement o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("element"); WriteAttribute(@"id", @"", o.Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (((bool)o.@IsAbstract) != false) { WriteAttribute(@"abstract", @"", XmlConvert.ToString((bool)((bool)o.@IsAbstract))); } WriteAttribute(@"block", @"", Write11_XmlSchemaDerivationMethod(o.BlockResolved)); WriteAttribute(@"default", @"", o.DefaultValue); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); WriteAttribute(@"fixed", @"", o.FixedValue); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) { WriteAttribute(@"form", @"", "qualified"); } else { WriteAttribute(@"form", @"", "unqualified"); } } if (o.Name != null && o.Name.Length != 0) { WriteAttribute(@"name", @"", o.Name); } if (o.IsNillable) { WriteAttribute(@"nillable", @"", XmlConvert.ToString(o.IsNillable)); } if (!o.SubstitutionGroup.IsEmpty) { WriteAttribute("substitutionGroup", "", o.SubstitutionGroup); } if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } else if (!o.SchemaTypeName.IsEmpty) { WriteAttribute("type", "", o.SchemaTypeName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { Write35_XmlSchemaComplexType((XmlSchemaComplexType)o.SchemaType); } else if (o.SchemaType is XmlSchemaSimpleType) { Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.SchemaType); } WriteSortedItems(o.Constraints); WriteEndElement(); } private void Write47_XmlSchemaKey(XmlSchemaKey o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("key"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) { if ((object)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaUnique)) { Write51_XmlSchemaUnique((XmlSchemaUnique)o); return; } else if (t == typeof(XmlSchemaKeyref)) { Write50_XmlSchemaKeyref((XmlSchemaKeyref)o); return; } else if (t == typeof(XmlSchemaKey)) { Write47_XmlSchemaKey((XmlSchemaKey)o); return; } } private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o) { if ((object)o == null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("keyref"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); // UNDONE compare reference here WriteAttribute(@"refer", @"", o.@Refer); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath(@"field", @"", (XmlSchemaXPath)a[ia]); } } } WriteEndElement(); } private void Write51_XmlSchemaUnique(XmlSchemaUnique o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("unique"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { Write49_XmlSchemaXPath("field", "", (XmlSchemaXPath)a[ia]); } } WriteEndElement(); } private void Write52_XmlSchemaChoice(XmlSchemaChoice o) { if ((object)o == null) return; System.Type t = o.GetType(); WriteStartElement("choice"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } private void Write53_XmlSchemaAny(XmlSchemaAny o) { if ((object)o == null) return; WriteStartElement("any"); WriteAttribute(@"id", @"", o.@Id); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private void Write54_XmlSchemaSequence(XmlSchemaSequence o) { if ((object)o == null) return; WriteStartElement("sequence"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) { for (int ia = 0; ia < a.Count; ia++) { XmlSchemaObject ai = (XmlSchemaObject)a[ia]; if (ai is XmlSchemaAny) { Write53_XmlSchemaAny((XmlSchemaAny)ai); } else if (ai is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)ai); } else if (ai is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)ai); } else if (ai is XmlSchemaElement) { Write46_XmlSchemaElement((XmlSchemaElement)ai); } else if (ai is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)ai); } } } WriteEndElement(); } private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) { if ((object)o == null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); WriteEndElement(); } private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o) { if ((object)o == null) return; WriteStartElement("restriction"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); if ([email protected]) { WriteAttribute(@"base", @"", o.@BaseTypeName); } Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaGroupRef) { Write55_XmlSchemaGroupRef((XmlSchemaGroupRef)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); WriteEndElement(); } private void Write57_XmlSchemaGroup(XmlSchemaGroup o) { if ((object)o == null) return; WriteStartElement("group"); WriteAttribute(@"id", @"", ((string)o.@Id)); WriteAttribute(@"name", @"", ((string)o.@Name)); WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); } else if (o.@Particle is XmlSchemaChoice) { Write52_XmlSchemaChoice((XmlSchemaChoice)o.@Particle); } else if (o.@Particle is XmlSchemaAll) { Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteEndElement(); } } }
using System; using System.Collections.Generic; /// <summary> /// String.GetEnumerator() /// Retrieves an object that can iterate through the individual characters in this string. /// </summary> class StringGetEnumerator { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { StringGetEnumerator iege = new StringGetEnumerator(); TestLibrary.TestFramework.BeginTestCase("for method: String.GetEnumerator()"); if (iege.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random string"; const string c_TEST_ID = "P001"; string strSrc; IEnumerator<Char> iterator; bool condition = false; bool expectedValue = true; bool actualValue = false; strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { iterator = ((IEnumerable<Char>)strSrc).GetEnumerator(); condition = true; int index = 0; while (iterator.MoveNext()) { condition = object.Equals(iterator.Current, strSrc[index]) && condition; index++; } iterator.Reset(); actualValue = condition && (null != iterator); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: string.Empty "; const string c_TEST_ID = "P002"; string strSrc; IEnumerator<Char> iterator; bool condition = false; bool expectedValue = true; bool actualValue = false; strSrc = string.Empty; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { iterator = ((IEnumerable<Char>)strSrc).GetEnumerator(); condition = true; int index = 0; while (iterator.MoveNext()) { condition = object.Equals(iterator.Current, strSrc[index]) && condition; index++; } iterator.Reset(); actualValue = condition && (null != iterator); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = @"PosTest3: string is \0 "; const string c_TEST_ID = "P003"; string strSrc; IEnumerator<Char> iterator; bool condition = false; bool expectedValue = true; bool actualValue = false; strSrc = "\0"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { iterator = ((IEnumerable<Char>)strSrc).GetEnumerator(); condition = true; int index = 0; while (iterator.MoveNext()) { condition = object.Equals(iterator.Current, strSrc[index]) && condition; index++; } iterator.Reset(); actualValue = condition && (null != iterator); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes private string GetDataString(string strSrc) { string str1, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); return str; } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Byte : IComparable, IConvertible, IFormattable, IComparable<byte>, IEquatable<byte>, ISpanFormattable { private readonly byte m_value; // Do not rename (binary serialization) // The maximum value that a Byte may represent: 255. public const byte MaxValue = (byte)0xFF; // The minimum value that a Byte may represent: 0. public const byte MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type byte, this method throws an ArgumentException. // public int CompareTo(object value) { if (value == null) { return 1; } if (!(value is byte)) { throw new ArgumentException(SR.Arg_MustBeByte); } return m_value - (((byte)value).m_value); } public int CompareTo(byte value) { return m_value - value; } // Determines whether two Byte objects are equal. public override bool Equals(object obj) { if (!(obj is byte)) { return false; } return m_value == ((byte)obj).m_value; } [NonVersionable] public bool Equals(byte obj) { return m_value == obj; } // Gets a hash code for this instance. public override int GetHashCode() { return m_value; } public static byte Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static byte Parse(string s, IFormatProvider provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } // Parses an unsigned byte from a String in the given style. If // a NumberFormatInfo isn't specified, the current culture's // NumberFormatInfo is assumed. public static byte Parse(string s, NumberStyles style, IFormatProvider provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static byte Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static byte Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { int i = 0; try { i = Number.ParseInt32(s, style, info); } catch (OverflowException e) { throw new OverflowException(SR.Overflow_Byte, e); } if (i < MinValue || i > MaxValue) throw new OverflowException(SR.Overflow_Byte); return (byte)i; } public static bool TryParse(string s, out byte result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out byte result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out byte result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out byte result) { result = 0; int i; if (!Number.TryParseInt32(s, style, info, out i)) { return false; } if (i < MinValue || i > MaxValue) { return false; } result = (byte)i; return true; } public override string ToString() { return Number.FormatUInt32(m_value, null, null); } public string ToString(string format) { return Number.FormatUInt32(m_value, format, null); } public string ToString(IFormatProvider provider) { return Number.FormatUInt32(m_value, null, provider); } public string ToString(string format, IFormatProvider provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Byte; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider provider) { return m_value; } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Byte", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Xml; using Xstream.Core.Converters; using Xstream.Core.Converters.Complex; namespace Xstream.Core { /// <summary> /// A MarshalContext provides methods and a context enviroment /// to convert objects to XML, or convert XML back into the original /// (or different) objects. /// </summary> public class MarshalContext : IMarshalContext { private static readonly Assembly __mscorlib = typeof (int).Assembly; private static readonly Type __objectType = typeof (object); private static readonly Type __typeType = typeof (Type); private static readonly Type __arrayType = typeof (Array); private static readonly Type __genericListType = typeof(List<>); private static readonly Type __enumType = typeof (Enum); private static readonly Type __nullType = typeof (NullType); private static readonly Type __methodInfoType = typeof (MethodInfo); private readonly Hashtable converterMap = new Hashtable(20); private readonly Hashtable aliasMap = new Hashtable(); private readonly Hashtable reverseAliasMap = new Hashtable(); private readonly Hashtable cdataMap = new Hashtable(); private readonly ArrayList stackList = new ArrayList(); private readonly Hashtable stackMap; private bool useRepository; private Type ignoredAttributeType; private bool caseSensitive; /// <summary> /// Registers a set of default converters for almost all types. /// </summary> public MarshalContext() : this(new ReferenceComparer()) {} public MarshalContext(IEqualityComparer equalityComparer) { stackMap = new Hashtable(equalityComparer); useRepository = false; caseSensitive = true; AddConverters(); } private void AddConverters() { AddConverter(new NullConverter()); AddConverter(new IntConverter()); AddConverter(new LongConverter()); AddConverter(new ShortConverter()); AddConverter(new FloatConverter()); AddConverter(new DoubleConverter()); AddConverter(new StringConverter()); AddConverter(new BooleanConverter()); AddConverter(new CharConverter()); AddConverter(new ObjectConverter()); AddConverter(new ArrayConverter()); AddConverter(new PointerConverter()); AddConverter(new ByteConverter()); AddConverter(new DateTimeConverter()); AddConverter(new TimeSpanConverter()); AddConverter(new DecimalConverter()); AddConverter(new GuidConverter()); AddConverter(new EnumConverter()); AddConverter(new TypeConverter()); AddConverter(new MethodInfoConverter()); AddConverter(new StringBuilderConverter()); AddConverter(new CDataConverter()); AddConverter(new GenericListConverter()); } public bool UseRepository { get { return useRepository; } set { useRepository = value; } } public bool CaseSensitive { get { return caseSensitive; } set { caseSensitive = value; } } public virtual void AddConverter(IConverter converter) { converter.Register(this); } public virtual bool IsCData(Type type, string fieldName) { if (cdataMap.Contains(type) && ((ArrayList)cdataMap[type]).Contains(fieldName)) return true; return false; } public virtual IConverter GetCDataConverter() { return (IConverter) converterMap[typeof (CDataConverter)]; } public void AddCdata(Type type, string name) { if(!cdataMap.Contains(type)) { ArrayList fields = new ArrayList(); fields.Add(name); cdataMap.Add(type, fields); } else { ArrayList fields = (ArrayList)cdataMap[type]; if (!fields.Contains(name)) fields.Add(name); } } /// <summary> /// Registers a new converter for a specific type. /// </summary> /// <param name="type">Type the converter can handle.</param> /// <param name="converter">Converter instance to use when converting.</param> public virtual void RegisterConverter(Type type, IConverter converter) { if (type == null) type = __nullType; converterMap[type] = converter; } /// <summary> /// Adds a simple string alias for a specific Type. /// </summary> /// <param name="alias">String alias name.</param> /// <param name="type">Type to use the alias for.</param> public void Alias(string alias, Type type) { // Perform a regular expression check on the alias name: // only _ and alphanumerical characters are allowed if (type == null) type = __nullType; // Add alias to forward and reverse map aliasMap[alias] = type; reverseAliasMap[type] = alias; } /// <summary> /// Returns the name of the type in the shortest safe way that /// it can be used to retrieve the Type instance. /// </summary> public string GetTypeName(Type type) { if (type.Assembly == __mscorlib) return type.FullName; return type.AssemblyQualifiedName; } /// <summary> /// Writes the opening (start) tag of an element representing /// the XML serialized version of an object. /// </summary> /// <param name="type">Type of the object.</param> /// <param name="field">Field of the parent the object represents.</param> /// <param name="xml">XML output to write on.</param> public void WriteStartTag(Type type, FieldInfo field, XmlTextWriter xml) { string tagName, assemblyName = null, typeName = null; if (field != null) { // If the field is set, the tag name is the field name tagName = auto_property_name(field.Name); // If the object type is different from the field type, add the type information if (type != field.FieldType && field.FieldType.GetGenericTypeDefinition() != typeof(List<>)) { // Get the aliased version of the type information typeName = reverseAliasMap[type] as string; if (typeName == null) typeName = GetTypeName(type); } } else { // No field set, the tag name is the full type name tagName = reverseAliasMap[type] as string; // If no alias is found, check the assembly if (tagName == null) { tagName = type.ToString(); // If the assembly is not the default assembly, write out the attribute if (type.Assembly != __mscorlib) assemblyName = type.Assembly.FullName; } } // Replace all + characters with - in the tag name xml.WriteStartElement(tagName.Replace('+', '-').Replace("[]", "--")); if (typeName != null) xml.WriteAttributeString("type", typeName); if (assemblyName != null) xml.WriteAttributeString("assembly", assemblyName); } public static string auto_property_name(string tagName) { if (tagName.Contains("k__BackingField")) tagName = tagName.Replace("<", "").Replace(">k__BackingField", ""); return tagName; } /// <summary> /// Writes the closing (end) tag of an element representing the /// XML serialized version of an object. /// </summary> /// <param name="type">Type of the object.</param> /// <param name="field">Field of the parent the object represents.</param> /// <param name="xml">XML output to write on.</param> public void WriteEndTag(Type type, FieldInfo field, XmlTextWriter xml) { xml.WriteEndElement(); } public Type GetTypeFromTag(XmlNode node, bool isField) { // Replace all - characters with + in the tag name string tagName = node.Name.Replace("--", "[]").Replace('-', '+'); string typeName = node.Attributes["type"] != null ? node.Attributes["type"].Value : null; string assemblyName = node.Attributes["assembly"] != null ? node.Attributes["assembly"].Value : null; ; Type type = null; // If a typeName is specified, use this type if (typeName != null) { type = aliasMap[typeName] as Type; if (type == null) type = Type.GetType(typeName); } if (!isField) { // Check if the tag is an alias type = aliasMap[tagName] as Type; if (type == null) { string fqn = tagName + (assemblyName != null ? "," + assemblyName : ""); type = Type.GetType(fqn); } } return type; } /// <summary> /// Gets an IConverter that can convert the given type. /// </summary> public IConverter GetConverter(Type type) { if (type == null) type = __nullType; // Try a primitive match IConverter converter = converterMap[type] as IConverter; // Try an exact class match if (converter == null) { if (type.IsArray) return converterMap[__arrayType] as IConverter; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) return converterMap[__genericListType] as IConverter; if (type.IsEnum) return converterMap[__enumType] as IConverter; if (type.IsSubclassOf(__typeType)) return converterMap[__typeType] as IConverter; if (type.IsSubclassOf(__methodInfoType)) return converterMap[__methodInfoType] as IConverter; if (type.Name.StartsWith("Predicate`1")) return NoopConverter.Instance; converter = ObjectConverter; } if (converter == null) throw new ConversionException("No valid converter found for type " + type); return converter; } public virtual ObjectConverter ObjectConverter { get { return (ObjectConverter) converterMap[__objectType]; } } /// <summary> /// Gets an IConverter that can convert the object represented /// by the XML node back to an instance. The exact type of the /// object represented by the node, if possible to determine, /// is passed in and out as a reference parameter. /// </summary> /// <remarks> /// Only if the node represents on object linked to a field of a /// parent object, is the reference type allowed to be set, in /// all other cases the value should be null. /// </remarks> /// <param name="node">XmlNode representing the object.</param> /// <param name="type"> /// Proposed type of the object, this would be the type of the /// field the object represents. /// </param> public IConverter GetConverter(XmlNode node, ref Type type) { Type nodeType = GetTypeFromTag(node, type != null); if (nodeType != null) type = nodeType; if (type != null) return GetConverter(type); else throw new ConversionException("Could not find the Type of element: " + node.Name); } /// <summary> /// Adds an object to the context stack, allowing serializing /// of nested objects with back references. /// </summary> public void Stack(object oo) { if (stackMap.Contains(oo)) return; int add = stackList.Add(oo); stackMap.Add(oo, add); } public void Stack(object value, Type type, XmlNode xml) { int add = stackList.Add(value); stackMap.Add(value, add); } public void Stack(object value, Type type) { if (stackMap.Contains(value)) return; int add = stackList.Add(value); stackMap.Add(value, add); } /// <summary> /// Gets the index of the object reference in the stack. /// A negative number (-1) is returned if the object is not /// yet contained in the context stack. /// </summary> public int GetStackIndex(object oo) { if (!stackMap.Contains(oo)) return -1; return (int) stackMap[oo]; } /// <summary> /// Returns the object at the given position in the stack. /// Null is returned if no object is found. /// </summary> public object GetStackObject(int position) { if (position >= stackList.Count) return null; return stackList[position]; } /// <summary> /// Clears the stack of objects encountered. /// </summary> public void ClearStack() { stackMap.Clear(); stackList.Clear(); } public void AddIgnoreAttribute(Type type) { ignoredAttributeType = type; } public Type IgnoredAttributeType { get { return ignoredAttributeType; } } public IConverter RemoveConverter(Type type) { object converter = converterMap[type]; converterMap[type] = null; return (IConverter) converter; } public virtual bool ContainsType(object o) { foreach (DictionaryEntry entry in stackMap) if (EntryKeyIs(entry, o)) return true; return false; } private static bool EntryKeyIs(DictionaryEntry entry, object o) { return entry.Key.GetType().Equals(o.GetType()); } public virtual object GetOfType(object matchingObj) { foreach (DictionaryEntry entry in stackMap) if (EntryKeyIs(entry, matchingObj)) return entry.Key; return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace paperTestsCode { class Groups { /// <summary> /// An enumeration type for comparing values /// </summary> public enum Comprison { SrictlyLess, LessOrEqual, StrictlyGreater, GreaterOrEqual }; /// <summary> /// Applying the meta analytic framework /// </summary> public Tuple<List<List<List<T>>>,int> metaAnalyticProcedure<T>(Func<T, T, double> function, Comprison comp, List<T> lst, double tolerance, int num_results) { // Whether or not we subtract 1 here depends on the optimisation function used. In our case, // it is justified since we are using the Pearson correlation coefficient and want to prefer those // cases where the correlations are closest to 1. Func<T, T, double> absRelation = (x, y) => Math.Abs(function(x, y) - 1); // Again whether the sum, average, etc. is used here is dependss on the comparison function Func<List<T>, double> adjacentRelations_aux = ls => (zipp(ls).Select(x => Math.Exp(absRelation(x.Item1, x.Item2)))).Sum(); //.Average() ; Func<List<T>, double> adjacentRelations = ls => (ls == null || ls.Count < 2) ? 2 : adjacentRelations_aux(ls); Func<List<List<T>>, double> meanAdjacentRelation = ls => (ls.Select(x => adjacentRelations(x))).Average(); // ----------------------------------- The method ------------------------------------------------------- // 1. Get the initial founder sets using the relation function and the stated tolerance List<List<T>> founderSets = getFounderSets(lst, function, tolerance); // 2. consider ways of recombining the founder sets to form larger groups var recombinedFounders_aux = allGroups(founderSets, true); List<List<List<T>>> recombinedFounders = recombinedFounders_aux.Select(x => x.Select(y => listConcatenate(y)).ToList()).ToList(); int original_recombinations = recombinedFounders.Count; // 3. if the the number of recombined founder sets is reasonable ("Reasonable" is determined by the 'num_results' parameter) if (recombinedFounders.Count <= num_results) { // 3a. Return all the recombined founder sets return Tuple.Create(recombinedFounders,original_recombinations); } else { // 3b. Otherwise we retain only those original founder sets that score increasingly higher/lower // subject to the meanAdjacentRelation function defined above var result = maintainBy(meanAdjacentRelation, comp, recombinedFounders, null); // .. and return at most the specified 'reasonable' number of then. return Tuple.Create(take(num_results,result),original_recombinations); } } // Form 2-tuples of adjacent elements of a list private List<Tuple<T, T>> zipp<T>(List<T> ls) { if (ls != null && ls.Count > 1) { var temp = new List<Tuple<T, T>>(); for (int i = 0; i < ls.Count - 1; i++) temp.Add(Tuple.Create(ls.ElementAt(i), ls.ElementAt(i + 1))); return temp; } else return null; } /// <summary> /// Retaining elements in a list that satisfy a given condition such that only those elements of incraesing / decreasing /// subject to some real function on its elements, remains in the list /// </summary> private List<T> maintainBy<T>(Func<T, double> fn, Comprison comp, List<T> ls, List<T> acc) { if (ls != null && ls.Count > 1) { var y = ls.ElementAt(0); var lss = drop(1, ls); return maintainBy_aux(fn, y, lss, comp, null); } else return ls; } // private List<T> maintainBy_aux<T>(Func<T, double> fn, T a1, List<T> ls, Comprison comp, List<T> acc) { if (ls != null && ls.Count > 0) { acc = (acc == null) ? new List<T>() : acc; var y = ls.ElementAt(0); ls.RemoveAt(0); // comparing the elements depending on the comparison operator Func<double, double, bool> compare = (a, b) => comp == Comprison.SrictlyLess ? a < b : (comp == Comprison.LessOrEqual ? a <= b : (comp == Comprison.StrictlyGreater ? a > b : a >= b)); if (compare(fn(a1), fn(y))) { prepend_to_list(a1, acc); return maintainBy_aux(fn, a1, ls, comp, acc); } else { prepend_to_list(y, acc); return maintainBy_aux(fn, y, ls, comp, acc); } } else return acc; } // prepends an element to a list if a comparable element is not already at the front of said list private static void prepend_to_list<T>(T a, List<T> ls) { if (ls == null || ls.Count < 1) ls.Add(a); else { var x = ls.ElementAt(0); if (!EqualityComparer<T>.Default.Equals(x, a)) ls.Insert(0, a); } } // taking the first n elements of a list. I prefer this syntax private static List<T> take<T>(int n, List<T> list) { return list.Take(n).ToList(); } // The analogue of take - dropping the first n elements of a list private static List<T> drop<T>(int n, List<T> list) { var split = splitAt(n, list); if (split == null) return null; else return split.Item2; } /// <summary> /// Split a list at a given index, returning a tuple with each portion of the list, or null if the /// list is null or the index is invalid. /// </summary> private static Tuple<List<T>, List<T>> splitAt<T>(int n, List<T> ls) { if (ls == null || n <= 0 || n > ls.Count) return null; else { List<T> front = new List<T>(); List<T> back = new List<T>(); for (int i = 0; i < ls.Count; i++) { if (i < n) front.Add(ls.ElementAt(i)); else back.Add(ls.ElementAt(i)); } return Tuple.Create(front, back); } } /// <summary> /// All adjacent concatenations,with the option to concatenate at least two elements to form a group /// </summary> private List<List<List<T>>> allGroups<T>(List<T> ls, bool one_element_in_a_group) { if (ls != null && ls.Count > 0) { int len = ls.Count; int max = 0; int cuts = one_element_in_a_group ? len - 1 : Math.DivRem(len, 2, out max); int min_group = one_element_in_a_group ? 1 : 2; var temp = new List<List<List<T>>>(); // get all the pieces; for (int i = 0; i < cuts; i++) { var iPieces = (nGroups(i, min_group, ls)); foreach (List<List<T>> tp in iPieces) temp.Add(tp); } return temp; } else return null; } /// <summary> /// Calculates all possible adjacent elements from n cuts of the list built from /// at least min_lim elements, keeping track of the occurrence of cuts /// </summary> private List<List<List<T>>> nGroups<T>(int m, int min_lim, List<T> inList) { if (inList == null || min_lim < 1 || m >= inList.Count) return null; else if (m <= 0) { // return the original list var temp = new List<List<T>>(); temp.Add(inList); var temp2 = new List<List<List<T>>>(); temp2.Add(temp); return temp2; } else { int end = inList.Count - min_lim + 1; List<List<List<T>>> temp = new List<List<List<T>>>(); for (int i = min_lim; i < end; i++) { // the elements of the list up to i var split = splitAt(i, inList); List<T> ns = split.Item1; List<T> ms = split.Item2; var sub_groups = nGroups(m - 1, min_lim, ms); sub_groups = sub_groups == null ? new List<List<List<T>>>() : sub_groups; foreach (List<List<T>> ps in sub_groups) { var grp = (ps == null) ? new List<List<T>>() : ps; grp.Insert(0, ns); temp.Add(grp); } } return temp; } } // the find groups function private List<List<T>> getFounderSets<T>(List<T> list, Func<T, T, double> fun, double tol) { return findGrps_aux<T>(list, fun, tol, null); } static List<List<T>> findGrps_aux<T>(List<T> list, Func<T, T, double> fun, double tol, List<List<T>> accm) { if (list == null) return accm; else if (list.Count == 1) { accm.Add(list); return accm; } else { var elm = list.ElementAt(0); var effective_set = findGrps_aux1(1, list, elm, fun, tol, null); int mx = effective_set == null ? 1 : effective_set.Max(x => x.Item2); var split = splitAt(mx, list); accm = accm == null ? new List<List<T>>() : accm; accm.Add(split.Item1); return findGrps_aux(split.Item2, fun, tol, accm); } } /// find groups private static List<Tuple<List<T>, int>> findGrps_aux1<T>(int n, List<T> list, T elm, Func<T, T, double> fun, double tol, List<Tuple<List<T>, int>> dummy) { if (n >= 0 && list != null) { if (n > list.Count - 1) return dummy; else { var front = take(n, list); bool valid = front.All(x => fun(elm, x) >= tol); if (valid == false) { return dummy; } else { dummy = (dummy == null) ? new List<Tuple<List<T>, int>>() : dummy; dummy.Insert(0, Tuple.Create(front, front.Count)); return findGrps_aux1(n + 1, list, elm, fun, tol, dummy); } } } else return null; } // concatenate a list of lists public List<T> listConcatenate<T>(List<List<T>> ls) { if (ls != null && ls.Count > 0) { List<T> temp = new List<T>(); for (int i = 0; i < ls.Count; i++) foreach (T elm in ls.ElementAt(i)) temp.Add(elm); return temp; } else return null; } } }
#if MONO using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using NUnit.Framework; using Palaso.Reporting; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.UI.WindowsForms.Keyboarding.Linux; using Palaso.WritingSystems; namespace PalasoUIWindowsForms.Tests.Keyboarding { [TestFixture] [Category("SkipOnTeamCity")] public class LinuxKeyboardControllerTests { private Form _window; [TestFixtureSetUp] public void FixtureSetup() { KeyboardController.Initialize(); } [TestFixtureTearDown] public void FixtureTearDown() { KeyboardController.Shutdown(); } [SetUp] public void Setup() { ErrorReport.IsOkToInteractWithUser = false; } [TearDown] public void Teardown() { if (_window != null) { _window.Close(); Application.DoEvents(); _window.Dispose(); _window = null; } } private void RequiresWindowForFocus() { _window = new Form(); var box = new TextBox(); box.Dock = DockStyle.Fill; _window.Controls.Add(box); _window.Show(); box.Select(); Application.DoEvents(); } [Test] public void GetAllKeyboards_GivesSeveral() { var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.Greater(keyboards.Count(), 1, "This test requires that the Windows IME has at least two languages installed."); } [Test] public void ActivateKeyboard_BogusName_RaisesMessageBox() { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => Keyboard.Controller.SetKeyboard("foobar") ); } [Test] public void ActivateKeyboard_BogusName_SecondTimeNoLongerRaisesMessageBox() { // the keyboardName for this test and above need to be different const string keyboardName = "This should never be the same as the name of an installed keyboard"; try { Keyboard.Controller.SetKeyboard(keyboardName); Assert.Fail("Should have thrown exception but didn't."); } catch (ErrorReport.ProblemNotificationSentToUserException) { } Keyboard.Controller.SetKeyboard(keyboardName); } #if WANT_PORT /// <summary> /// The main thing here is that it doesn't crash doing a LoadLibrary() /// </summary> [Test] public void NoKeyman7_GetKeyboards_DoesNotCrash() { KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Keyman7); } [Test] [Ignore("SCIM deprecated")] public void EngineAvailable_ScimIsSetUpAndConfiguredCorrectly_ReturnsTrue() { Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.Scim)); } [Test] [Ignore("SCIM deprecated")] public void GetActiveKeyboard_ScimIsSetUpAndConfiguredToDefault_ReturnsEnglishKeyboard() { RequiresWindowForFocus(); ResetKeyboardToDefault(); Assert.AreEqual("English/Keyboard", KeyboardController.GetActiveKeyboard()); } [Test] [Ignore("SCIM deprecated")] public void KeyboardDescriptors_ScimIsSetUpAndConfiguredToDefault_3KeyboardsReturned() { List<KeyboardController.KeyboardDescriptor> availableKeyboards = KeyboardController.GetAvailableKeyboards(KeyboardController.Engines.Scim); Assert.AreEqual("English/European", availableKeyboards[0].ShortName); Assert.AreEqual("RAW CODE", availableKeyboards[1].ShortName); Assert.AreEqual("English/Keyboard", availableKeyboards[2].ShortName); } [Test] [Ignore("SCIM deprecated")] public void Deactivate_ScimIsRunning_GetCurrentKeyboardReturnsEnglishKeyboard() { RequiresWindowForFocus(); Keyboard.Controller.SetKeyboard("English/European"); KeyboardController.DeactivateKeyboard(); Assert.AreEqual("English/Keyboard", KeyboardController.GetActiveKeyboard()); } [Test] [Ignore("SCIM deprecated")] public void ActivateKeyBoard_ScimHasKeyboard_GetCurrentKeyboardReturnsActivatedKeyboard() { RequiresWindowForFocus(); ResetKeyboardToDefault(); Keyboard.Controller.SetKeyboard("English/European"); Assert.AreEqual("English/European", KeyboardController.GetActiveKeyboard()); ResetKeyboardToDefault(); } [Test] [Ignore("SCIM deprecated")] public void ActivateKeyBoard_ScimDoesNotHaveKeyboard_Throws() { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => Keyboard.Controller.SetKeyboard("Nonexistent Keyboard") ); } [Test] [Ignore("SCIM deprecated")] [Category("No IM Running")] public void GetAvailableKeyboards_NoIMRunning_ReturnsEmptyList() { var availableKeyboards = Keyboard.Controller.AllAvailableKeyboards.Where(kbd => kbd is KeyboardDescription && ((KeyboardDescription)kbd).Engine == "SCIM"); Assert.AreEqual(0, availableKeyboards.Count()); } #endif private static void ResetKeyboardToDefault() { Keyboard.Controller.ActivateDefaultKeyboard(); } [Test] [Category("No IM Running")] public void Deactivate_NoIMRunning_DoesNotThrow() { Keyboard.Controller.ActivateDefaultKeyboard(); } #if WANT_PORT [Test] [Category("IBus not Running")] public void EngineAvailable_IBusIsnotRunning_returnsFalse() { Assert.IsFalse(KeyboardController.EngineAvailable(KeyboardController.Engines.IBus)); } [Test] [Category("IBus")] public void EngineAvailable_IBusIsSetUpAndConfiguredCorrectly_ReturnsTrue() { // needed for focus RequiresWindowForFocus(); Assert.IsTrue(KeyboardController.EngineAvailable(KeyboardController.Engines.IBus)); } #endif [Test] [Category("IBus")] public void Deactivate_IBusIsRunning_GetCurrentKeyboardReturnsEnglishKeyboard() { if (Keyboard.Controller.AllAvailableKeyboards.Count(kbd => kbd.Layout == "m17n:am:sera") <= 0) Assert.Ignore("Can't run this test without ibus keyboard 'm17n:am:sera' being installed."); // needed for focus RequiresWindowForFocus(); Keyboard.Controller.SetKeyboard("m17n:am:sera"); Keyboard.Controller.ActivateDefaultKeyboard(); Assert.AreEqual("m17n:am:sera", Keyboard.Controller.ActiveKeyboard); } [Test] [Category("IBus")] public void ActivateKeyBoard_IBusHasKeyboard_GetCurrentKeyboardReturnsActivatedKeyboard() { if (Keyboard.Controller.AllAvailableKeyboards.Count(kbd => kbd.Layout == "m17n:am:sera") <= 0) Assert.Ignore("Can't run this test without ibus keyboard 'm17n:am:sera' being installed."); // needed for focus RequiresWindowForFocus(); Keyboard.Controller.ActivateDefaultKeyboard(); Keyboard.Controller.SetKeyboard("m17n:am:sera"); Assert.AreEqual("m17n:am:sera", Keyboard.Controller.ActiveKeyboard); Keyboard.Controller.ActivateDefaultKeyboard(); } [Test] [Category("IBus")] public void ActivateKeyBoard_IBusDoesNotHaveKeyboard_Throws() { // needed for focus RequiresWindowForFocus(); Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => Keyboard.Controller.SetKeyboard("Nonexistent Keyboard") ); } [Test] public void CreateKeyboardDefinition_NewKeyboard_ReturnsNewObject() { // REVIEW: adjust this test var keyboard = Keyboard.Controller.CreateKeyboardDefinition("foo", "en-US"); Assert.That(keyboard, Is.Not.Null); Assert.That(keyboard, Is.TypeOf<XkbKeyboardDescription>()); } } } #endif
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.StorSimple; using Microsoft.WindowsAzure.Management.StorSimple.Models; namespace Microsoft.WindowsAzure.Management.StorSimple { /// <summary> /// All Operations related to Device Jobs /// </summary> internal partial class DeviceJobOperations : IServiceOperations<StorSimpleManagementClient>, IDeviceJobOperations { /// <summary> /// Initializes a new instance of the DeviceJobOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DeviceJobOperations(StorSimpleManagementClient client) { this._client = client; } private StorSimpleManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.StorSimple.StorSimpleManagementClient. /// </summary> public StorSimpleManagementClient Client { get { return this._client; } } /// <summary> /// Begin async task to update a device job. /// </summary> /// <param name='deviceId'> /// Required. id of device /// </param> /// <param name='jobId'> /// Required. id of job to update /// </param> /// <param name='updateRequest'> /// Required. Request data, contains the action to be taken /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// This is the Task Response for all Async Calls /// </returns> public async Task<GuidTaskResponse> BeginUpdateDeviceJobAsync(string deviceId, string jobId, UpdateDeviceJobRequest updateRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (deviceId == null) { throw new ArgumentNullException("deviceId"); } if (jobId == null) { throw new ArgumentNullException("jobId"); } if (updateRequest == null) { throw new ArgumentNullException("updateRequest"); } if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("jobId", jobId); tracingParameters.Add("updateRequest", updateRequest); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "BeginUpdateDeviceJobAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devices/"; url = url + Uri.EscapeDataString(deviceId); url = url + "/devicejobs/"; url = url + Uri.EscapeDataString(jobId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.1.0"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement updateDeviceJobRequestElement = new XElement(XName.Get("UpdateDeviceJobRequest", "http://windowscloudbackup.com/CiS/V2013_03")); requestDoc.Add(updateDeviceJobRequestElement); XElement actionElement = new XElement(XName.Get("Action", "http://windowscloudbackup.com/CiS/V2013_03")); actionElement.Value = updateRequest.DeviceJobAction.ToString(); updateDeviceJobRequestElement.Add(actionElement); requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // 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.Accepted) { 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 GuidTaskResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GuidTaskResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement guidElement = responseDoc.Element(XName.Get("guid", "http://schemas.microsoft.com/2003/10/Serialization/")); if (guidElement != null) { string guidInstance = guidElement.Value; result.TaskId = guidInstance; } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='deviceId'> /// Optional. Device id of device of jobs /// </param> /// <param name='jobType'> /// Optional. Type of deviceJob /// </param> /// <param name='jobStatus'> /// Optional. Status of job /// </param> /// <param name='jobId'> /// Optional. Id of job /// </param> /// <param name='startTime'> /// Optional. Job start time, in ISO 8601 format /// 'yyyy'-'MM'-'dd'T'HH':'mm':'ss' /// </param> /// <param name='endTime'> /// Optional. Job end time, in ISO 8601 format /// 'yyyy'-'MM'-'dd'T'HH':'mm':'ss' /// </param> /// <param name='skip'> /// Required. Pagination parameter. The number of entries to skip, i.e. /// index of the first entry to be returned /// </param> /// <param name='top'> /// Required. Pagination parameter. The number of entries to return /// after skipping the 'skip' number of entries /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response model of Get Query for a Device Job /// </returns> public async Task<GetDeviceJobResponse> GetAsync(string deviceId, string jobType, string jobStatus, string jobId, string startTime, string endTime, int skip, int top, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (customRequestHeaders == null) { throw new ArgumentNullException("customRequestHeaders"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("jobType", jobType); tracingParameters.Add("jobStatus", jobStatus); tracingParameters.Add("jobId", jobId); tracingParameters.Add("startTime", startTime); tracingParameters.Add("endTime", endTime); tracingParameters.Add("skip", skip); tracingParameters.Add("top", top); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(this.Client.CloudServiceName); url = url + "/resources/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/~/"; url = url + "CisVault"; url = url + "/"; url = url + Uri.EscapeDataString(this.Client.ResourceName); url = url + "/api/devicejobs"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-01-01.2.0"); if (deviceId != null) { queryParameters.Add("deviceId=" + Uri.EscapeDataString(deviceId)); } if (jobType != null) { queryParameters.Add("type=" + Uri.EscapeDataString(jobType)); } if (jobStatus != null) { queryParameters.Add("status=" + Uri.EscapeDataString(jobStatus)); } if (jobId != null) { queryParameters.Add("jobId=" + Uri.EscapeDataString(jobId)); } if (startTime != null) { queryParameters.Add("startTime=" + Uri.EscapeDataString(startTime)); } if (endTime != null) { queryParameters.Add("endTime=" + Uri.EscapeDataString(endTime)); } queryParameters.Add("skip=" + Uri.EscapeDataString(skip.ToString())); queryParameters.Add("top=" + Uri.EscapeDataString(top.ToString())); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/xml"); httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Language); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2014-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetDeviceJobResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetDeviceJobResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement jobQueryResultV2Element = responseDoc.Element(XName.Get("JobQueryResult_V2", "http://windowscloudbackup.com/CiS/V2013_03")); if (jobQueryResultV2Element != null) { XElement nextPageUriElement = jobQueryResultV2Element.Element(XName.Get("NextPageUri", "http://windowscloudbackup.com/CiS/V2013_03")); if (nextPageUriElement != null) { string nextPageUriInstance = nextPageUriElement.Value; result.NextPageUri = nextPageUriInstance; } XElement nextPageStartIdentifierElement = jobQueryResultV2Element.Element(XName.Get("NextPageStartIdentifier", "http://windowscloudbackup.com/CiS/V2013_03")); if (nextPageStartIdentifierElement != null) { string nextPageStartIdentifierInstance = nextPageStartIdentifierElement.Value; result.NextPageStartIdentifier = nextPageStartIdentifierInstance; } XElement deviceJobListSequenceElement = jobQueryResultV2Element.Element(XName.Get("DeviceJobList", "http://windowscloudbackup.com/CiS/V2013_03")); if (deviceJobListSequenceElement != null) { foreach (XElement deviceJobListElement in deviceJobListSequenceElement.Elements(XName.Get("JobDetails", "http://windowscloudbackup.com/CiS/V2013_03"))) { DeviceJobDetails jobDetailsInstance = new DeviceJobDetails(); result.DeviceJobList.Add(jobDetailsInstance); XElement instanceIdElement = deviceJobListElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement != null) { string instanceIdInstance = instanceIdElement.Value; jobDetailsInstance.InstanceId = instanceIdInstance; } XElement nameElement = deviceJobListElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement != null) { string nameInstance = nameElement.Value; jobDetailsInstance.Name = nameInstance; } XElement typeElement = deviceJobListElement.Element(XName.Get("Type", "http://windowscloudbackup.com/CiS/V2013_03")); if (typeElement != null) { string typeInstance = typeElement.Value; jobDetailsInstance.Type = typeInstance; } XElement statusElement = deviceJobListElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); if (statusElement != null) { string statusInstance = statusElement.Value; jobDetailsInstance.Status = statusInstance; } XElement progressElement = deviceJobListElement.Element(XName.Get("Progress", "http://windowscloudbackup.com/CiS/V2013_03")); if (progressElement != null) { int progressInstance = int.Parse(progressElement.Value, CultureInfo.InvariantCulture); jobDetailsInstance.Progress = progressInstance; } XElement timeStatsElement = deviceJobListElement.Element(XName.Get("TimeStats", "http://windowscloudbackup.com/CiS/V2013_03")); if (timeStatsElement != null) { TimeStatistics timeStatsInstance = new TimeStatistics(); jobDetailsInstance.TimeStats = timeStatsInstance; XElement startTimestampElement = timeStatsElement.Element(XName.Get("StartTimestamp", "http://windowscloudbackup.com/CiS/V2013_03")); if (startTimestampElement != null) { DateTime startTimestampInstance = DateTime.Parse(startTimestampElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); timeStatsInstance.StartTimestamp = startTimestampInstance; } XElement endTimestampElement = timeStatsElement.Element(XName.Get("EndTimestamp", "http://windowscloudbackup.com/CiS/V2013_03")); if (endTimestampElement != null) { DateTime endTimestampInstance = DateTime.Parse(endTimestampElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); timeStatsInstance.EndTimestamp = endTimestampInstance; } XElement durationElement = timeStatsElement.Element(XName.Get("Duration", "http://windowscloudbackup.com/CiS/V2013_03")); if (durationElement != null) { string durationInstance = durationElement.Value; timeStatsInstance.Duration = durationInstance; } } XElement dataStatsElement = deviceJobListElement.Element(XName.Get("DataStats", "http://windowscloudbackup.com/CiS/V2013_03")); if (dataStatsElement != null) { DataStatistics dataStatsInstance = new DataStatistics(); jobDetailsInstance.DataStats = dataStatsInstance; XElement totalDataElement = dataStatsElement.Element(XName.Get("TotalData", "http://windowscloudbackup.com/CiS/V2013_03")); if (totalDataElement != null) { long totalDataInstance = long.Parse(totalDataElement.Value, CultureInfo.InvariantCulture); dataStatsInstance.TotalData = totalDataInstance; } XElement processedDataElement = dataStatsElement.Element(XName.Get("ProcessedData", "http://windowscloudbackup.com/CiS/V2013_03")); if (processedDataElement != null) { long processedDataInstance = long.Parse(processedDataElement.Value, CultureInfo.InvariantCulture); dataStatsInstance.ProcessedData = processedDataInstance; } XElement cloudDataElement = dataStatsElement.Element(XName.Get("CloudData", "http://windowscloudbackup.com/CiS/V2013_03")); if (cloudDataElement != null) { long cloudDataInstance = long.Parse(cloudDataElement.Value, CultureInfo.InvariantCulture); dataStatsInstance.CloudData = cloudDataInstance; } XElement throughputElement = dataStatsElement.Element(XName.Get("Throughput", "http://windowscloudbackup.com/CiS/V2013_03")); if (throughputElement != null) { long throughputInstance = long.Parse(throughputElement.Value, CultureInfo.InvariantCulture); dataStatsInstance.Throughput = throughputInstance; } } XElement deviceElement = deviceJobListElement.Element(XName.Get("Device", "http://windowscloudbackup.com/CiS/V2013_03")); if (deviceElement != null) { CisBaseObject deviceInstance = new CisBaseObject(); jobDetailsInstance.Device = deviceInstance; XElement nameElement2 = deviceElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement2 != null) { string nameInstance2 = nameElement2.Value; deviceInstance.Name = nameInstance2; } XElement instanceIdElement2 = deviceElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement2 != null) { string instanceIdInstance2 = instanceIdElement2.Value; deviceInstance.InstanceId = instanceIdInstance2; } XElement operationInProgressElement = deviceElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement != null) { OperationInProgress operationInProgressInstance = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement.Value, true)); deviceInstance.OperationInProgress = operationInProgressInstance; } } XElement sourceDeviceElement = deviceJobListElement.Element(XName.Get("SourceDevice", "http://windowscloudbackup.com/CiS/V2013_03")); if (sourceDeviceElement != null) { CisBaseObject sourceDeviceInstance = new CisBaseObject(); jobDetailsInstance.SourceDevice = sourceDeviceInstance; XElement nameElement3 = sourceDeviceElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement3 != null) { string nameInstance3 = nameElement3.Value; sourceDeviceInstance.Name = nameInstance3; } XElement instanceIdElement3 = sourceDeviceElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement3 != null) { string instanceIdInstance3 = instanceIdElement3.Value; sourceDeviceInstance.InstanceId = instanceIdInstance3; } XElement operationInProgressElement2 = sourceDeviceElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement2 != null) { OperationInProgress operationInProgressInstance2 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement2.Value, true)); sourceDeviceInstance.OperationInProgress = operationInProgressInstance2; } } XElement entityElement = deviceJobListElement.Element(XName.Get("Entity", "http://windowscloudbackup.com/CiS/V2013_03")); if (entityElement != null) { CisBaseObject entityInstance = new CisBaseObject(); jobDetailsInstance.Entity = entityInstance; XElement nameElement4 = entityElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement4 != null) { string nameInstance4 = nameElement4.Value; entityInstance.Name = nameInstance4; } XElement instanceIdElement4 = entityElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement4 != null) { string instanceIdInstance4 = instanceIdElement4.Value; entityInstance.InstanceId = instanceIdInstance4; } XElement operationInProgressElement3 = entityElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement3 != null) { OperationInProgress operationInProgressInstance3 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement3.Value, true)); entityInstance.OperationInProgress = operationInProgressInstance3; } } XElement sourceEntityElement = deviceJobListElement.Element(XName.Get("SourceEntity", "http://windowscloudbackup.com/CiS/V2013_03")); if (sourceEntityElement != null) { CisBaseObject sourceEntityInstance = new CisBaseObject(); jobDetailsInstance.SourceEntity = sourceEntityInstance; XElement nameElement5 = sourceEntityElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement5 != null) { string nameInstance5 = nameElement5.Value; sourceEntityInstance.Name = nameInstance5; } XElement instanceIdElement5 = sourceEntityElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement5 != null) { string instanceIdInstance5 = instanceIdElement5.Value; sourceEntityInstance.InstanceId = instanceIdInstance5; } XElement operationInProgressElement4 = sourceEntityElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement4 != null) { OperationInProgress operationInProgressInstance4 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement4.Value, true)); sourceEntityInstance.OperationInProgress = operationInProgressInstance4; } } XElement volumeElement = deviceJobListElement.Element(XName.Get("Volume", "http://windowscloudbackup.com/CiS/V2013_03")); if (volumeElement != null) { CisBaseObject volumeInstance = new CisBaseObject(); jobDetailsInstance.Volume = volumeInstance; XElement nameElement6 = volumeElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement6 != null) { string nameInstance6 = nameElement6.Value; volumeInstance.Name = nameInstance6; } XElement instanceIdElement6 = volumeElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement6 != null) { string instanceIdInstance6 = instanceIdElement6.Value; volumeInstance.InstanceId = instanceIdInstance6; } XElement operationInProgressElement5 = volumeElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement5 != null) { OperationInProgress operationInProgressInstance5 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement5.Value, true)); volumeInstance.OperationInProgress = operationInProgressInstance5; } } XElement sourceVolumeElement = deviceJobListElement.Element(XName.Get("SourceVolume", "http://windowscloudbackup.com/CiS/V2013_03")); if (sourceVolumeElement != null) { CisBaseObject sourceVolumeInstance = new CisBaseObject(); jobDetailsInstance.SourceVolume = sourceVolumeInstance; XElement nameElement7 = sourceVolumeElement.Element(XName.Get("Name", "http://windowscloudbackup.com/CiS/V2013_03")); if (nameElement7 != null) { string nameInstance7 = nameElement7.Value; sourceVolumeInstance.Name = nameInstance7; } XElement instanceIdElement7 = sourceVolumeElement.Element(XName.Get("InstanceId", "http://windowscloudbackup.com/CiS/V2013_03")); if (instanceIdElement7 != null) { string instanceIdInstance7 = instanceIdElement7.Value; sourceVolumeInstance.InstanceId = instanceIdInstance7; } XElement operationInProgressElement6 = sourceVolumeElement.Element(XName.Get("OperationInProgress", "http://windowscloudbackup.com/CiS/V2013_03")); if (operationInProgressElement6 != null) { OperationInProgress operationInProgressInstance6 = ((OperationInProgress)Enum.Parse(typeof(OperationInProgress), operationInProgressElement6.Value, true)); sourceVolumeInstance.OperationInProgress = operationInProgressInstance6; } } XElement backupTimeStampElement = deviceJobListElement.Element(XName.Get("BackupTimeStamp", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupTimeStampElement != null) { DateTime backupTimeStampInstance = DateTime.Parse(backupTimeStampElement.Value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal).ToLocalTime(); jobDetailsInstance.BackupTimeStamp = backupTimeStampInstance; } XElement backupPolicyElement = deviceJobListElement.Element(XName.Get("BackupPolicy", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupPolicyElement != null) { string backupPolicyInstance = backupPolicyElement.Value; jobDetailsInstance.BackupPolicy = backupPolicyInstance; } XElement backupTypeElement = deviceJobListElement.Element(XName.Get("BackupType", "http://windowscloudbackup.com/CiS/V2013_03")); if (backupTypeElement != null) { BackupType backupTypeInstance = ((BackupType)Enum.Parse(typeof(BackupType), backupTypeElement.Value, true)); jobDetailsInstance.BackupType = backupTypeInstance; } XElement jobDetailsElement = deviceJobListElement.Element(XName.Get("JobDetails", "http://windowscloudbackup.com/CiS/V2013_03")); if (jobDetailsElement != null) { JobStatusInfo jobDetailsInstance2 = new JobStatusInfo(); jobDetailsInstance.JobDetails = jobDetailsInstance2; XElement jobIdElement = jobDetailsElement.Element(XName.Get("JobId", "http://windowscloudbackup.com/CiS/V2013_03")); if (jobIdElement != null) { string jobIdInstance = jobIdElement.Value; jobDetailsInstance2.JobId = jobIdInstance; } XElement statusElement2 = jobDetailsElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); if (statusElement2 != null) { JobStatus statusInstance2 = ((JobStatus)Enum.Parse(typeof(JobStatus), statusElement2.Value, true)); jobDetailsInstance2.Status = statusInstance2; } XElement resultElement = jobDetailsElement.Element(XName.Get("Result", "http://windowscloudbackup.com/CiS/V2013_03")); if (resultElement != null) { JobResult resultInstance = ((JobResult)Enum.Parse(typeof(JobResult), resultElement.Value, true)); jobDetailsInstance2.Result = resultInstance; } XElement errorElement = jobDetailsElement.Element(XName.Get("Error", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorElement != null) { CisApiError errorInstance = new CisApiError(); jobDetailsInstance2.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://windowscloudbackup.com/CiS/V2013_03")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement errorCodeElement = errorElement.Element(XName.Get("ErrorCode", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorCodeElement != null) { string errorCodeInstance = errorCodeElement.Value; errorInstance.ErrorCode = errorCodeInstance; } XElement languageElement = errorElement.Element(XName.Get("Language", "http://windowscloudbackup.com/CiS/V2013_03")); if (languageElement != null) { string languageInstance = languageElement.Value; errorInstance.Language = languageInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://windowscloudbackup.com/CiS/V2013_03")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } XElement itemsSequenceElement = errorElement.Element(XName.Get("Items", "http://windowscloudbackup.com/CiS/V2013_03")); if (itemsSequenceElement != null) { foreach (XElement itemsElement in itemsSequenceElement.Elements(XName.Get("Item", "http://windowscloudbackup.com/CiS/V2013_03"))) { Item itemInstance = new Item(); errorInstance.Values.Add(itemInstance); XElement keyElement = itemsElement.Element(XName.Get("Key", "http://windowscloudbackup.com/CiS/V2013_03")); if (keyElement != null) { string keyInstance = keyElement.Value; itemInstance.Key = keyInstance; } XElement valueElement = itemsElement.Element(XName.Get("Value", "http://windowscloudbackup.com/CiS/V2013_03")); if (valueElement != null) { string valueInstance = valueElement.Value; itemInstance.Value = valueInstance; } } } } XElement taskResultElement = jobDetailsElement.Element(XName.Get("TaskResult", "http://windowscloudbackup.com/CiS/V2013_03")); if (taskResultElement != null) { TaskResult taskResultInstance = ((TaskResult)Enum.Parse(typeof(TaskResult), taskResultElement.Value, true)); jobDetailsInstance2.TaskResult = taskResultInstance; } XElement jobStepsSequenceElement = jobDetailsElement.Element(XName.Get("JobSteps", "http://windowscloudbackup.com/CiS/V2013_03")); if (jobStepsSequenceElement != null) { foreach (XElement jobStepsElement in jobStepsSequenceElement.Elements(XName.Get("JobStep", "http://windowscloudbackup.com/CiS/V2013_03"))) { JobStep jobStepInstance = new JobStep(); jobDetailsInstance2.JobSteps.Add(jobStepInstance); XElement messageElement2 = jobStepsElement.Element(XName.Get("Message", "http://windowscloudbackup.com/CiS/V2013_03")); if (messageElement2 != null) { string messageInstance2 = messageElement2.Value; jobStepInstance.Message = messageInstance2; } XElement statusElement3 = jobStepsElement.Element(XName.Get("Status", "http://windowscloudbackup.com/CiS/V2013_03")); if (statusElement3 != null) { JobStatus statusInstance3 = ((JobStatus)Enum.Parse(typeof(JobStatus), statusElement3.Value, true)); jobStepInstance.Status = statusInstance3; } XElement resultElement2 = jobStepsElement.Element(XName.Get("Result", "http://windowscloudbackup.com/CiS/V2013_03")); if (resultElement2 != null) { JobResult resultInstance2 = ((JobResult)Enum.Parse(typeof(JobResult), resultElement2.Value, true)); jobStepInstance.Result = resultInstance2; } XElement detailElement = jobStepsElement.Element(XName.Get("Detail", "http://windowscloudbackup.com/CiS/V2013_03")); if (detailElement != null) { string detailInstance = detailElement.Value; jobStepInstance.Detail = detailInstance; } XElement errorCodeElement2 = jobStepsElement.Element(XName.Get("ErrorCode", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorCodeElement2 != null) { string errorCodeInstance2 = errorCodeElement2.Value; jobStepInstance.ErrorCode = errorCodeInstance2; } } } } XElement isJobCancellableElement = deviceJobListElement.Element(XName.Get("IsJobCancellable", "http://windowscloudbackup.com/CiS/V2013_03")); if (isJobCancellableElement != null) { bool isJobCancellableInstance = bool.Parse(isJobCancellableElement.Value); jobDetailsInstance.IsJobCancellable = isJobCancellableInstance; } XElement errorDetailsSequenceElement = deviceJobListElement.Element(XName.Get("ErrorDetails", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorDetailsSequenceElement != null) { foreach (XElement errorDetailsElement in errorDetailsSequenceElement.Elements(XName.Get("ErrorInfo", "http://windowscloudbackup.com/CiS/V2013_03"))) { ErrorInfo errorInfoInstance = new ErrorInfo(); jobDetailsInstance.ErrorDetails.Add(errorInfoInstance); XElement errorCodeElement3 = errorDetailsElement.Element(XName.Get("ErrorCode", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorCodeElement3 != null) { int errorCodeInstance3 = int.Parse(errorCodeElement3.Value, CultureInfo.InvariantCulture); errorInfoInstance.ErrorCode = errorCodeInstance3; } XElement errorTitleElement = errorDetailsElement.Element(XName.Get("ErrorTitle", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorTitleElement != null) { string errorTitleInstance = errorTitleElement.Value; errorInfoInstance.ErrorTitle = errorTitleInstance; } XElement errorStringElement = errorDetailsElement.Element(XName.Get("ErrorString", "http://windowscloudbackup.com/CiS/V2013_03")); if (errorStringElement != null) { string errorStringInstance = errorStringElement.Value; errorInfoInstance.ErrorString = errorStringInstance; } XElement recommendationsSequenceElement = errorDetailsElement.Element(XName.Get("Recommendations", "http://windowscloudbackup.com/CiS/V2013_03")); if (recommendationsSequenceElement != null) { foreach (XElement recommendationsElement in recommendationsSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays"))) { errorInfoInstance.Recommendations.Add(recommendationsElement.Value); } } } } XElement hideProgressDetailsElement = deviceJobListElement.Element(XName.Get("HideProgressDetails", "http://windowscloudbackup.com/CiS/V2013_03")); if (hideProgressDetailsElement != null) { bool hideProgressDetailsInstance = bool.Parse(hideProgressDetailsElement.Value); jobDetailsInstance.HideProgressDetails = hideProgressDetailsInstance; } XElement isInstantRestoreCompleteElement = deviceJobListElement.Element(XName.Get("IsInstantRestoreComplete", "http://windowscloudbackup.com/CiS/V2013_03")); if (isInstantRestoreCompleteElement != null) { bool isInstantRestoreCompleteInstance = bool.Parse(isInstantRestoreCompleteElement.Value); jobDetailsInstance.IsInstantRestoreComplete = isInstantRestoreCompleteInstance; } } } XElement countElement = jobQueryResultV2Element.Element(XName.Get("Count", "http://windowscloudbackup.com/CiS/V2013_03")); if (countElement != null) { int countInstance = int.Parse(countElement.Value, CultureInfo.InvariantCulture); result.Count = countInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a device job /// </summary> /// <param name='deviceId'> /// Required. id of device /// </param> /// <param name='jobId'> /// Required. id of job to update /// </param> /// <param name='updateRequest'> /// Required. Request data, contains the action to be taken /// </param> /// <param name='customRequestHeaders'> /// Required. The Custom Request Headers which client must use. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Info about the async task /// </returns> public async Task<TaskStatusInfo> UpdateDeviceJobAsync(string deviceId, string jobId, UpdateDeviceJobRequest updateRequest, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { StorSimpleManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("deviceId", deviceId); tracingParameters.Add("jobId", jobId); tracingParameters.Add("updateRequest", updateRequest); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "UpdateDeviceJobAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); GuidTaskResponse response = await client.DeviceJob.BeginUpdateDeviceJobAsync(deviceId, jobId, updateRequest, customRequestHeaders, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); TaskStatusInfo result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 5; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.TaskId, cancellationToken).ConfigureAwait(false); delayInSeconds = 5; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.AsyncTaskAggregatedResult != AsyncTaskAggregatedResult.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Security.Cryptography.X509Certificates; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests { public static class SignedCmsWholeDocumentTests { [Fact] public static void ReadRsaPssDocument() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPssDocument); Assert.Equal(3, cms.Version); ContentInfo contentInfo = cms.ContentInfo; Assert.Equal("1.2.840.113549.1.7.1", contentInfo.ContentType.Value); Assert.Equal("54686973206973206120746573740D0A", contentInfo.Content.ByteArrayToHex()); X509Certificate2Collection certs = cms.Certificates; Assert.Single(certs); X509Certificate2 topLevelCert = certs[0]; Assert.Equal("localhost", topLevelCert.GetNameInfo(X509NameType.SimpleName, false)); Assert.Equal( new DateTimeOffset(2016, 3, 2, 2, 37, 54, TimeSpan.Zero), new DateTimeOffset(topLevelCert.NotBefore)); Assert.Equal( new DateTimeOffset(2017, 3, 2, 2, 37, 54, TimeSpan.Zero), new DateTimeOffset(topLevelCert.NotAfter)); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; Assert.Equal(3, signer.Version); Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifier.Type); Assert.Equal("1063CAB14FB14C47DC211C0E0285F3EE5946BF2D", signer.SignerIdentifier.Value); Assert.Equal("2.16.840.1.101.3.4.2.1", signer.DigestAlgorithm.Value); #if NETCOREAPP Assert.Equal("1.2.840.113549.1.1.10", signer.SignatureAlgorithm.Value); #endif CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Equal(4, signedAttrs.Count); Assert.Equal("1.2.840.113549.1.9.3", signedAttrs[0].Oid.Value); Assert.Equal("1.2.840.113549.1.9.5", signedAttrs[1].Oid.Value); Assert.Equal("1.2.840.113549.1.9.4", signedAttrs[2].Oid.Value); Assert.Equal("1.2.840.113549.1.9.15", signedAttrs[3].Oid.Value); Assert.Equal(1, signedAttrs[0].Values.Count); Assert.Equal(1, signedAttrs[1].Values.Count); Assert.Equal(1, signedAttrs[2].Values.Count); Assert.Equal(1, signedAttrs[3].Values.Count); Pkcs9ContentType contentTypeAttr = (Pkcs9ContentType)signedAttrs[0].Values[0]; Assert.Equal("1.2.840.113549.1.7.1", contentTypeAttr.ContentType.Value); Pkcs9SigningTime signingTimeAttr = (Pkcs9SigningTime)signedAttrs[1].Values[0]; Assert.Equal( new DateTimeOffset(2017, 10, 26, 1, 6, 25, TimeSpan.Zero), new DateTimeOffset(signingTimeAttr.SigningTime)); Pkcs9MessageDigest messageDigestAttr = (Pkcs9MessageDigest)signedAttrs[2].Values[0]; Assert.Equal( "07849DC26FCBB2F3BD5F57BDF214BAE374575F1BD4E6816482324799417CB379", messageDigestAttr.MessageDigest.ByteArrayToHex()); Assert.IsType<Pkcs9AttributeObject>(signedAttrs[3].Values[0]); Assert.NotSame(signedAttrs[3].Oid, signedAttrs[3].Values[0].Oid); Assert.Equal( "306A300B060960864801650304012A300B0609608648016503040116300B0609" + "608648016503040102300A06082A864886F70D0307300E06082A864886F70D03" + "0202020080300D06082A864886F70D0302020140300706052B0E030207300D06" + "082A864886F70D0302020128", signedAttrs[3].Values[0].RawData.ByteArrayToHex()); #if NETCOREAPP Assert.Equal( "B93E81D141B3C9F159AB0021910635DC72E8E860BE43C28E5D53243D6DC247B7" + "D4F18C20195E80DEDCC75B29C43CE5047AD775B65BFC93589BD748B950C68BAD" + "DF1A4673130302BBDA8667D5DDE5EA91ECCB13A9B4C04F1C4842FEB1697B7669" + "C7692DD3BDAE13B5AA8EE3EB5679F3729D1DC4F2EB9DC89B7E8773F2F8C6108C" + "05", signer.GetSignature().ByteArrayToHex()); #endif CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes; Assert.Empty(unsignedAttrs); SignerInfoCollection counterSigners = signer.CounterSignerInfos; Assert.Empty(counterSigners); X509Certificate2 signerCertificate = signer.Certificate; Assert.Equal( "CN=localhost, OU=.NET Framework, O=Microsoft Corp., L=Redmond, S=Washington, C=US", signerCertificate.SubjectName.Name); // CheckHash always throws for certificate-based signers. Assert.Throws<CryptographicException>(() => signer.CheckHash()); // At this time we cannot support the PSS parameters for this document. Assert.Throws<CryptographicException>(() => signer.CheckSignature(true)); // Since there are no NoSignature signers the document CheckHash will succeed. // Assert.NotThrows cms.CheckHash(); // Since at least one signer fails, the document signature will fail Assert.Throws<CryptographicException>(() => cms.CheckSignature(true)); } [Fact] public static void ReadRsaPkcs1SimpleDocument() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber); Assert.Equal(1, cms.Version); ContentInfo contentInfo = cms.ContentInfo; Assert.Equal("1.2.840.113549.1.7.1", contentInfo.ContentType.Value); Assert.Equal("4D6963726F736F667420436F72706F726174696F6E", contentInfo.Content.ByteArrayToHex()); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { X509Certificate2Collection certs = cms.Certificates; Assert.Single(certs); Assert.Equal(cert, certs[0]); Assert.Equal(cert, signer.Certificate); Assert.NotSame(certs[0], signer.Certificate); Assert.NotSame(cert, signer.Certificate); Assert.NotSame(cert, certs[0]); } Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifier.Type); Assert.Equal(Oids.Sha1, signer.DigestAlgorithm.Value); #if NETCOREAPP Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); Assert.Equal( "5A1717621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6" + "B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E09" + "6EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B73" + "3A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3", signer.GetSignature().ByteArrayToHex()); #endif CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Empty(signedAttrs); CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes; Assert.Empty(unsignedAttrs); SignerInfoCollection counterSigners = signer.CounterSignerInfos; Assert.Empty(counterSigners); // Assert.NotThrows signer.CheckSignature(true); // CheckHash always throws for certificate-based signers. Assert.Throws<CryptographicException>(() => signer.CheckHash()); // Since there are no NoSignature signers the document CheckHash will succeed. // Assert.NotThrows cms.CheckHash(); // Since all the signers succeed the document will succeed cms.CheckSignature(true); } [Fact] public static void ReadRsaPkcs1CounterSigned() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.CounterSignedRsaPkcs1OneSigner); Assert.Equal(1, cms.Version); ContentInfo contentInfo = cms.ContentInfo; Assert.Equal("1.2.840.113549.1.7.1", contentInfo.ContentType.Value); Assert.Equal("4D6963726F736F667420436F72706F726174696F6E", contentInfo.Content.ByteArrayToHex()); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { X509Certificate2Collection certs = cms.Certificates; Assert.Single(certs); Assert.Equal(cert, certs[0]); Assert.Equal(cert, signer.Certificate); Assert.NotSame(certs[0], signer.Certificate); Assert.NotSame(cert, signer.Certificate); Assert.NotSame(cert, certs[0]); } Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifier.Type); Assert.Equal(Oids.Sha1, signer.DigestAlgorithm.Value); #if NETCOREAPP Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); Assert.Equal( "5A1717621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6" + "B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E09" + "6EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B73" + "3A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3", signer.GetSignature().ByteArrayToHex()); #endif CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Empty(signedAttrs); CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes; Assert.Single(unsignedAttrs); Assert.Equal(Oids.CounterSigner, unsignedAttrs[0].Oid.Value); SignerInfoCollection counterSigners = signer.CounterSignerInfos; Assert.Single(counterSigners); SignerInfo counterSigner = counterSigners[0]; Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, counterSigner.SignerIdentifier.Type); // Not universally true, but is in this case. Assert.Equal(signer.Certificate, counterSigner.Certificate); Assert.NotSame(signer.Certificate, counterSigner.Certificate); // Assert.NotThrows signer.CheckSignature(true); // Assert.NotThrows counterSigner.CheckSignature(true); // The document should be validly signed, then. // Assert.NotThrows cms.CheckSignature(true); // If CheckSignature succeeds then CheckHash cannot. Assert.Throws<CryptographicException>(() => counterSigner.CheckHash()); Assert.Throws<CryptographicException>(() => signer.CheckHash()); // Since there are no NoSignature signers, CheckHash won't throw. // Assert.NotThrows cms.CheckHash(); } [Fact] public static void CheckNoSignatureDocument() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.NoSignatureSignedWithAttributesAndCounterSignature); Assert.Equal(1, cms.Version); Assert.Equal(Oids.Pkcs7Data, cms.ContentInfo.ContentType.Value); Assert.Equal( "4D6963726F736F667420436F72706F726174696F6E", cms.ContentInfo.Content.ByteArrayToHex()); X509Certificate2Collection cmsCerts = cms.Certificates; Assert.Single(cmsCerts); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; Assert.Equal(SubjectIdentifierType.NoSignature, signer.SignerIdentifier.Type); Assert.Null(signer.SignerIdentifier.Value); Assert.Null(signer.Certificate); Assert.Equal(Oids.Sha1, signer.DigestAlgorithm.Value); #if NETCOREAPP Assert.Equal("1.3.6.1.5.5.7.6.2", signer.SignatureAlgorithm.Value); Assert.Equal( "8B70D20D0477A35CD84AB962C10DC52FBA6FAD6B", signer.GetSignature().ByteArrayToHex()); #endif CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Equal(3, signedAttrs.Count); Assert.Single(signedAttrs[0].Values); Assert.Single(signedAttrs[1].Values); Assert.Single(signedAttrs[2].Values); Pkcs9ContentType contentType = (Pkcs9ContentType)signedAttrs[0].Values[0]; Pkcs9SigningTime signingTime = (Pkcs9SigningTime)signedAttrs[1].Values[0]; Pkcs9MessageDigest messageDigest = (Pkcs9MessageDigest)signedAttrs[2].Values[0]; Assert.Equal(Oids.Pkcs7Data, contentType.ContentType.Value); Assert.Equal( new DateTimeOffset(2017, 11, 1, 17, 17, 17, TimeSpan.Zero), signingTime.SigningTime); Assert.Equal(DateTimeKind.Utc, signingTime.SigningTime.Kind); using (SHA1 sha1 = SHA1.Create()) { Assert.Equal( sha1.ComputeHash(cms.ContentInfo.Content).ByteArrayToHex(), messageDigest.MessageDigest.ByteArrayToHex()); } CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes; Assert.Single(unsignedAttrs); // No need to check the contents, it's a CounterSigner (tested next) SignerInfoCollection counterSigners = signer.CounterSignerInfos; Assert.Single(counterSigners); SignerInfo counterSigner = counterSigners[0]; Assert.Equal(3, counterSigner.Version); Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, counterSigner.SignerIdentifier.Type); Assert.Equal("6B4A6B92FDED07EE0119F3674A96D1A70D2A588D", (string)counterSigner.SignerIdentifier.Value); Assert.Equal(Oids.Sha1, counterSigner.DigestAlgorithm.Value); CryptographicAttributeObjectCollection csSignedAttrs = counterSigner.SignedAttributes; Assert.Equal(2, csSignedAttrs.Count); // RFC3369 says that the content-type attribute must not be present for counter-signers, but it is. // RFC2630 said that it "is not required". Pkcs9ContentType csContentType = (Pkcs9ContentType)csSignedAttrs[0].Values[0]; Pkcs9MessageDigest csMessageDigest = (Pkcs9MessageDigest)csSignedAttrs[1].Values[0]; Assert.Equal(Oids.Pkcs7Data, csContentType.ContentType.Value); Assert.Equal( "833378066BDCCBA7047EF6919843D181A57D6479", csMessageDigest.MessageDigest.ByteArrayToHex()); #if NETCOREAPP Assert.Equal(Oids.Rsa, counterSigner.SignatureAlgorithm.Value); Assert.Equal( "2155D226DD744166E582D040E60535210195050EA00F2C179897198521DABD0E" + "6B27750FD8BA5F9AAF58B4863B6226456F38553A22453CAF0A0F106766C7AB6F" + "3D6AFD106753DC50F8A6E4F9E5508426D236C2DBB4BCB8162FA42E995CBA16A3" + "40FD7C793569DF1B71368E68253299BC74E38312B40B8F52EAEDE10DF414A522", counterSigner.GetSignature().ByteArrayToHex()); #endif using (X509Certificate2 capiCert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { Assert.Equal(capiCert, cmsCerts[0]); Assert.Equal(capiCert, counterSigner.Certificate); } // The counter-signer has a (real) signature, and a certificate, so CheckSignature // will pass counterSigner.CheckSignature(true); // The (primary) signer has a hash-only signature with no certificate, // so CheckSignature will fail. Assert.Throws<CryptographicException>(() => signer.CheckSignature(true)); // The (primary) signer is a NoSignature type, so CheckHash will succeed signer.CheckHash(); // The document has a NoSignature signer, so CheckHash will do something (and succeed). cms.CheckHash(); // Since the document's primary signer is NoSignature, CheckSignature will fail Assert.Throws<CryptographicException>(() => cms.CheckSignature(true)); } [Fact] public static void NonEmbeddedCertificate() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.RsaCapiTransfer1_NoEmbeddedCert); Assert.Equal(3, cms.Version); Assert.Equal(Oids.Pkcs7Data, cms.ContentInfo.ContentType.Value); Assert.Equal( "4D6963726F736F667420436F72706F726174696F6E", cms.ContentInfo.Content.ByteArrayToHex()); Assert.Empty(cms.Certificates); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; Assert.Equal(3, signer.Version); Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, signer.SignerIdentifier.Type); Assert.Equal("6B4A6B92FDED07EE0119F3674A96D1A70D2A588D", (string)signer.SignerIdentifier.Value); Assert.Equal(Oids.Sha1, signer.DigestAlgorithm.Value); CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Equal(3, signedAttrs.Count); Pkcs9ContentType contentType = (Pkcs9ContentType)signedAttrs[0].Values[0]; Pkcs9SigningTime signingTime = (Pkcs9SigningTime)signedAttrs[1].Values[0]; Pkcs9MessageDigest messageDigest = (Pkcs9MessageDigest)signedAttrs[2].Values[0]; Assert.Equal(Oids.Pkcs7Data, contentType.ContentType.Value); Assert.Equal( new DateTimeOffset(2017, 11, 2, 15, 34, 4, TimeSpan.Zero), signingTime.SigningTime); Assert.Equal(DateTimeKind.Utc, signingTime.SigningTime.Kind); Assert.Empty(signer.UnsignedAttributes); Assert.Empty(signer.CounterSignerInfos); Assert.Null(signer.Certificate); #if NETCOREAPP Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); Assert.Equal( "0EDE3870B8A80B45A21BAEC4681D059B46502E1B1AA6B8920CF50D4D837646A5" + "5559B4C05849126C655D95FF3C6C1B420E07DC42629F294EE69822FEA56F32D4" + "1B824CBB6BF809B7583C27E77B7AC58DFC925B1C60EA4A67AA84D73FC9E9191D" + "33B36645F17FD6748A2D8B12C6C384C3C734D27273386211E4518FE2B4ED0147", signer.GetSignature().ByteArrayToHex()); #endif using (SHA1 sha1 = SHA1.Create()) { Assert.Equal( sha1.ComputeHash(cms.ContentInfo.Content).ByteArrayToHex(), messageDigest.MessageDigest.ByteArrayToHex()); } // Since it's not NoSignature CheckHash will throw. Assert.Throws<CryptographicException>(() => signer.CheckHash()); // Since there's no matched certificate CheckSignature will throw. Assert.Throws<CryptographicException>(() => signer.CheckSignature(true)); // Since there are no NoSignature signers, SignedCms.CheckHash will succeed cms.CheckHash(); // Since there are no matched certificates SignedCms.CheckSignature will throw. Assert.Throws<CryptographicException>(() => cms.CheckSignature(true)); using (X509Certificate2 wrongCert = Certificates.RSAKeyTransfer1.GetCertificate()) using (X509Certificate2 rightCert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { X509Certificate2Collection coll = new X509Certificate2Collection(wrongCert); // Wrong certificate, still throw. Assert.Throws<CryptographicException>(() => signer.CheckSignature(coll, true)); Assert.Throws<CryptographicException>(() => cms.CheckSignature(coll, true)); coll = new X509Certificate2Collection(rightCert); // Right cert, success signer.CheckSignature(coll, true); Assert.Null(signer.Certificate); cms.CheckSignature(coll, true); Assert.Null(cms.SignerInfos[0].Certificate); coll.Add(wrongCert); // Both right and wrong, success signer.CheckSignature(coll, true); Assert.Null(signer.Certificate); cms.CheckSignature(coll, true); Assert.Null(cms.SignerInfos[0].Certificate); coll = new X509Certificate2Collection(wrongCert); // Just wrong again, no accidental stateful match Assert.Throws<CryptographicException>(() => signer.CheckSignature(coll, true)); Assert.Throws<CryptographicException>(() => cms.CheckSignature(coll, true)); coll.Add(rightCert); // Wrong then right, success signer.CheckSignature(coll, true); Assert.Null(signer.Certificate); cms.CheckSignature(coll, true); Assert.Null(cms.SignerInfos[0].Certificate); } } [Fact] public static void ReadRsaPkcs1DoubleCounterSigned() { SignedCms cms = new SignedCms(); cms.Decode(SignedDocuments.OneRsaSignerTwoRsaCounterSigners); Assert.Equal(1, cms.Version); ContentInfo contentInfo = cms.ContentInfo; Assert.Equal("1.2.840.113549.1.7.1", contentInfo.ContentType.Value); Assert.Equal("4D6963726F736F667420436F72706F726174696F6E", contentInfo.Content.ByteArrayToHex()); SignerInfoCollection signers = cms.SignerInfos; Assert.Single(signers); SignerInfo signer = signers[0]; using (X509Certificate2 cert = Certificates.RSAKeyTransferCapi1.GetCertificate()) { X509Certificate2Collection certs = cms.Certificates; Assert.Equal(2, certs.Count); Assert.Equal(cert, certs[1]); Assert.Equal(cert, signer.Certificate); Assert.NotSame(certs[1], signer.Certificate); Assert.NotSame(cert, signer.Certificate); Assert.NotSame(cert, certs[1]); } Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, signer.SignerIdentifier.Type); Assert.Equal(Oids.Sha1, signer.DigestAlgorithm.Value); #if NETCOREAPP Assert.Equal(Oids.Rsa, signer.SignatureAlgorithm.Value); Assert.Equal( "5A1717621D450130B3463662160EEC06F7AE77E017DD95F294E97A0BDD433FE6" + "B2CCB34FAAC33AEA50BFD7D9E78DC7174836284619F744278AE77B8495091E09" + "6EEF682D9CA95F6E81C7DDCEDDA6A12316B453C894B5000701EB09DF57A53B73" + "3A4E80DA27FA710870BD88C86E2FDB9DCA14D18BEB2F0C87E9632ABF02BE2FE3", signer.GetSignature().ByteArrayToHex()); #endif CryptographicAttributeObjectCollection signedAttrs = signer.SignedAttributes; Assert.Empty(signedAttrs); CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes; Assert.Equal(2, unsignedAttrs.Count); Assert.Equal(Oids.CounterSigner, unsignedAttrs[0].Oid.Value); SignerInfoCollection counterSigners = signer.CounterSignerInfos; Assert.Equal(2, counterSigners.Count); SignerInfo cs1 = counterSigners[0]; SignerInfo cs2 = counterSigners[1]; Assert.Equal(SubjectIdentifierType.SubjectKeyIdentifier, cs1.SignerIdentifier.Type); // Not universally true, but is in this case. Assert.Equal(signer.Certificate, cs1.Certificate); Assert.NotSame(signer.Certificate, cs1.Certificate); Assert.Equal(SubjectIdentifierType.IssuerAndSerialNumber, cs2.SignerIdentifier.Type); Assert.NotEqual(signer.Certificate, cs2.Certificate); // Assert.NotThrows signer.CheckSignature(true); // Assert.NotThrows cs1.CheckSignature(true); // Assert.NotThrows cs2.CheckSignature(true); // The document should be validly signed, then. // Assert.NotThrows cms.CheckSignature(true); #if NETCOREAPP Assert.Equal( "1AA282DBED4D862D7CEA30F803E790BDB0C97EE852778CEEDDCD94BB9304A155" + "2E60A8D36052AC8C2D28755F3B2F473824100AB3A6ABD4C15ABD77E0FFE13D0D" + "F253BCD99C718FA673B6CB0CBBC68CE5A4AC671298C0A07C7223522E0E7FFF15" + "CEDBAB55AAA99588517674671691065EB083FB729D1E9C04B2BF99A9953DAA5E", cs2.GetSignature().ByteArrayToHex()); #endif // If CheckSignature succeeds then CheckHash cannot. Assert.Throws<CryptographicException>(() => cs1.CheckHash()); Assert.Throws<CryptographicException>(() => cs2.CheckHash()); Assert.Throws<CryptographicException>(() => signer.CheckHash()); // Since there are no NoSignature signers, CheckHash won't throw. // Assert.NotThrows cms.CheckHash(); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Dispatcher { using System.Collections.Generic; using System.Runtime; using System.Text; internal class TrieSegmentComparer : IComparer<TrieSegment> { public int Compare(TrieSegment t1, TrieSegment t2) { return ((int)t1.FirstChar) - ((int)t2.FirstChar); } public bool Equals(TrieSegment t1, TrieSegment t2) { return t1.FirstChar == t2.FirstChar; } public int GetHashCode(TrieSegment t) { return t.GetHashCode(); } } internal class TrieSegmentKeyComparer : IItemComparer<char, TrieSegment> { public int Compare(char c, TrieSegment t) { return ((int)c) - ((int)t.FirstChar); } } internal class TrieSegment { static readonly TrieSegmentKeyComparer SegKeyComparer = new TrieSegmentKeyComparer(); static readonly TrieSegmentComparer SegComparer = new TrieSegmentComparer(); SortedBuffer<TrieSegment, TrieSegmentComparer> children; QueryBranch data; TrieSegment parent; // segment's parent char segmentFirstChar; // this segment's first character string segmentTail; // this segment's tail int segmentLength; internal TrieSegment() : this(char.MinValue) { } internal TrieSegment(char firstChar) : this(firstChar, string.Empty) { } internal TrieSegment(char firstChar, string segmentTail) { Fx.Assert(null != segmentTail, ""); this.SetSegment(firstChar, segmentTail); this.children = new SortedBuffer<TrieSegment, TrieSegmentComparer>(SegComparer); } internal TrieSegment(string sourceSegment, int offset, int length) { Fx.Assert(null != sourceSegment && length > 0, ""); this.SetSegmentString(sourceSegment, offset, length); this.children = new SortedBuffer<TrieSegment, TrieSegmentComparer>(SegComparer); } internal bool CanMerge { get { return (null == this.data && 1 == this.children.Count); } } internal bool CanPrune { get { return (null == this.data && 0 == this.children.Count); } } #if NO internal int ChildCount { get { return this.children.Count; } } #endif internal void CollectXPathFilters(ICollection<MessageFilter> filters) { if (this.data != null) { (this.data).Branch.CollectXPathFilters(filters); } for (int i = 0; i < this.children.Count; ++i) { this.children[i].CollectXPathFilters(filters); } } internal QueryBranch Data { get { return this.data; } set { this.data = value; } } internal char FirstChar { get { return this.segmentFirstChar; } } internal bool HasChildren { get { return (this.children.Count > 0); } } internal int Length { get { //return (this.segmentFirstChar == char.MinValue) ? 0 : this.segmentTail.Length + 1; return this.segmentLength; } } #if NO internal string Tail { get { return this.segmentTail; } } #endif internal TrieSegment AddChild(TrieSegment segment) { Fx.Assert(null != segment, ""); this.children.Insert(segment); segment.parent = this; return segment; } #if NO internal TrieSegment[] CopyChildren() { return this.children.ToArray(); } #endif internal int FindDivergence(string compareString, int offset, int length) { Fx.Assert(null != compareString && length > 0, ""); if (compareString[offset] != this.segmentFirstChar) { return 0; } --length; ++offset; int charCount = (length <= this.segmentTail.Length) ? length : this.segmentTail.Length; for (int iSegment = 0, iCompare = offset; iSegment < charCount; ++iSegment, ++iCompare) { if (compareString[iCompare] != this.segmentTail[iSegment]) { return iSegment + 1; } } if (length < this.segmentTail.Length) { return length + 1; } return -1; } internal TrieSegment GetChild(int index) { Fx.Assert(this.HasChildren, ""); return this.children[index]; } /// <summary> /// Return the index of the child such that matchString == the string segment stored at that child /// i.e. matchString[0] == child.segmentFirstChar and matchString[1 -> length] == child.segmentTail[0 -> length] /// </summary> internal int GetChildPosition(string matchString, int offset, int length) { Fx.Assert(null != matchString, ""); if (this.HasChildren) { char matchChar = matchString[offset]; int tailLength = length - 1; int tailOffset = offset + 1; int index = this.children.IndexOfKey(matchChar, SegKeyComparer); if (index >= 0) { TrieSegment child = this.children[index]; if (tailLength >= child.segmentTail.Length && (0 == child.segmentTail.Length || 0 == string.CompareOrdinal(matchString, tailOffset, child.segmentTail, 0, child.segmentTail.Length))) { return index; } } } return -1; } /// <summary> /// Return the index of the child such that child.segmentFirstChar == ch /// </summary> internal int GetChildPosition(char ch) { return this.children.IndexOfKey(ch, SegKeyComparer); } internal int IndexOf(TrieSegment segment) { return this.children.IndexOf(segment); } internal void MergeChild(TrieSegment segment) { int childIndex = this.IndexOf(segment); if (childIndex > -1) { this.MergeChild(childIndex); } } /// <summary> /// If the child node has no data associated with it and but one child of its own, it can be /// merged with the child, reducing the path by 1 /// </summary> internal void MergeChild(int childIndex) { Fx.Assert(this.HasChildren, ""); TrieSegment child = this.children[childIndex]; if (child.CanMerge) { TrieSegment grandchild = child.children[0]; StringBuilder newTail = new StringBuilder(); newTail.Append(child.segmentTail); newTail.Append(grandchild.segmentFirstChar); newTail.Append(grandchild.segmentTail); grandchild.SetSegment(child.segmentFirstChar, newTail.ToString()); grandchild.parent = this; this.children.Exchange(child, grandchild); child.parent = null; } } internal void Remove() { if (null != this.parent) { this.parent.RemoveChild(this); } } /// <summary> /// Remove the child == segment, and prune the tree /// </summary> void RemoveChild(TrieSegment segment) { Fx.Assert(null != segment, ""); int childIndex = this.IndexOf(segment); if (childIndex >= 0) { this.RemoveChild(childIndex, true); } } /// <summary> /// Remove the child at index childIndex. /// If fixupTree is true, traverse back up the tree, removing prunable nodes or merging mergable nodes /// as appropriate /// </summary> internal void RemoveChild(int childIndex, bool fixupTree) { Fx.Assert(this.HasChildren && childIndex >= 0, ""); TrieSegment child = this.children[childIndex]; child.parent = null; this.children.RemoveAt(childIndex); if (0 == this.children.Count) { if (fixupTree && this.CanPrune) { this.Remove(); } } else { if (fixupTree && this.CanMerge && null != this.parent) { this.parent.MergeChild(this); } } } void SetSegment(char firstChar, string segmentTail) { this.segmentFirstChar = firstChar; this.segmentTail = segmentTail; this.segmentLength = firstChar == char.MinValue ? 0 : 1 + segmentTail.Length; } void SetSegmentString(string segmentString, int offset, int length) { this.segmentFirstChar = segmentString[offset]; if (length > 1) { this.segmentTail = segmentString.Substring(offset + 1, length - 1); } else { this.segmentTail = string.Empty; } this.segmentLength = length; } TrieSegment SplitAt(int charIndex) { Fx.Assert(charIndex > 0, ""); TrieSegment newSegment; if (1 == charIndex) { newSegment = new TrieSegment(this.segmentFirstChar); } else { Fx.Assert(this.segmentTail.Length > 0, ""); newSegment = new TrieSegment(this.segmentFirstChar, this.segmentTail.Substring(0, charIndex - 1)); } --charIndex; this.SetSegmentString(this.segmentTail, charIndex, this.segmentTail.Length - charIndex); newSegment.AddChild(this); return newSegment; } internal TrieSegment SplitChild(int childIndex, int charIndex) { Fx.Assert(this.HasChildren, ""); TrieSegment child = this.children[childIndex]; this.children.Remove(child); TrieSegment newChild = child.SplitAt(charIndex); this.children.Insert(newChild); newChild.parent = this; return newChild; } internal void Trim() { this.children.Trim(); for (int i = 0; i < this.children.Count; ++i) { this.children[i].Trim(); } } } internal struct TrieTraverser { int length; int offset; string prefix; TrieSegment rootSegment; TrieSegment segment; int segmentIndex; internal TrieTraverser(TrieSegment root, string prefix) { Fx.Assert(null != root && null != prefix, ""); this.prefix = prefix; this.rootSegment = root; this.segment = null; this.segmentIndex = -1; this.offset = 0; this.length = prefix.Length; } /// <summary> /// What length of segment that matched /// </summary> internal int Length { get { return this.length; } } /// <summary> /// The offset within the original segment where the matching part of the source string began /// </summary> internal int Offset { get { return this.offset; } } /// <summary> /// The traverser is currently at this segment node /// </summary> internal TrieSegment Segment { get { return this.segment; } set { Fx.Assert(null != value, ""); this.segment = value; } } internal int SegmentIndex { get { return this.segmentIndex; } } /// <summary> /// Traverse the prefix tree /// </summary> internal bool MoveNext() { if (null != this.segment) { int segmentLength = this.segment.Length; this.offset += segmentLength; this.length -= segmentLength; if (this.length > 0) { this.segmentIndex = this.segment.GetChildPosition(this.prefix, this.offset, this.length); if (this.segmentIndex > -1) { this.segment = this.segment.GetChild(this.segmentIndex); return true; } } else { this.segmentIndex = -1; } this.segment = null; } else if (null != this.rootSegment) { this.segment = this.rootSegment; this.rootSegment = null; return true; } return false; } /// <summary> /// Traverse the prefix tree.. using only the first character of each segment to jump from /// segment to segment /// </summary> internal bool MoveNextByFirstChar() { if (null != this.segment) { int segmentLength = this.segment.Length; this.offset += segmentLength; this.length -= segmentLength; if (this.length > 0) { this.segmentIndex = this.segment.GetChildPosition(this.prefix[this.offset]); if (this.segmentIndex > -1) { this.segment = this.segment.GetChild(this.segmentIndex); return true; } } else { this.segmentIndex = -1; } this.segment = null; } else if (null != this.rootSegment) { this.segment = this.rootSegment; this.rootSegment = null; return true; } return false; } } internal class Trie { TrieSegment root; // prefix tree root bool hasDescendants; internal Trie() { this.hasDescendants = false; } bool HasDescendants { get { //return (null != this.root && this.root.ChildCount > 0); return this.hasDescendants; } } #if NO internal bool IsEmpty { get { return (null == this.root || (null == this.root.Data && 0 == this.root.ChildCount)); } } #endif internal TrieSegment this[string prefix] { get { return this.Find(prefix); } } /// <summary> /// Tree root segment /// </summary> internal TrieSegment Root { get { this.EnsureRoot(); return this.root; } } internal TrieSegment Add(string newPrefix) { if (newPrefix.Length <= 0) { return this.Root; } this.EnsureRoot(); TrieTraverser traverser = new TrieTraverser(this.root, newPrefix); // struct TrieSegment parent; int indexDivergence; while (true) { parent = traverser.Segment; if (traverser.MoveNextByFirstChar()) { // There is a child segment that starts with the same character as the remainder of newPrefix // We have a shared segment // How much does newPrefix share with the current segment? Find the point at which they diverge if (null != parent && -1 != (indexDivergence = traverser.Segment.FindDivergence(newPrefix, traverser.Offset, traverser.Length))) { // Segments diverge at character # 'indexDivergence'. newPrefix will share the segment upto // that character. Beyond that character, we will now have 2 child segments: // - one for the portion of the current segment that diverged // - one for the portion of the new segment that diverged // Split the current segment into a shared part and a child containing the remainder of the segment.. traverser.Segment = parent.SplitChild(traverser.SegmentIndex, indexDivergence); } } else { if (traverser.Length <= 0) { // The entire new prefix has been added to the tree break; } // No existing segment to share. Add a new one traverser.Segment = parent.AddChild(new TrieSegment(newPrefix, traverser.Offset, traverser.Length)); } } this.hasDescendants = true; return parent; } void EnsureRoot() { if (null == this.root) { this.root = new TrieSegment(); } } TrieSegment Find(string prefix) { Fx.Assert(null != prefix, ""); if (0 == prefix.Length) { return this.Root; } if (!this.HasDescendants) { return null; } TrieTraverser traverser = new TrieTraverser(this.root, prefix); // struct TrieSegment foundSegment = null; while (traverser.MoveNext()) { foundSegment = traverser.Segment; } if (traverser.Length > 0) { // We haven't used up the entire prefix in this search. Clearly, we didn't find the matching node return null; } return foundSegment; } void PruneRoot() { if (null != this.root && this.root.CanPrune) { this.root = null; } } internal void Remove(string segment) { Fx.Assert(null != segment, ""); TrieSegment trieSegment = this[segment]; if (null == trieSegment) { return; } if (trieSegment.HasChildren) { trieSegment.Data = null; return; } if (trieSegment == this.root) { // Remove the entire tree! this.root = null; this.hasDescendants = false; return; } trieSegment.Remove(); this.PruneRoot(); } internal void Trim() { this.root.Trim(); } } internal class StringPrefixOpcode : LiteralRelationOpcode { string literal; internal StringPrefixOpcode(string literal) : base(OpcodeID.StringPrefix) { Fx.Assert(null != literal, ""); this.literal = literal; } #if NO internal override ValueDataType DataType { get { return ValueDataType.String; } } #endif internal override object Literal { get { return this.literal; } } internal override void Add(Opcode op) { StringPrefixOpcode prefixOp = op as StringPrefixOpcode; if (null == prefixOp) { base.Add(op); return; } Fx.Assert(null != this.prev, ""); StringPrefixBranchOpcode branch = new StringPrefixBranchOpcode(); this.prev.Replace(this, branch); branch.Add(this); branch.Add(prefixOp); } internal override bool Equals(Opcode op) { if (base.Equals(op)) { StringPrefixOpcode prefixOp = (StringPrefixOpcode)op; return (prefixOp.literal == this.literal); } return false; } internal override Opcode Eval(ProcessingContext context) { StackFrame arg = context.TopArg; if (1 == arg.Count) { Fx.Assert(context.Values[arg.basePtr].IsType(ValueDataType.String), ""); string target = context.Values[arg.basePtr].String; context.Values[arg.basePtr].Boolean = target.StartsWith(this.literal, StringComparison.Ordinal); } else { for (int i = arg.basePtr; i <= arg.endPtr; ++i) { Fx.Assert(context.Values[i].IsType(ValueDataType.String), ""); string target = context.Values[i].String; context.Values[i].Boolean = target.StartsWith(this.literal, StringComparison.Ordinal); } } return this.next; } } internal class TrieBranchIndex : QueryBranchIndex { int count; Trie trie; internal TrieBranchIndex() { this.count = 0; this.trie = new Trie(); } internal override int Count { get { return this.count; } } internal override QueryBranch this[object key] { get { TrieSegment segment = this.trie[(string)key]; if (null != segment) { return segment.Data; } return null; } set { Fx.Assert(null != key, ""); TrieSegment segment = this.trie.Add((string)key); Fx.Assert(null != segment, ""); this.count++; segment.Data = value; } } internal override void CollectXPathFilters(ICollection<MessageFilter> filters) { this.trie.Root.CollectXPathFilters(filters); } #if NO internal override IEnumerator GetEnumerator() { //return new TrieBreadthFirstEnum(this.trie); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException("TODO")); } #endif void Match(int valIndex, string segment, QueryBranchResultSet results) { TrieTraverser traverser = new TrieTraverser(this.trie.Root, segment); while (traverser.MoveNext()) { object segmentData = traverser.Segment.Data; if (null != segmentData) { results.Add((QueryBranch)segmentData, valIndex); } } } internal override void Match(int valIndex, ref Value val, QueryBranchResultSet results) { if (ValueDataType.Sequence == val.Type) { NodeSequence sequence = val.Sequence; for (int i = 0; i < sequence.Count; ++i) { this.Match(valIndex, sequence.Items[i].StringValue(), results); } } else { this.Match(valIndex, val.String, results); } } internal override void Remove(object key) { this.trie.Remove((string)key); this.count--; } internal override void Trim() { this.trie.Trim(); } } internal class StringPrefixBranchOpcode : QueryConditionalBranchOpcode { internal StringPrefixBranchOpcode() : base(OpcodeID.StringPrefixBranch, new TrieBranchIndex()) { } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - [email protected]) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.6.10. Information issued in response to a data query pdu or a set data pdu is communicated using a data pdu. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class DataPdu : SimulationManagementFamilyPdu, IEquatable<DataPdu> { /// <summary> /// ID of request /// </summary> private uint _requestID; /// <summary> /// padding /// </summary> private uint _padding1; /// <summary> /// Number of fixed datum records /// </summary> private uint _numberOfFixedDatumRecords; /// <summary> /// Number of variable datum records /// </summary> private uint _numberOfVariableDatumRecords; /// <summary> /// variable length list of fixed datums /// </summary> private List<FixedDatum> _fixedDatums = new List<FixedDatum>(); /// <summary> /// variable length list of variable length datums /// </summary> private List<VariableDatum> _variableDatums = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="DataPdu"/> class. /// </summary> public DataPdu() { PduType = (byte)20; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(DataPdu left, DataPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(DataPdu left, DataPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 4; // this._requestID marshalSize += 4; // this._padding1 marshalSize += 4; // this._numberOfFixedDatumRecords marshalSize += 4; // this._numberOfVariableDatumRecords for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the ID of request /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(uint), ElementName = "padding1")] public uint Padding1 { get { return this._padding1; } set { this._padding1 = value; } } /// <summary> /// Gets or sets the Number of fixed datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfFixedDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfFixedDatumRecords")] public uint NumberOfFixedDatumRecords { get { return this._numberOfFixedDatumRecords; } set { this._numberOfFixedDatumRecords = value; } } /// <summary> /// Gets or sets the Number of variable datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getnumberOfVariableDatumRecords method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "numberOfVariableDatumRecords")] public uint NumberOfVariableDatumRecords { get { return this._numberOfVariableDatumRecords; } set { this._numberOfVariableDatumRecords = value; } } /// <summary> /// Gets the variable length list of fixed datums /// </summary> [XmlElement(ElementName = "fixedDatumsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatums { get { return this._fixedDatums; } } /// <summary> /// Gets the variable length list of variable length datums /// </summary> [XmlElement(ElementName = "variableDatumsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatums { get { return this._variableDatums; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedInt((uint)this._requestID); dos.WriteUnsignedInt((uint)this._padding1); dos.WriteUnsignedInt((uint)this._fixedDatums.Count); dos.WriteUnsignedInt((uint)this._variableDatums.Count); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._requestID = dis.ReadUnsignedInt(); this._padding1 = dis.ReadUnsignedInt(); this._numberOfFixedDatumRecords = dis.ReadUnsignedInt(); this._numberOfVariableDatumRecords = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.NumberOfFixedDatumRecords; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatums.Add(anX); } for (int idx = 0; idx < this.NumberOfVariableDatumRecords; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatums.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<DataPdu>"); base.Reflection(sb); try { sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("<padding1 type=\"uint\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>"); sb.AppendLine("<fixedDatums type=\"uint\">" + this._fixedDatums.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatums>"); sb.AppendLine("<variableDatums type=\"uint\">" + this._variableDatums.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatums>"); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { sb.AppendLine("<fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { sb.AppendLine("<variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</DataPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as DataPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(DataPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._requestID != obj._requestID) { ivarsEqual = false; } if (this._padding1 != obj._padding1) { ivarsEqual = false; } if (this._numberOfFixedDatumRecords != obj._numberOfFixedDatumRecords) { ivarsEqual = false; } if (this._numberOfVariableDatumRecords != obj._numberOfVariableDatumRecords) { ivarsEqual = false; } if (this._fixedDatums.Count != obj._fixedDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { if (!this._fixedDatums[idx].Equals(obj._fixedDatums[idx])) { ivarsEqual = false; } } } if (this._variableDatums.Count != obj._variableDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { if (!this._variableDatums[idx].Equals(obj._variableDatums[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); result = GenerateHash(result) ^ this._padding1.GetHashCode(); result = GenerateHash(result) ^ this._numberOfFixedDatumRecords.GetHashCode(); result = GenerateHash(result) ^ this._numberOfVariableDatumRecords.GetHashCode(); if (this._fixedDatums.Count > 0) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatums[idx].GetHashCode(); } } if (this._variableDatums.Count > 0) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { result = GenerateHash(result) ^ this._variableDatums[idx].GetHashCode(); } } 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.Collections.Generic; using System.IO; using Microsoft.Protocols.TestTools.StackSdk.Messages; using Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbTrans2QueryPathInformationFinal Response /// </summary> public class SmbTrans2QueryPathInformationFinalResponsePacket : SmbTransaction2FinalResponsePacket { #region Fields private TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Parameters trans2Parameters; private TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Data trans2Data; /// <summary> /// Indicates that client specifies the information it is requesting. Server return different data based on /// the client's request. /// </summary> protected QueryInformationLevel informationLevel; /// <summary> /// The size of SizeOfListInBytes field in trans2Data /// </summary> private const ushort sizeOfListInBytesLength = 4; #endregion #region Properties /// <summary> /// get or set the Trans2_Parameters:TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Parameters /// </summary> public TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Parameters Trans2Parameters { get { return this.trans2Parameters; } set { this.trans2Parameters = value; } } /// <summary> /// get or set the Trans2_Data:TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Data /// </summary> public TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Data Trans2Data { get { return this.trans2Data; } set { this.trans2Data = value; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbTrans2QueryPathInformationFinalResponsePacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbTrans2QueryPathInformationFinalResponsePacket(byte[] data) : base(data) { } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> /// <param name="informationLevel">The response format is controlled by the value of the InformationLevel /// field provided in the request.</param> public SmbTrans2QueryPathInformationFinalResponsePacket(QueryInformationLevel informationLevel) { this.InitDefaultValue(); this.informationLevel = informationLevel; } /// <summary> /// Deep copy constructor. /// </summary> public SmbTrans2QueryPathInformationFinalResponsePacket( SmbTrans2QueryPathInformationFinalResponsePacket packet) : base(packet) { this.InitDefaultValue(); this.trans2Parameters.EaErrorOffset = packet.trans2Parameters.EaErrorOffset; this.trans2Data.Data = packet.trans2Data.Data; this.informationLevel = packet.informationLevel; } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbTrans2QueryPathInformationFinalResponsePacket(this); } /// <summary> /// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters /// </summary> protected override void EncodeTrans2Parameters() { this.smbData.Trans2_Parameters = CifsMessageUtils.ToBytes<TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Parameters>( this.trans2Parameters); } /// <summary> /// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data /// </summary> protected override void EncodeTrans2Data() { if (this.trans2Data.Data != null) { Type type = this.trans2Data.Data.GetType(); if (type == typeof(SMB_INFO_STANDARD_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_INFO_STANDARD_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_INFO_STANDARD_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_INFO_QUERY_EA_SIZE_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_INFO_QUERY_EA_SIZE_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_INFO_QUERY_EA_SIZE_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_INFO_QUERY_EAS_FROM_LIST_OF_TRANS2_QUERY_PATH_INFORMATION)) { SMB_INFO_QUERY_EAS_FROM_LIST_OF_TRANS2_QUERY_PATH_INFORMATION data = (SMB_INFO_QUERY_EAS_FROM_LIST_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data; if (data.ExtendedAttributeList != null) { this.smbData.Trans2_Data = new byte[data.SizeOfListInBytes]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<uint>(data.SizeOfListInBytes); foreach (SMB_FEA smbEa in data.ExtendedAttributeList) { channel.Write<SMB_FEA>(smbEa); } channel.EndWriteGroup(); } } } } else if (type == typeof(SMB_INFO_QUERY_ALL_EAS_OF_TRANS2_QUERY_PATH_INFORMATION)) { SMB_INFO_QUERY_ALL_EAS_OF_TRANS2_QUERY_PATH_INFORMATION easData = (SMB_INFO_QUERY_ALL_EAS_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data; if (easData.ExtendedAttributeList != null) { this.smbData.Trans2_Data = new byte[easData.SizeOfListInBytes]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<uint>(easData.SizeOfListInBytes); foreach (SMB_FEA smbEa in easData.ExtendedAttributeList) { channel.Write<SMB_FEA>(smbEa); } channel.EndWriteGroup(); } } } } else if (type == typeof(SMB_QUERY_FILE_BASIC_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_BASIC_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_BASIC_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_STANDARD_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_STANDARD_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_STANDARD_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_EA_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_EA_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_EA_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_ALL_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_ALL_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_ALL_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_ALT_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_ALT_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_ALT_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_STREAM_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_STREAM_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_STREAM_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else if (type == typeof(SMB_QUERY_FILE_COMPRESSION_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)) { this.smbData.Trans2_Data = CifsMessageUtils.ToBytes< SMB_QUERY_FILE_COMPRESSION_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>( (SMB_QUERY_FILE_COMPRESSION_INFO_OF_TRANS2_QUERY_PATH_INFORMATION)this.trans2Data.Data); } else { // Branch for negative testing. } } else { this.smbData.Trans2_Data = new byte[0]; } } /// <summary> /// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters. /// </summary> protected override void DecodeTrans2Parameters() { if (this.informationLevel != QueryInformationLevel.SMB_INFO_IS_NAME_VALID && this.smbData.Trans2_Parameters != null && this.smbData.Trans2_Parameters.Length > 0) { this.trans2Parameters = CifsMessageUtils.ToStuct< TRANS2_QUERY_PATH_INFORMATION_Response_Trans2_Parameters>(this.smbData.Trans2_Parameters); } } /// <summary> /// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] protected override void DecodeTrans2Data() { if (this.smbData.Trans2_Data != null && this.smbData.Trans2_Data.Length > 0) { switch (this.informationLevel) { case QueryInformationLevel.SMB_INFO_STANDARD: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_INFO_STANDARD_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_INFO_QUERY_EA_SIZE: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_INFO_QUERY_EA_SIZE_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST: if (this.smbData.Trans2_Data != null && this.smbData.Trans2_Data.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { SMB_INFO_QUERY_EAS_FROM_LIST_OF_TRANS2_QUERY_PATH_INFORMATION data = new SMB_INFO_QUERY_EAS_FROM_LIST_OF_TRANS2_QUERY_PATH_INFORMATION(); data.SizeOfListInBytes = channel.Read<uint>(); uint sizeOfListInBytes = data.SizeOfListInBytes - sizeOfListInBytesLength; List<SMB_FEA> attributeList = new List<SMB_FEA>(); while (sizeOfListInBytes > 0) { SMB_FEA smbEa = channel.Read<SMB_FEA>(); attributeList.Add(smbEa); sizeOfListInBytes -= (uint)(EA.SMB_EA_FIXED_SIZE + smbEa.AttributeName.Length + smbEa.ValueName.Length); } data.ExtendedAttributeList = attributeList.ToArray(); this.trans2Data.Data = data; } } } break; case QueryInformationLevel.SMB_INFO_QUERY_ALL_EAS: if (this.smbData.Trans2_Data != null && this.smbData.Trans2_Data.Length > 0) { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { SMB_INFO_QUERY_ALL_EAS_OF_TRANS2_QUERY_PATH_INFORMATION easData = new SMB_INFO_QUERY_ALL_EAS_OF_TRANS2_QUERY_PATH_INFORMATION(); easData.SizeOfListInBytes = channel.Read<uint>(); uint sizeOfList = easData.SizeOfListInBytes - sizeOfListInBytesLength; List<SMB_FEA> eaList = new List<SMB_FEA>(); while (sizeOfList > 0) { SMB_FEA smbEa = channel.Read<SMB_FEA>(); eaList.Add(smbEa); sizeOfList -= (uint)(EA.SMB_EA_FIXED_SIZE + smbEa.AttributeName.Length + smbEa.ValueName.Length); } easData.ExtendedAttributeList = eaList.ToArray(); this.trans2Data.Data = easData; } } } break; case QueryInformationLevel.SMB_QUERY_FILE_BASIC_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_BASIC_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_STANDARD_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_STANDARD_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_EA_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_EA_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_NAME_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_ALL_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_ALL_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_ALT_NAME_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_ALT_NAME_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_STREAM_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_STREAM_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; case QueryInformationLevel.SMB_QUERY_FILE_COMPRESSION_INFO: this.trans2Data.Data = CifsMessageUtils.ToStuct< SMB_QUERY_FILE_COMPRESSION_INFO_OF_TRANS2_QUERY_PATH_INFORMATION>(this.smbData.Trans2_Data); break; } } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #if LEGACYTELEMETRY using System; using System.Collections.Generic; using System.Diagnostics; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Language; using System.Threading; using System.Threading.Tasks; namespace Microsoft.PowerShell.Telemetry.Internal { /// <summary> /// </summary> [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public static class TelemetryAPI { #region Public API /// <summary> /// Public API to expose Telemetry in PowerShell /// Provide meaningful message. Ex: PSCONSOLE_START, PSRUNSPACE_START /// arguments are of anonymous type. Ex: new { PSVersion = "5.0", PSRemotingProtocolVersion = "2.2"} /// </summary> public static void TraceMessage<T>(string message, T arguments) { TelemetryWrapper.TraceMessage(message, arguments); } #endregion private static int s_anyPowerShellSessionOpen; private static DateTime s_sessionStartTime; private enum HostIsInteractive { Unknown, Interactive, NonInteractive } /// <summary> /// Called either after opening a runspace (the default), or by the host application. /// </summary> public static void ReportStartupTelemetry(IHostProvidesTelemetryData ihptd) { // Avoid reporting startup more than once, except if we report "exited" and // another runspace gets opened. if (Interlocked.CompareExchange(ref s_anyPowerShellSessionOpen, 1, 0) == 1) return; bool is32Bit = !Environment.Is64BitProcess; var psversion = PSVersionInfo.PSVersion.ToString(); var hostName = Process.GetCurrentProcess().ProcessName; if (ihptd != null) { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = ihptd.HostIsInteractive ? HostIsInteractive.Interactive : HostIsInteractive.NonInteractive, ProfileLoadTime = ihptd.ProfileLoadTimeInMS, ReadyForInputTime = ihptd.ReadyForInputTimeInMS, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } else { TelemetryWrapper.TraceMessage("PSHostStart", new { Interactive = HostIsInteractive.Unknown, ProfileLoadTime = 0, ReadyForInputTime = 0, Is32Bit = is32Bit, PSVersion = psversion, ProcessName = hostName, }); } s_sessionStartTime = DateTime.Now; } /// <summary> /// Called after there are no more open runspaces. In some host applications, this could /// report multiple exits. /// </summary> public static void ReportExitTelemetry(IHostProvidesTelemetryData ihptd) { TelemetryWrapper.TraceMessage("PSHostStop", new { InteractiveCommandCount = ihptd != null ? ihptd.InteractiveCommandCount : 0, TabCompletionTimes = s_tabCompletionTimes, TabCompletionCounts = s_tabCompletionCounts, TabCompletionResultCounts = s_tabCompletionResultCounts, SessionTime = (DateTime.Now - s_sessionStartTime).TotalMilliseconds }); // In case a host opens another runspace, we will want another PSHostStart event, // so reset our flag here to allow that event to fire. s_anyPowerShellSessionOpen = 0; } /// <summary> /// Report Get-Help requests, how many results are returned, and how long it took. /// </summary> internal static void ReportGetHelpTelemetry(string name, int topicsFound, long timeInMS, bool updatedHelp) { TelemetryWrapper.TraceMessage("PSHelpRequest", new { TopicCount = topicsFound, TimeInMS = timeInMS, RanUpdateHelp = updatedHelp, HelpTopic = name, }); } /// <summary> /// Report when Get-Command fails to find something. /// </summary> internal static void ReportGetCommandFailed(string[] name, long timeInMS) { TelemetryWrapper.TraceMessage("PSGetCommandFailed", new { TimeInMS = timeInMS, CommandNames = name }); } private static long[] s_tabCompletionTimes = new long[(int)CompletionResultType.DynamicKeyword + 1]; private static int[] s_tabCompletionCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; private static int[] s_tabCompletionResultCounts = new int[(int)CompletionResultType.DynamicKeyword + 1]; internal static void ReportTabCompletionTelemetry(long elapsedMilliseconds, int count, CompletionResultType completionResultType) { // We'll collect some general statistics. int idx = (int)completionResultType; if (idx >= 0 && idx <= (int)CompletionResultType.DynamicKeyword) { s_tabCompletionTimes[idx] += elapsedMilliseconds; s_tabCompletionCounts[idx]++; s_tabCompletionResultCounts[idx] += count; } // Also write an event for any slow tab completion (> 250ms). if (elapsedMilliseconds > 250) { TelemetryWrapper.TraceMessage("PSSlowTabCompletion", new { Time = elapsedMilliseconds, Count = count, Type = completionResultType, }); } } /// <summary> /// Report that a module was loaded, but only do so for modules that *might* be authored by Microsoft. We can't /// be 100% certain, but we'll ignore non-Microsoft module names when looking at any data, so it's best to /// at least attempt avoiding collecting data we'll ignore. /// </summary> internal static void ReportModuleLoad(PSModuleInfo foundModule) { var modulePath = foundModule.Path; var companyName = foundModule.CompanyName; bool couldBeMicrosoftModule = (modulePath != null && (modulePath.StartsWith(Utils.DefaultPowerShellAppBase, StringComparison.OrdinalIgnoreCase) || // The following covers both 64 and 32 bit Program Files by assuming 32bit is just ...\Program Files + " (x86)" modulePath.StartsWith(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), StringComparison.OrdinalIgnoreCase))) || (companyName != null && foundModule.CompanyName.StartsWith("Microsoft", StringComparison.OrdinalIgnoreCase)); if (couldBeMicrosoftModule) { TelemetryWrapper.TraceMessage("PSImportModule", new { ModuleName = foundModule.Name, Version = foundModule.Version.ToString() }); } } /// <summary> /// Report that a new local session (runspace) is created. /// </summary> internal static void ReportLocalSessionCreated( System.Management.Automation.Runspaces.InitialSessionState iss, System.Management.Automation.Host.TranscriptionData transcriptionData) { bool isConstrained = (iss != null) && (iss.DefaultCommandVisibility != SessionStateEntryVisibility.Public) && (iss.LanguageMode != PSLanguageMode.FullLanguage); bool isTranscripting = (transcriptionData != null) && (transcriptionData.SystemTranscript != null); TelemetryWrapper.TraceMessage("PSNewLocalSession", new { Constrained = isConstrained, Transcripting = isTranscripting }); } private enum RemoteSessionType { Unknown, LocalProcess, WinRMRemote, HyperVRemote, ContainerRemote } private enum RemoteConfigurationType { Unknown, PSDefault, PSWorkflow, ServerManagerWorkflow, Custom } /// <summary> /// Report that a new remote session (runspace) is created. /// </summary> internal static void ReportRemoteSessionCreated( System.Management.Automation.Runspaces.RunspaceConnectionInfo connectionInfo) { RemoteSessionType sessionType = RemoteSessionType.Unknown; RemoteConfigurationType configurationType = RemoteConfigurationType.Unknown; if (connectionInfo is System.Management.Automation.Runspaces.NewProcessConnectionInfo) { sessionType = RemoteSessionType.LocalProcess; configurationType = RemoteConfigurationType.PSDefault; } else { System.Management.Automation.Runspaces.WSManConnectionInfo wsManConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.WSManConnectionInfo; if (wsManConnectionInfo != null) { sessionType = RemoteSessionType.WinRMRemote; // Parse configuration name from ShellUri: // ShellUri = 'http://schemas.microsoft.com/powershell/Microsoft.PowerShell' // ConfigName = 'Microsoft.PowerShell' string configurationName = wsManConnectionInfo.ShellUri; if (!string.IsNullOrEmpty(configurationName)) { int index = configurationName.LastIndexOf('/'); if (index > -1) { configurationName = configurationName.Substring(index + 1); } } configurationType = GetConfigurationTypefromName(configurationName); } else { System.Management.Automation.Runspaces.VMConnectionInfo vmConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.VMConnectionInfo; if (vmConnectionInfo != null) { sessionType = RemoteSessionType.HyperVRemote; configurationType = GetConfigurationTypefromName(vmConnectionInfo.ConfigurationName); } else { System.Management.Automation.Runspaces.ContainerConnectionInfo containerConnectionInfo = connectionInfo as System.Management.Automation.Runspaces.ContainerConnectionInfo; if (containerConnectionInfo != null) { sessionType = RemoteSessionType.ContainerRemote; configurationType = GetConfigurationTypefromName( (containerConnectionInfo.ContainerProc != null) ? containerConnectionInfo.ContainerProc.ConfigurationName : string.Empty); } } } } TelemetryWrapper.TraceMessage("PSNewRemoteSession", new { Type = sessionType, Configuration = configurationType }); } private static RemoteConfigurationType GetConfigurationTypefromName(string name) { string configName = (name != null) ? name.Trim() : string.Empty; if (string.IsNullOrEmpty(configName) || configName.Equals("microsoft.powershell", StringComparison.OrdinalIgnoreCase) || configName.Equals("microsoft.powershell32", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.PSDefault; } else if (configName.Equals("microsoft.powershell.workflow", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.PSWorkflow; } else if (configName.Equals("microsoft.windows.servermanagerworkflows", StringComparison.OrdinalIgnoreCase)) { return RemoteConfigurationType.ServerManagerWorkflow; } else { return RemoteConfigurationType.Custom; } } private enum ScriptFileType { None = 0, Ps1 = 1, Psd1 = 2, Psm1 = 3, Other = 4, } private static readonly int s_promptHashCode = "prompt".GetHashCode(); /// <summary> /// Report some telemetry about the scripts that are run. /// </summary> internal static void ReportScriptTelemetry(Ast ast, bool dotSourced, long compileTimeInMS) { if (ast.Parent != null || !TelemetryWrapper.IsEnabled) return; Task.Run(() => { var extent = ast.Extent; var text = extent.Text; var hash = text.GetHashCode(); // Ignore 'prompt' so we don't generate an event for every 'prompt' that is invoked. // (We really should only create 'prompt' once, but we don't. if (hash == s_promptHashCode) return; var visitor = new ScriptBlockTelemetry(); ast.Visit(visitor); var scriptFileType = ScriptFileType.None; var fileName = extent.File; if (fileName != null) { var ext = System.IO.Path.GetExtension(fileName); if (".ps1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Ps1; } else if (".psd1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psd1; } else if (".psm1".Equals(ext, StringComparison.OrdinalIgnoreCase)) { scriptFileType = ScriptFileType.Psm1; } else { // Reachable? scriptFileType = ScriptFileType.Other; } } TelemetryWrapper.TraceMessage("PSScriptDetails", new { Hash = hash, IsDotSourced = dotSourced, ScriptFileType = scriptFileType, Length = text.Length, LineCount = extent.EndLineNumber - extent.StartLineNumber, CompileTimeInMS = compileTimeInMS, StatementCount = visitor.StatementCount, CountOfCommands = visitor.CountOfCommands, CountOfDotSourcedCommands = visitor.CountOfDotSourcedCommands, MaxArrayLength = visitor.MaxArraySize, ArrayLiteralCount = visitor.ArrayLiteralCount, ArrayLiteralCumulativeSize = visitor.ArrayLiteralCumulativeSize, MaxStringLength = visitor.MaxStringSize, StringLiteralCount = visitor.StringLiteralCount, StringLiteralCumulativeSize = visitor.StringLiteralCumulativeSize, MaxPipelineDepth = visitor.MaxPipelineDepth, PipelineCount = visitor.PipelineCount, FunctionCount = visitor.FunctionCount, ScriptBlockCount = visitor.ScriptBlockCount, ClassCount = visitor.ClassCount, EnumCount = visitor.EnumCount, CommandsCalled = visitor.CommandsCalled, }); }); } } internal class ScriptBlockTelemetry : AstVisitor2 { internal ScriptBlockTelemetry() { CommandsCalled = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); } internal Dictionary<string, int> CommandsCalled { get; private set; } internal int CountOfCommands { get; private set; } internal int CountOfDotSourcedCommands { get; private set; } public override AstVisitAction VisitCommand(CommandAst commandAst) { CountOfCommands++; var commandName = commandAst.GetCommandName(); if (commandName != null) { int commandCount; CommandsCalled.TryGetValue(commandName, out commandCount); CommandsCalled[commandName] = commandCount + 1; } if (commandAst.InvocationOperator == TokenKind.Dot) CountOfDotSourcedCommands++; return AstVisitAction.Continue; } internal int MaxStringSize { get; private set; } internal int StringLiteralCount { get; private set; } internal int StringLiteralCumulativeSize { get; private set; } public override AstVisitAction VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { var stringSize = stringConstantExpressionAst.Value.Length; StringLiteralCount += 1; StringLiteralCumulativeSize += stringSize; MaxStringSize = Math.Max(MaxStringSize, stringSize); return AstVisitAction.Continue; } public override AstVisitAction VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { var stringSize = expandableStringExpressionAst.Value.Length; StringLiteralCount += 1; StringLiteralCumulativeSize += stringSize; MaxStringSize = Math.Max(MaxStringSize, stringSize); return AstVisitAction.Continue; } internal int MaxArraySize { get; private set; } internal int ArrayLiteralCount { get; private set; } internal int ArrayLiteralCumulativeSize { get; private set; } public override AstVisitAction VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { var elementCount = arrayLiteralAst.Elements.Count; ArrayLiteralCount += 1; ArrayLiteralCumulativeSize += elementCount; MaxArraySize = Math.Max(MaxArraySize, elementCount); return AstVisitAction.Continue; } internal int StatementCount { get; private set; } public override AstVisitAction VisitBlockStatement(BlockStatementAst blockStatementAst) { StatementCount += blockStatementAst.Body.Statements.Count; return AstVisitAction.Continue; } public override AstVisitAction VisitNamedBlock(NamedBlockAst namedBlockAst) { StatementCount += namedBlockAst.Statements.Count; return AstVisitAction.Continue; } internal int FunctionCount { get; private set; } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { FunctionCount += 1; return AstVisitAction.Continue; } internal int ScriptBlockCount { get; private set; } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { ScriptBlockCount += 1; return AstVisitAction.Continue; } internal int MaxPipelineDepth { get; private set; } internal int PipelineCount { get; private set; } public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) { MaxPipelineDepth = Math.Max(MaxPipelineDepth, pipelineAst.PipelineElements.Count); PipelineCount += 1; return AstVisitAction.Continue; } internal int ClassCount { get; private set; } internal int EnumCount { get; private set; } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { if (typeDefinitionAst.IsClass) ClassCount += 1; else if (typeDefinitionAst.IsEnum) EnumCount += 1; return AstVisitAction.Continue; } } /// <summary> /// If implemented by the host, the host should call <see cref="TelemetryAPI.ReportStartupTelemetry"/> and <see cref="TelemetryAPI.ReportExitTelemetry"/> /// and track the data defined by this interface. /// </summary> public interface IHostProvidesTelemetryData { /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> bool HostIsInteractive { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> double ProfileLoadTimeInMS { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> double ReadyForInputTimeInMS { get; } /// <summary>A host sets this property as appropriate - used when reporting telemetry.</summary> int InteractiveCommandCount { get; } } } #endif
//----------------------------------------------------------------------------- // Filename: ByteBuffer.cs // // Description: Provides some useful methods for working with byte[] buffers. // // History: // 04 May 2006 Aaron Clauson Created. //----------------------------------------------------------------------------- using System; using System.IO; using System.Text; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.Sys { public class ByteBufferInfo { /// <summary> /// Searches a buffer for a string up until a specified end string. /// </summary> /// <param name="buffer">The byte array to search for an instance of the specified string.</param> /// <param name="startPosition">The position in the array that the search should be started from.</param> /// <param name="endPosition">An index that if reached indicates the search should be halted.</param> /// <param name="find">The string that is being searched for.</param> /// <param name="end">If the end string is found the search is halted and a negative result returned.</param> /// <returns>The start position in the buffer of the requested string or -1 if not found.</returns> public static int GetStringPosition(byte[] buffer, int startPosition, int endPosition, string find, string end) { if(buffer == null || buffer.Length == 0 || find == null) { return -1; } else { byte[] findArray = Encoding.UTF8.GetBytes(find); byte[] endArray = (end != null) ? Encoding.UTF8.GetBytes(end) : null; int findPosn = 0; int endPosn = 0; for (int index = startPosition; index < endPosition; index++) { if(buffer[index] == findArray[findPosn]) { findPosn++; } else { findPosn = 0; } if(endArray != null && buffer[index] == endArray[endPosn]) { endPosn++; } else { endPosn = 0; } if(findPosn == findArray.Length) { return index - findArray.Length + 1; } else if(endArray != null && endPosn == endArray.Length) { return -1; } } return -1; } } public static bool HasString(byte[] buffer, int startPosition, int endPosition, string find, string end) { return GetStringPosition(buffer, startPosition, endPosition, find, end) != -1; } #region Unit testing. #if UNITTEST [TestFixture] public class SIPURIUnitTest { [TestFixtureSetUp] public void Init() { } [TestFixtureTearDown] public void Dispose() { } [Test] public void SampleTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); Assert.IsTrue(true, "True was false."); } [Test] public void HasStringUnitTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); byte[] sample = Encoding.ASCII.GetBytes("The quick brown fox jumped over..."); bool hasFox = ByteBufferInfo.HasString(sample, 0, Int32.MaxValue, "fox", null); Assert.IsTrue(hasFox, "The string was not found in the buffer."); } [Test] public void NotBeforeEndUnitTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); byte[] sample = Encoding.ASCII.GetBytes("The quick brown fox jumped over..."); bool hasFox = ByteBufferInfo.HasString(sample, 0, Int32.MaxValue, "fox", "brown"); Assert.IsTrue(!hasFox, "The string was not found in the buffer."); } [Test] public void GetStringIndexUnitTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); string sipMsg = "REGISTER sip:Blue Face SIP/2.0\r\n" + "Via: SIP/2.0/UDP 127.0.0.1:1720;branch=z9hG4bKlgnUQcaywCOaPcXR\r\n" + "Max-Forwards: 70\r\n" + "User-Agent: PA168S\r\n" + "From: \"user\" <sip:user@Blue Face>;tag=81swjAV7dHG1yjd5\r\n" + "To: \"user\" <sip:user@Blue Face>\r\n" + "Call-ID: [email protected]\r\n" + "CSeq: 15754 REGISTER\r\n" + "Contact: <sip:[email protected]:1720>\r\n" + "Expires: 30\r\n" + "Content-Length: 0\r\n\r\n"; byte[] sample = Encoding.ASCII.GetBytes(sipMsg); int endOfMsgIndex = ByteBufferInfo.GetStringPosition(sample, 0, Int32.MaxValue, "\r\n\r\n", null); Assert.IsTrue(endOfMsgIndex == sample.Length - 4, "The string position was not correctly found in the buffer."); } [Test] public void GetStringIndexSIPInviteUnitTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); string sipMsg = "INVITE sip:[email protected]:5060;TCID-0 SIP/2.0\r\n" + "From: UNAVAILABLE<sip:[email protected]:5060>;tag=c0a83dfe-13c4-26bf01-975a21d0-2d8a\r\n" + "To: <sip:[email protected]:5060>\r\n" + "Call-ID: [email protected]\r\n" + "CSeq: 1 INVITE\r\n" + "Via: SIP/2.0/UDP 86.9.84.23:5060;branch=z9hG4bK-26bf01-975a21d0-1ffb\r\n" + "Max-Forwards: 70\r\n" + "User-Agent: TA612V-V1.2_54\r\n" + "Supported: timer,replaces\r\n" + "Contact: <sip:[email protected]:5060>\r\n" + "Content-Type: application/SDP\r\n" + "Content-Length: 386\r\n" + "\r\n" + "v=0\r\n" + "o=b0000 613 888 IN IP4 88.8.88.88\r\n" + "s=SIP Call\r\n" + "c=IN IP4 88.8.88.88\r\n" + "t=0 0\r\n" + "m=audio 10000 RTP/AVP 0 101 18 100 101 2 103 8\r\n" + "a=fmtp:101 0-15\r\n" + "a=fmtp:18 annexb=no\r\n" + "a=sendrecv\r\n" + "a=rtpmap:0 PCMU/8000\r\n" + "a=rtpmap:101 telephone-event/8000\r\n" + "a=rtpmap:18 G729/8000\r\n" + "a=rtpmap:100 G726-16/8000\r\n" + "a=rtpmap:101 G726-24/8000\r\n" + "a=rtpmap:2 G726-32/8000\r\n" + "a=rtpmap:103 G726-40/8000\r\n" + "a=rtpmap:8 PCMA/8000"; byte[] sample = Encoding.ASCII.GetBytes(sipMsg); int endOfMsgIndex = ByteBufferInfo.GetStringPosition(sample, 0, Int32.MaxValue, "\r\n\r\n", null); Assert.IsTrue(endOfMsgIndex == sipMsg.IndexOf("\r\n\r\n"), "The string position was not correctly found in the buffer. Index found was " + endOfMsgIndex + ", should have been " + sipMsg.IndexOf("\r\n\r\n") + "."); } [Test] public void GetStringIndexNotFoundUnitTest() { Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); string sipMsg = "REGISTER sip:Blue Face SIP/2.0\r\n" + "Via: SIP/2.0/UDP 127.0.0.1:1720;branch=z9hG4bKlgnUQcaywCOaPcXR\r\n" + "Max-Forwards: 70\r\n" + "User-Agent: PA168S\r\n" + "From: \"user\" <sip:user@Blue Face>;tag=81swjAV7dHG1yjd5\r\n" + "To: \"user\" <sip:user@Blue Face>\r\n" + "Call-ID: [email protected]\r\n" + "CSeq: 15754 REGISTER\r\n" + "Contact: <sip:[email protected]:1720>\r\n" + "Expires: 30\r\n" + "Content-Length: 0\r\n"; byte[] sample = Encoding.ASCII.GetBytes(sipMsg); int endOfMsgIndex = ByteBufferInfo.GetStringPosition(sample, 0, Int32.MaxValue, "\r\n\r\n", null); Assert.IsTrue(endOfMsgIndex == -1, "The string position was not correctly found in the buffer."); } } #endif #endregion } }
/* * 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 CookComputing.XmlRpc; namespace XenAPI { /// <summary> /// The physical block devices through which hosts access SRs /// First published in XenServer 4.0. /// </summary> public partial class PBD : XenObject<PBD> { public PBD() { } public PBD(string uuid, XenRef<Host> host, XenRef<SR> SR, Dictionary<string, string> device_config, bool currently_attached, Dictionary<string, string> other_config) { this.uuid = uuid; this.host = host; this.SR = SR; this.device_config = device_config; this.currently_attached = currently_attached; this.other_config = other_config; } /// <summary> /// Creates a new PBD from a Proxy_PBD. /// </summary> /// <param name="proxy"></param> public PBD(Proxy_PBD proxy) { this.UpdateFromProxy(proxy); } public override void UpdateFrom(PBD update) { uuid = update.uuid; host = update.host; SR = update.SR; device_config = update.device_config; currently_attached = update.currently_attached; other_config = update.other_config; } internal void UpdateFromProxy(Proxy_PBD proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; host = proxy.host == null ? null : XenRef<Host>.Create(proxy.host); SR = proxy.SR == null ? null : XenRef<SR>.Create(proxy.SR); device_config = proxy.device_config == null ? null : Maps.convert_from_proxy_string_string(proxy.device_config); currently_attached = (bool)proxy.currently_attached; other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_PBD ToProxy() { Proxy_PBD result_ = new Proxy_PBD(); result_.uuid = (uuid != null) ? uuid : ""; result_.host = (host != null) ? host : ""; result_.SR = (SR != null) ? SR : ""; result_.device_config = Maps.convert_to_proxy_string_string(device_config); result_.currently_attached = currently_attached; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Creates a new PBD from a Hashtable. /// </summary> /// <param name="table"></param> public PBD(Hashtable table) { uuid = Marshalling.ParseString(table, "uuid"); host = Marshalling.ParseRef<Host>(table, "host"); SR = Marshalling.ParseRef<SR>(table, "SR"); device_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "device_config")); currently_attached = Marshalling.ParseBool(table, "currently_attached"); other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(PBD other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._host, other._host) && Helper.AreEqual2(this._SR, other._SR) && Helper.AreEqual2(this._device_config, other._device_config) && Helper.AreEqual2(this._currently_attached, other._currently_attached) && Helper.AreEqual2(this._other_config, other._other_config); } public override string SaveChanges(Session session, string opaqueRef, PBD server) { if (opaqueRef == null) { Proxy_PBD p = this.ToProxy(); return session.proxy.pbd_create(session.uuid, p).parse(); } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { PBD.set_other_config(session, opaqueRef, _other_config); } if (!Helper.AreEqual2(_device_config, server._device_config)) { PBD.set_device_config(session, opaqueRef, _device_config); } return null; } } /// <summary> /// Get a record containing the current state of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static PBD get_record(Session session, string _pbd) { return new PBD((Proxy_PBD)session.proxy.pbd_get_record(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Get a reference to the PBD 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<PBD> get_by_uuid(Session session, string _uuid) { return XenRef<PBD>.Create(session.proxy.pbd_get_by_uuid(session.uuid, (_uuid != null) ? _uuid : "").parse()); } /// <summary> /// Create a new PBD instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<PBD> create(Session session, PBD _record) { return XenRef<PBD>.Create(session.proxy.pbd_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Create a new PBD instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, PBD _record) { return XenRef<Task>.Create(session.proxy.async_pbd_create(session.uuid, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified PBD instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static void destroy(Session session, string _pbd) { session.proxy.pbd_destroy(session.uuid, (_pbd != null) ? _pbd : "").parse(); } /// <summary> /// Destroy the specified PBD instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static XenRef<Task> async_destroy(Session session, string _pbd) { return XenRef<Task>.Create(session.proxy.async_pbd_destroy(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Get the uuid field of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static string get_uuid(Session session, string _pbd) { return (string)session.proxy.pbd_get_uuid(session.uuid, (_pbd != null) ? _pbd : "").parse(); } /// <summary> /// Get the host field of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static XenRef<Host> get_host(Session session, string _pbd) { return XenRef<Host>.Create(session.proxy.pbd_get_host(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Get the SR field of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static XenRef<SR> get_SR(Session session, string _pbd) { return XenRef<SR>.Create(session.proxy.pbd_get_sr(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Get the device_config field of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static Dictionary<string, string> get_device_config(Session session, string _pbd) { return Maps.convert_from_proxy_string_string(session.proxy.pbd_get_device_config(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Get the currently_attached field of the given PBD. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static bool get_currently_attached(Session session, string _pbd) { return (bool)session.proxy.pbd_get_currently_attached(session.uuid, (_pbd != null) ? _pbd : "").parse(); } /// <summary> /// Get the other_config field of the given PBD. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static Dictionary<string, string> get_other_config(Session session, string _pbd) { return Maps.convert_from_proxy_string_string(session.proxy.pbd_get_other_config(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Set the other_config field of the given PBD. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _pbd, Dictionary<string, string> _other_config) { session.proxy.pbd_set_other_config(session.uuid, (_pbd != null) ? _pbd : "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given PBD. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</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 _pbd, string _key, string _value) { session.proxy.pbd_add_to_other_config(session.uuid, (_pbd != null) ? _pbd : "", (_key != null) ? _key : "", (_value != null) ? _value : "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given PBD. If the key is not in that Map, then do nothing. /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _pbd, string _key) { session.proxy.pbd_remove_from_other_config(session.uuid, (_pbd != null) ? _pbd : "", (_key != null) ? _key : "").parse(); } /// <summary> /// Activate the specified PBD, causing the referenced SR to be attached and scanned /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static void plug(Session session, string _pbd) { session.proxy.pbd_plug(session.uuid, (_pbd != null) ? _pbd : "").parse(); } /// <summary> /// Activate the specified PBD, causing the referenced SR to be attached and scanned /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static XenRef<Task> async_plug(Session session, string _pbd) { return XenRef<Task>.Create(session.proxy.async_pbd_plug(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Deactivate the specified PBD, causing the referenced SR to be detached and nolonger scanned /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static void unplug(Session session, string _pbd) { session.proxy.pbd_unplug(session.uuid, (_pbd != null) ? _pbd : "").parse(); } /// <summary> /// Deactivate the specified PBD, causing the referenced SR to be detached and nolonger scanned /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> public static XenRef<Task> async_unplug(Session session, string _pbd) { return XenRef<Task>.Create(session.proxy.async_pbd_unplug(session.uuid, (_pbd != null) ? _pbd : "").parse()); } /// <summary> /// Sets the PBD's device_config field /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> /// <param name="_value">The new value of the PBD's device_config</param> public static void set_device_config(Session session, string _pbd, Dictionary<string, string> _value) { session.proxy.pbd_set_device_config(session.uuid, (_pbd != null) ? _pbd : "", Maps.convert_to_proxy_string_string(_value)).parse(); } /// <summary> /// Sets the PBD's device_config field /// First published in XenServer 4.1. /// </summary> /// <param name="session">The session</param> /// <param name="_pbd">The opaque_ref of the given pbd</param> /// <param name="_value">The new value of the PBD's device_config</param> public static XenRef<Task> async_set_device_config(Session session, string _pbd, Dictionary<string, string> _value) { return XenRef<Task>.Create(session.proxy.async_pbd_set_device_config(session.uuid, (_pbd != null) ? _pbd : "", Maps.convert_to_proxy_string_string(_value)).parse()); } /// <summary> /// Return a list of all the PBDs known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<PBD>> get_all(Session session) { return XenRef<PBD>.Create(session.proxy.pbd_get_all(session.uuid).parse()); } /// <summary> /// Get all the PBD 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<PBD>, PBD> get_all_records(Session session) { return XenRef<PBD>.Create<Proxy_PBD>(session.proxy.pbd_get_all_records(session.uuid).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid; /// <summary> /// physical machine on which the pbd is available /// </summary> public virtual XenRef<Host> host { get { return _host; } set { if (!Helper.AreEqual(value, _host)) { _host = value; Changed = true; NotifyPropertyChanged("host"); } } } private XenRef<Host> _host; /// <summary> /// the storage repository that the pbd realises /// </summary> public virtual XenRef<SR> SR { get { return _SR; } set { if (!Helper.AreEqual(value, _SR)) { _SR = value; Changed = true; NotifyPropertyChanged("SR"); } } } private XenRef<SR> _SR; /// <summary> /// a config string to string map that is provided to the host's SR-backend-driver /// </summary> public virtual Dictionary<string, string> device_config { get { return _device_config; } set { if (!Helper.AreEqual(value, _device_config)) { _device_config = value; Changed = true; NotifyPropertyChanged("device_config"); } } } private Dictionary<string, string> _device_config; /// <summary> /// is the SR currently attached on this host? /// </summary> public virtual bool currently_attached { get { return _currently_attached; } set { if (!Helper.AreEqual(value, _currently_attached)) { _currently_attached = value; Changed = true; NotifyPropertyChanged("currently_attached"); } } } private bool _currently_attached; /// <summary> /// additional configuration /// First published in XenServer 4.1. /// </summary> public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config; } }
/* * 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 OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.CoreModules.World.LightShare; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using System; using System.Runtime.Remoting.Lifetime; using System.Threading; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.Api { [Serializable] public class LS_Api : MarshalByRefObject, ILS_Api, IScriptApi { internal IScriptEngine m_ScriptEngine; internal SceneObjectPart m_host; internal bool m_LSFunctionsEnabled = false; internal IScriptModuleComms m_comms = null; public void Initialize( IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item, WaitHandle coopSleepHandle) { m_ScriptEngine = scriptEngine; m_host = host; if (m_ScriptEngine.Config.GetBoolean("AllowLightShareFunctions", false)) m_LSFunctionsEnabled = true; m_comms = m_ScriptEngine.World.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) m_LSFunctionsEnabled = false; } public override Object InitializeLifetimeService() { ILease lease = (ILease)base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.FromMinutes(0); // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0); // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0); } return lease; } public Scene World { get { return m_ScriptEngine.World; } } /// <summary> /// Dumps an error message on the debug console. /// </summary> internal void LSShoutError(string message) { if (message.Length > 1023) message = message.Substring(0, 1023); World.SimChat(Utils.StringToBytes(message), ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, true); IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>(); wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message); } /// <summary> /// Get the current Windlight scene /// </summary> /// <returns>List of windlight parameters</returns> public LSL_List lsGetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return new LSL_List(); } m_host.AddScriptLPS(1); RegionLightShareData wl = m_host.ParentGroup.Scene.RegionInfo.WindlightSettings; LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { LSL_Integer ruleInt = rules.GetLSLIntegerItem(idx); uint rule = (uint)ruleInt; LSL_List toadd = new LSL_List(); switch (rule) { case (int)ScriptBaseClass.WL_AMBIENT: toadd.Add(new LSL_Rotation(wl.ambient.X, wl.ambient.Y, wl.ambient.Z, wl.ambient.W)); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.bigWaveDirection.X, wl.bigWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: toadd.Add(new LSL_Rotation(wl.blueDensity.X, wl.blueDensity.Y, wl.blueDensity.Z, wl.blueDensity.W)); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: toadd.Add(new LSL_Float(wl.blurMultiplier)); break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: toadd.Add(new LSL_Rotation(wl.cloudColor.X, wl.cloudColor.Y, wl.cloudColor.Z, wl.cloudColor.W)); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: toadd.Add(new LSL_Float(wl.cloudCoverage)); break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudDetailXYDensity.X, wl.cloudDetailXYDensity.Y, wl.cloudDetailXYDensity.Z)); break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: toadd.Add(new LSL_Float(wl.cloudScale)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: toadd.Add(new LSL_Float(wl.cloudScrollX)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollXLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: toadd.Add(new LSL_Float(wl.cloudScrollY)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollYLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudXYDensity.X, wl.cloudXYDensity.Y, wl.cloudXYDensity.Z)); break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: toadd.Add(new LSL_Float(wl.densityMultiplier)); break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: toadd.Add(new LSL_Float(wl.distanceMultiplier)); break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: toadd.Add(new LSL_Integer(wl.drawClassicClouds ? 1 : 0)); break; case (int)ScriptBaseClass.WL_EAST_ANGLE: toadd.Add(new LSL_Float(wl.eastAngle)); break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: toadd.Add(new LSL_Float(wl.fresnelOffset)); break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: toadd.Add(new LSL_Float(wl.fresnelScale)); break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: toadd.Add(new LSL_Float(wl.hazeDensity)); break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: toadd.Add(new LSL_Float(wl.hazeHorizon)); break; case (int)ScriptBaseClass.WL_HORIZON: toadd.Add(new LSL_Rotation(wl.horizon.X, wl.horizon.Y, wl.horizon.Z, wl.horizon.W)); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.littleWaveDirection.X, wl.littleWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: toadd.Add(new LSL_Integer(wl.maxAltitude)); break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: toadd.Add(new LSL_Key(wl.normalMapTexture.ToString())); break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: toadd.Add(new LSL_Vector(wl.reflectionWaveletScale.X, wl.reflectionWaveletScale.Y, wl.reflectionWaveletScale.Z)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: toadd.Add(new LSL_Float(wl.refractScaleAbove)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: toadd.Add(new LSL_Float(wl.refractScaleBelow)); break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: toadd.Add(new LSL_Float(wl.sceneGamma)); break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: toadd.Add(new LSL_Float(wl.starBrightness)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: toadd.Add(new LSL_Float(wl.sunGlowFocus)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: toadd.Add(new LSL_Float(wl.sunGlowSize)); break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: toadd.Add(new LSL_Rotation(wl.sunMoonColor.X, wl.sunMoonColor.Y, wl.sunMoonColor.Z, wl.sunMoonColor.W)); break; case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: toadd.Add(new LSL_Float(wl.sunMoonPosition)); break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: toadd.Add(new LSL_Float(wl.underwaterFogModifier)); break; case (int)ScriptBaseClass.WL_WATER_COLOR: toadd.Add(new LSL_Vector(wl.waterColor.X, wl.waterColor.Y, wl.waterColor.Z)); break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: toadd.Add(new LSL_Float(wl.waterFogDensityExponent)); break; } if (toadd.Length > 0) { values.Add(ruleInt); values.Add(toadd.Data[0]); } idx++; } return values; } private RegionLightShareData getWindlightProfileFromRules(LSL_List rules) { RegionLightShareData wl = (RegionLightShareData)m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.Clone(); // LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { uint rule; try { rule = (uint)rules.GetLSLIntegerItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule type: arg #{0} - parameter type must be integer", idx)); } LSL_Types.Quaternion iQ; LSL_Types.Vector3 iV; switch (rule) { case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: idx++; try { wl.sunMoonPosition = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_MOON_POSITION: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_AMBIENT: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_AMBIENT: arg #{0} - parameter 1 must be rotation", idx)); } wl.ambient = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BIG_WAVE_DIRECTION: arg #{0} - parameter 1 must be vector", idx)); } wl.bigWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BLUE_DENSITY: arg #{0} - parameter 1 must be rotation", idx)); } wl.blueDensity = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: idx++; try { wl.blurMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_BLUR_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_COLOR: arg #{0} - parameter 1 must be rotation", idx)); } wl.cloudColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: idx++; try { wl.cloudCoverage = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_COVERAGE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_DETAIL_XY_DENSITY: arg #{0} - parameter 1 must be vector", idx)); } wl.cloudDetailXYDensity = iV; break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: idx++; try { wl.cloudScale = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCALE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: idx++; try { wl.cloudScrollX = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_X: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: idx++; try { wl.cloudScrollXLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y_LOCK: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: idx++; try { wl.cloudScrollY = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: idx++; try { wl.cloudScrollYLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_SCROLL_Y_LOCK: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_CLOUD_XY_DENSITY: arg #{0} - parameter 1 must be vector", idx)); } wl.cloudXYDensity = iV; break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: idx++; try { wl.densityMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DENSITY_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: idx++; try { wl.distanceMultiplier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DISTANCE_MULTIPLIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: idx++; try { wl.drawClassicClouds = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_DRAW_CLASSIC_CLOUDS: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_EAST_ANGLE: idx++; try { wl.eastAngle = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_EAST_ANGLE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: idx++; try { wl.fresnelOffset = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_FRESNEL_OFFSET: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: idx++; try { wl.fresnelScale = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_FRESNEL_SCALE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: idx++; try { wl.hazeDensity = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HAZE_DENSITY: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: idx++; try { wl.hazeHorizon = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HAZE_HORIZON: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_HORIZON: idx++; try { iQ = rules.GetQuaternionItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_HORIZON: arg #{0} - parameter 1 must be rotation", idx)); } wl.horizon = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_LITTLE_WAVE_DIRECTION: arg #{0} - parameter 1 must be vector", idx)); } wl.littleWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: idx++; try { wl.maxAltitude = (ushort)rules.GetLSLIntegerItem(idx).value; } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_MAX_ALTITUDE: arg #{0} - parameter 1 must be integer", idx)); } break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: idx++; try { wl.normalMapTexture = new UUID(rules.GetLSLStringItem(idx).m_string); } catch (ArgumentException) { throw new InvalidCastException(string.Format("Error running rule WL_NORMAL_MAP_TEXTURE: arg #{0} - parameter 1 must be key", idx)); } break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFLECTION_WAVELET_SCALE: arg #{0} - parameter 1 must be vector", idx)); } wl.reflectionWaveletScale = iV; break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: idx++; try { wl.refractScaleAbove = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFRACT_SCALE_ABOVE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: idx++; try { wl.refractScaleBelow = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_REFRACT_SCALE_BELOW: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: idx++; try { wl.sceneGamma = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SCENE_GAMMA: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: idx++; try { wl.starBrightness = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_STAR_BRIGHTNESS: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: idx++; try { wl.sunGlowFocus = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_GLOW_FOCUS: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: idx++; try { wl.sunGlowSize = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_GLOW_SIZE: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: idx++; iQ = rules.GetQuaternionItem(idx); try { wl.sunMoonColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_SUN_MOON_COLOR: arg #{0} - parameter 1 must be rotation", idx)); } break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: idx++; try { wl.underwaterFogModifier = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_UNDERWATER_FOG_MODIFIER: arg #{0} - parameter 1 must be float", idx)); } break; case (int)ScriptBaseClass.WL_WATER_COLOR: idx++; try { iV = rules.GetVector3Item(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_WATER_COLOR: arg #{0} - parameter 1 must be vector", idx)); } wl.waterColor = iV; break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: idx++; try { wl.waterFogDensityExponent = (float)rules.GetLSLFloatItem(idx); } catch (InvalidCastException) { throw new InvalidCastException(string.Format("Error running rule WL_WATER_FOG_DENSITY_EXPONENT: arg #{0} - parameter 1 must be float", idx)); } break; } idx++; } return wl; } /// <summary> /// Set the current Windlight scene /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return 0; } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl; try { wl = getWindlightProfileFromRules(rules); } catch(InvalidCastException e) { LSShoutError(e.Message); return 0; } wl.valid = true; m_host.ParentGroup.Scene.StoreWindlightProfile(wl); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } public void lsClearWindlightScene() { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return; } m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.valid = false; if (m_host.ParentGroup.Scene.SimulationDataService != null) m_host.ParentGroup.Scene.SimulationDataService.RemoveRegionWindlightSettings(m_host.ParentGroup.Scene.RegionInfo.RegionID); m_host.ParentGroup.Scene.EventManager.TriggerOnSaveNewWindlightProfile(); } /// <summary> /// Set the current Windlight scene to a target avatar /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightSceneTargeted(LSL_List rules, LSL_Key target) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { LSShoutError("lsSetWindlightSceneTargeted can only be used by estate managers or owners."); return 0; } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl; try { wl = getWindlightProfileFromRules(rules); } catch(InvalidCastException e) { LSShoutError(e.Message); return 0; } World.EventManager.TriggerOnSendNewWindlightProfileTargeted(wl, new UUID(target.m_string)); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } } }
using System; using System.Collections.Generic; namespace angeldnd.dap { public static class ContextExtension { public static bool RemoveFromOwner(this IContext context) { IDict owner = context.OwnerAsDict; if (owner == null) return false; return owner.Remove<IContext>(context.Key) != null; } public static T GetAncestor<T>(this IContext context, Func<T, bool> checker = null) where T : class, IContext { return TreeHelper.GetAncestor<T>(context, checker); } public static T GetAncestorManner<T>(this IContext context, string mannerKey) where T : class, IManner { T result = null; GetAncestor<IContext>(context, (IContext ancestor) => { result = ancestor.Manners.Get<T>(mannerKey, true); return result != null; }); return result; } public static T GetOwnOrAncestorManner<T>(this IContext context, string mannerKey) where T : class, IManner { T manner = context.Manners.Get<T>(mannerKey, true); if (manner != null) return manner; return GetAncestorManner<T>(context, mannerKey); } public static T GetContext<T>(this IDictContext context, string relPath, bool isDebug = false) where T : class, IContext { return TreeHelper.GetDescendant<T>(context, relPath, isDebug); } public static IContext GetContext(this IDictContext context, string relPath, bool isDebug = false) { return GetContext<IContext>(context, relPath, isDebug); } public static bool HasContext(this IDictContext context, string relPath) { return GetContext<IContext>(context, relPath, true) != null; } public static T GetContextManner<T>(this IDictContext context, string relPath, string mannerKey, bool isDebug = false) where T : class, IManner { IContext descendant = GetContext<IContext>(context, relPath, isDebug); if (descendant != null) { T manner = descendant.Manners.Get<T>(mannerKey, isDebug); return manner; } return null; } //Note: Use IContext here so no need to cast to IDictContext public static string GetRelativePath(this IContext context, IContext descendant) { return PathHelper.GetRelativePath(context.Path, descendant.Path); } public static void ForEachContexts<T>(this IDictContext context, Action<T> callback) where T : class, IContext { TreeHelper.ForEachDescendants<T>(context, callback); } public static void ForEachContexts(this IDictContext context, Action<IContext> callback) { ForEachContexts<IContext>(context, callback); } public static List<T> GetContexts<T>(this IDictContext context) where T : class, IContext { return TreeHelper.GetDescendants<T>(context); } public static void ForEachContextsWithManner<T>(this IDictContext context, string mannerKey, Action<T> callback) where T : class, IManner { TreeHelper.ForEachDescendants<IContext>(context, (IContext element) => { T manner = element.Manners.Get<T>(mannerKey, true); if (manner != null) { callback(manner); } }); } public static List<T> GetContextsWithManner<T>(this IDictContext context, string mannerKey) where T : class, IManner { List<T> result = null; ForEachContextsWithManner<T>(context, mannerKey, (T manner) => { if (result == null) { result = new List<T>(); } result.Add(manner); }); return result; } public static T FirstContext<T>(this IDictContext context, Func<T, bool> callback, bool isDebug = false) where T : class, IContext { T result = null; TreeHelper.ForEachDescendants<T>(context, (T element) => { if (result == null && callback(element)) { result = element; } }); if (result == null) { context.ErrorOrDebug(isDebug, "First<{0}>({1}): Not Found", typeof(T).FullName, callback); } return result; } public static T FirstContext<T>(this IDictContext context, bool isDebug = false) where T : class, IContext { return FirstContext<T>(context, (T element) => { return true; }, isDebug); } public static T AddContext<TO, T>(this IDictContext context, string relPath) where TO : class, IDictContext where T : class, IContext { return TreeHelper.AddDescendant<TO, T>(context, relPath); } public static T AddContext<T>(this IDictContext context, string relPath) where T : class, IContext { return TreeHelper.AddDescendant<Items, T>(context, relPath); } public static T GetOrAddContext<TO, T>(this IDictContext context, string relPath) where TO : class, IDictContext where T : class, IContext { return TreeHelper.GetOrAddDescendant<TO, T>(context, relPath); } public static T GetOrAddContext<T>(this IDictContext context, string relPath) where T : class, IContext { return TreeHelper.GetOrAddDescendant<Items, T>(context, relPath); } public static T NewContext<TO, T>(this IDictContext context, string type, string relPath) where TO : class, IDictContext where T : class, IContext { return TreeHelper.NewDescendant<TO, T>(context, type, relPath); } public static T NewContext<T>(this IDictContext context, string type, string relPath) where T : class, IContext { return TreeHelper.NewDescendant<Items, T>(context, type, relPath); } public static T NewContext<T>(this IDictContext context, string relPath) where T : class, IContext { string dapType = DapType.GetDapType(typeof(T)); if (dapType == null) { context.Error("NewContext Failed, DapType Not Defined: " + typeof(T)); return null; } return NewContext<T>(context, dapType, relPath); } public static IContext NewContext(this IDictContext context, string type, string relPath) { return TreeHelper.NewDescendant<Items, IContext>(context, type, relPath); } public static T NewContextWithManner<T>(this IDictContext context, string type, string relPath, string mannerKey) where T : class, IManner { IContext descendant = NewContext(context, type, relPath); if (descendant != null) { return descendant.Manners.Add<T>(mannerKey); } return null; } public static T GetOrNewContext<T>(this IDictContext context, string type, string relPath) where T : class, IContext { return TreeHelper.GetOrNewDescendant<Items, T>(context, type, relPath); } public static T GetOrNewContext<T>(this IDictContext context, string relPath) where T : class, IContext { string dapType = DapType.GetDapType(typeof(T)); if (dapType == null) { context.Error("GetOrNewContext Failed, DapType Not Defined: " + typeof(T)); return null; } return TreeHelper.GetOrNewDescendant<Items, T>(context, dapType, relPath); } public static IContext GetOrNewContext(this IDictContext context, string type, string relPath) { return TreeHelper.GetOrNewDescendant<Items, IContext>(context, type, relPath); } public static T GetOrNewContextWithManner<T>(this IDictContext context, string type, string relPath, string mannerKey) where T : class, IManner { IContext descendant = GetOrNewContext(context, type, relPath); if (descendant != null) { return descendant.Manners.Add<T>(mannerKey); } return null; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Exam Subjects Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class TTESDataSet : EduHubDataSet<TTES> { /// <inheritdoc /> public override string Name { get { return "TTES"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal TTESDataSet(EduHubContext Context) : base(Context) { Index_GKEY = new Lazy<Dictionary<string, IReadOnlyList<TTES>>>(() => this.ToGroupedDictionary(i => i.GKEY)); Index_SUBJ = new Lazy<NullDictionary<string, IReadOnlyList<TTES>>>(() => this.ToGroupedNullDictionary(i => i.SUBJ)); Index_TID = new Lazy<Dictionary<int, TTES>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="TTES" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="TTES" /> fields for each CSV column header</returns> internal override Action<TTES, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<TTES, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "GKEY": mapper[i] = (e, v) => e.GKEY = v; break; case "TTEI_TID": mapper[i] = (e, v) => e.TTEI_TID = v == null ? (int?)null : int.Parse(v); break; case "SUBJ": mapper[i] = (e, v) => e.SUBJ = v; break; case "UNITS": mapper[i] = (e, v) => e.UNITS = v == null ? (short?)null : short.Parse(v); break; case "INCLUDE01": mapper[i] = (e, v) => e.INCLUDE01 = v; break; case "INCLUDE02": mapper[i] = (e, v) => e.INCLUDE02 = v; break; case "INCLUDE03": mapper[i] = (e, v) => e.INCLUDE03 = v; break; case "INCLUDE04": mapper[i] = (e, v) => e.INCLUDE04 = v; break; case "INCLUDE05": mapper[i] = (e, v) => e.INCLUDE05 = v; break; case "INCLUDE06": mapper[i] = (e, v) => e.INCLUDE06 = v; break; case "INCLUDE07": mapper[i] = (e, v) => e.INCLUDE07 = v; break; case "INCLUDE08": mapper[i] = (e, v) => e.INCLUDE08 = v; break; case "INCLUDE09": mapper[i] = (e, v) => e.INCLUDE09 = v; break; case "INCLUDE10": mapper[i] = (e, v) => e.INCLUDE10 = v; break; case "INCLUDE11": mapper[i] = (e, v) => e.INCLUDE11 = v; break; case "INCLUDE12": mapper[i] = (e, v) => e.INCLUDE12 = v; break; case "INCLUDE13": mapper[i] = (e, v) => e.INCLUDE13 = v; break; case "INCLUDE14": mapper[i] = (e, v) => e.INCLUDE14 = v; break; case "INCLUDE15": mapper[i] = (e, v) => e.INCLUDE15 = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="TTES" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="TTES" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="TTES" /> entities</param> /// <returns>A merged <see cref="IEnumerable{TTES}"/> of entities</returns> internal override IEnumerable<TTES> ApplyDeltaEntities(IEnumerable<TTES> Entities, List<TTES> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.GKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.GKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<TTES>>> Index_GKEY; private Lazy<NullDictionary<string, IReadOnlyList<TTES>>> Index_SUBJ; private Lazy<Dictionary<int, TTES>> Index_TID; #endregion #region Index Methods /// <summary> /// Find TTES by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTES</param> /// <returns>List of related TTES entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTES> FindByGKEY(string GKEY) { return Index_GKEY.Value[GKEY]; } /// <summary> /// Attempt to find TTES by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTES</param> /// <param name="Value">List of related TTES entities</param> /// <returns>True if the list of related TTES entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByGKEY(string GKEY, out IReadOnlyList<TTES> Value) { return Index_GKEY.Value.TryGetValue(GKEY, out Value); } /// <summary> /// Attempt to find TTES by GKEY field /// </summary> /// <param name="GKEY">GKEY value used to find TTES</param> /// <returns>List of related TTES entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTES> TryFindByGKEY(string GKEY) { IReadOnlyList<TTES> value; if (Index_GKEY.Value.TryGetValue(GKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find TTES by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTES</param> /// <returns>List of related TTES entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTES> FindBySUBJ(string SUBJ) { return Index_SUBJ.Value[SUBJ]; } /// <summary> /// Attempt to find TTES by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTES</param> /// <param name="Value">List of related TTES entities</param> /// <returns>True if the list of related TTES entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySUBJ(string SUBJ, out IReadOnlyList<TTES> Value) { return Index_SUBJ.Value.TryGetValue(SUBJ, out Value); } /// <summary> /// Attempt to find TTES by SUBJ field /// </summary> /// <param name="SUBJ">SUBJ value used to find TTES</param> /// <returns>List of related TTES entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<TTES> TryFindBySUBJ(string SUBJ) { IReadOnlyList<TTES> value; if (Index_SUBJ.Value.TryGetValue(SUBJ, out value)) { return value; } else { return null; } } /// <summary> /// Find TTES by TID field /// </summary> /// <param name="TID">TID value used to find TTES</param> /// <returns>Related TTES entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public TTES FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find TTES by TID field /// </summary> /// <param name="TID">TID value used to find TTES</param> /// <param name="Value">Related TTES entity</param> /// <returns>True if the related TTES entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out TTES Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find TTES by TID field /// </summary> /// <param name="TID">TID value used to find TTES</param> /// <returns>Related TTES entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public TTES TryFindByTID(int TID) { TTES value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a TTES table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[TTES]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[TTES]( [TID] int IDENTITY NOT NULL, [GKEY] varchar(8) NOT NULL, [TTEI_TID] int NULL, [SUBJ] varchar(5) NULL, [UNITS] smallint NULL, [INCLUDE01] varchar(1) NULL, [INCLUDE02] varchar(1) NULL, [INCLUDE03] varchar(1) NULL, [INCLUDE04] varchar(1) NULL, [INCLUDE05] varchar(1) NULL, [INCLUDE06] varchar(1) NULL, [INCLUDE07] varchar(1) NULL, [INCLUDE08] varchar(1) NULL, [INCLUDE09] varchar(1) NULL, [INCLUDE10] varchar(1) NULL, [INCLUDE11] varchar(1) NULL, [INCLUDE12] varchar(1) NULL, [INCLUDE13] varchar(1) NULL, [INCLUDE14] varchar(1) NULL, [INCLUDE15] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [TTES_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [TTES_Index_GKEY] ON [dbo].[TTES] ( [GKEY] ASC ); CREATE NONCLUSTERED INDEX [TTES_Index_SUBJ] ON [dbo].[TTES] ( [SUBJ] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTES]') AND name = N'TTES_Index_SUBJ') ALTER INDEX [TTES_Index_SUBJ] ON [dbo].[TTES] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTES]') AND name = N'TTES_Index_TID') ALTER INDEX [TTES_Index_TID] ON [dbo].[TTES] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTES]') AND name = N'TTES_Index_SUBJ') ALTER INDEX [TTES_Index_SUBJ] ON [dbo].[TTES] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[TTES]') AND name = N'TTES_Index_TID') ALTER INDEX [TTES_Index_TID] ON [dbo].[TTES] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="TTES"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="TTES"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<TTES> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[TTES] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the TTES data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the TTES data set</returns> public override EduHubDataSetDataReader<TTES> GetDataSetDataReader() { return new TTESDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the TTES data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the TTES data set</returns> public override EduHubDataSetDataReader<TTES> GetDataSetDataReader(List<TTES> Entities) { return new TTESDataReader(new EduHubDataSetLoadedReader<TTES>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class TTESDataReader : EduHubDataSetDataReader<TTES> { public TTESDataReader(IEduHubDataSetReader<TTES> Reader) : base (Reader) { } public override int FieldCount { get { return 23; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // GKEY return Current.GKEY; case 2: // TTEI_TID return Current.TTEI_TID; case 3: // SUBJ return Current.SUBJ; case 4: // UNITS return Current.UNITS; case 5: // INCLUDE01 return Current.INCLUDE01; case 6: // INCLUDE02 return Current.INCLUDE02; case 7: // INCLUDE03 return Current.INCLUDE03; case 8: // INCLUDE04 return Current.INCLUDE04; case 9: // INCLUDE05 return Current.INCLUDE05; case 10: // INCLUDE06 return Current.INCLUDE06; case 11: // INCLUDE07 return Current.INCLUDE07; case 12: // INCLUDE08 return Current.INCLUDE08; case 13: // INCLUDE09 return Current.INCLUDE09; case 14: // INCLUDE10 return Current.INCLUDE10; case 15: // INCLUDE11 return Current.INCLUDE11; case 16: // INCLUDE12 return Current.INCLUDE12; case 17: // INCLUDE13 return Current.INCLUDE13; case 18: // INCLUDE14 return Current.INCLUDE14; case 19: // INCLUDE15 return Current.INCLUDE15; case 20: // LW_DATE return Current.LW_DATE; case 21: // LW_TIME return Current.LW_TIME; case 22: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // TTEI_TID return Current.TTEI_TID == null; case 3: // SUBJ return Current.SUBJ == null; case 4: // UNITS return Current.UNITS == null; case 5: // INCLUDE01 return Current.INCLUDE01 == null; case 6: // INCLUDE02 return Current.INCLUDE02 == null; case 7: // INCLUDE03 return Current.INCLUDE03 == null; case 8: // INCLUDE04 return Current.INCLUDE04 == null; case 9: // INCLUDE05 return Current.INCLUDE05 == null; case 10: // INCLUDE06 return Current.INCLUDE06 == null; case 11: // INCLUDE07 return Current.INCLUDE07 == null; case 12: // INCLUDE08 return Current.INCLUDE08 == null; case 13: // INCLUDE09 return Current.INCLUDE09 == null; case 14: // INCLUDE10 return Current.INCLUDE10 == null; case 15: // INCLUDE11 return Current.INCLUDE11 == null; case 16: // INCLUDE12 return Current.INCLUDE12 == null; case 17: // INCLUDE13 return Current.INCLUDE13 == null; case 18: // INCLUDE14 return Current.INCLUDE14 == null; case 19: // INCLUDE15 return Current.INCLUDE15 == null; case 20: // LW_DATE return Current.LW_DATE == null; case 21: // LW_TIME return Current.LW_TIME == null; case 22: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // GKEY return "GKEY"; case 2: // TTEI_TID return "TTEI_TID"; case 3: // SUBJ return "SUBJ"; case 4: // UNITS return "UNITS"; case 5: // INCLUDE01 return "INCLUDE01"; case 6: // INCLUDE02 return "INCLUDE02"; case 7: // INCLUDE03 return "INCLUDE03"; case 8: // INCLUDE04 return "INCLUDE04"; case 9: // INCLUDE05 return "INCLUDE05"; case 10: // INCLUDE06 return "INCLUDE06"; case 11: // INCLUDE07 return "INCLUDE07"; case 12: // INCLUDE08 return "INCLUDE08"; case 13: // INCLUDE09 return "INCLUDE09"; case 14: // INCLUDE10 return "INCLUDE10"; case 15: // INCLUDE11 return "INCLUDE11"; case 16: // INCLUDE12 return "INCLUDE12"; case 17: // INCLUDE13 return "INCLUDE13"; case 18: // INCLUDE14 return "INCLUDE14"; case 19: // INCLUDE15 return "INCLUDE15"; case 20: // LW_DATE return "LW_DATE"; case 21: // LW_TIME return "LW_TIME"; case 22: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "GKEY": return 1; case "TTEI_TID": return 2; case "SUBJ": return 3; case "UNITS": return 4; case "INCLUDE01": return 5; case "INCLUDE02": return 6; case "INCLUDE03": return 7; case "INCLUDE04": return 8; case "INCLUDE05": return 9; case "INCLUDE06": return 10; case "INCLUDE07": return 11; case "INCLUDE08": return 12; case "INCLUDE09": return 13; case "INCLUDE10": return 14; case "INCLUDE11": return 15; case "INCLUDE12": return 16; case "INCLUDE13": return 17; case "INCLUDE14": return 18; case "INCLUDE15": return 19; case "LW_DATE": return 20; case "LW_TIME": return 21; case "LW_USER": return 22; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
#pragma warning disable SA1633 // File should have header - This is an imported file, // original header with license shall remain the same using UtfUnknown.Core.Models; namespace UtfUnknown.Core.Models.MultiByte.Japanese; internal class SJIS_SMModel : StateMachineModel { private static readonly int[] SJIS_cls = { //BitPacket.Pack4bits(0,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 00 - 07 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 0, 0), // 08 - 0f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 10 - 17 BitPackage.Pack4bits( 1, 1, 1, 0, 1, 1, 1, 1), // 18 - 1f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 20 - 27 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 28 - 2f BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 30 - 37 BitPackage.Pack4bits( 1, 1, 1, 1, 1, 1, 1, 1), // 38 - 3f BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 40 - 47 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 48 - 4f BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 50 - 57 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 58 - 5f BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 60 - 67 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 68 - 6f BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // 70 - 77 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 1), // 78 - 7f BitPackage.Pack4bits( 3, 3, 3, 3, 3, 3, 3, 3), // 80 - 87 BitPackage.Pack4bits( 3, 3, 3, 3, 3, 3, 3, 3), // 88 - 8f BitPackage.Pack4bits( 3, 3, 3, 3, 3, 3, 3, 3), // 90 - 97 BitPackage.Pack4bits( 3, 3, 3, 3, 3, 3, 3, 3), // 98 - 9f //0xa0 is illegal in sjis encoding, but some pages does //contain such byte. We need to be more error forgiven. BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // a0 - a7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // a8 - af BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // b0 - b7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // b8 - bf BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // c0 - c7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // c8 - cf BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // d0 - d7 BitPackage.Pack4bits( 2, 2, 2, 2, 2, 2, 2, 2), // d8 - df BitPackage.Pack4bits( 3, 3, 3, 3, 3, 3, 3, 3), // e0 - e7 BitPackage.Pack4bits( 3, 3, 3, 3, 3, 4, 4, 4), // e8 - ef BitPackage.Pack4bits( 4, 4, 4, 4, 4, 4, 4, 4), // f0 - f7 BitPackage.Pack4bits( 4, 4, 4, 4, 4, 0, 0, 0) // f8 - ff }; private static readonly int[] SJIS_st = { BitPackage.Pack4bits( ERROR, START, START, 3, ERROR, ERROR, ERROR, ERROR), //00-07 BitPackage.Pack4bits( ERROR, ERROR, ERROR, ERROR, ITSME, ITSME, ITSME, ITSME), //08-0f BitPackage.Pack4bits( ITSME, ITSME, ERROR, ERROR, START, START, START, START) //10-17 }; private static readonly int[] SJISCharLenTable = { 0, 1, 1, 2, 0, 0 }; public SJIS_SMModel() : base( new BitPackage( BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, SJIS_cls), 6, new BitPackage( BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, SJIS_st), SJISCharLenTable, CodepageName.SHIFT_JIS) { } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #if FEATURE_WIN32_REGISTRY using System; using System.Collections.Generic; using Microsoft.Build.Collections; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Internal; using Microsoft.Build.Shared; using Microsoft.Win32; using Xunit; using InvalidToolsetDefinitionException = Microsoft.Build.Exceptions.InvalidToolsetDefinitionException; namespace Microsoft.Build.UnitTests.Definition { /// <summary> /// Unit test for ToolsetRegistryReader class /// </summary> [PlatformSpecific(TestPlatforms.Windows)] public class ToolsetRegistryReader_Tests : IDisposable { // The registry key that is passed as the baseKey parameter to the ToolsetRegistryReader class private RegistryKey _testRegistryKey = null; // Subkey "3.5" private RegistryKey _currentVersionRegistryKey = null; // Subkey "ToolsVersions" private RegistryKey _toolsVersionsRegistryKey = null; // Path to the registry key under HKCU // Note that this is a test registry key created solely for unit testing. private const string testRegistryPath = @"msbuildUnitTests"; /// <summary> /// Store the value of the "VisualStudioVersion" environment variable here so that /// we can unset it for the duration of the test. /// </summary> private string _oldVisualStudioVersion; /// <summary> /// Reset the testRegistryKey /// </summary> public ToolsetRegistryReader_Tests() { DeleteTestRegistryKey(); _testRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath); _currentVersionRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath + "\\" + Constants.AssemblyVersion); _toolsVersionsRegistryKey = Registry.CurrentUser.CreateSubKey(testRegistryPath + "\\ToolsVersions"); _oldVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); Environment.SetEnvironmentVariable("VisualStudioVersion", null); } public void Dispose() { DeleteTestRegistryKey(); Environment.SetEnvironmentVariable("VisualStudioVersion", _oldVisualStudioVersion); } /// <summary> /// Helper class to delete the testRegistryKey tree. /// </summary> private void DeleteTestRegistryKey() { if (Registry.CurrentUser.OpenSubKey(testRegistryPath) != null) { Registry.CurrentUser.DeleteSubKeyTree(testRegistryPath); } } /// <summary> /// If the base key has been deleted, then we just don't get any information (no exception) /// </summary> [Fact] public void ReadRegistry_DeletedKey() { DeleteTestRegistryKey(); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Empty(values); } /// <summary> /// Tests the tools version 4.0 is written to the registry at install time /// </summary> [Fact(Skip = "Test requires installed toolset.")] public void DefaultValuesInRegistryCreatedBySetup() { if (NativeMethodsShared.IsUnixLike) { return; // "TODO: under Unix this runs out of stack. Investigate" } ToolsetReader reader = new ToolsetRegistryReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>()); //we don't use the test registry key because we want to verify the install Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); // Check the values in the data Assert.True(values.ContainsKey("4.0")); // "Tools version 4.0 should be defined by default" Assert.True(values.ContainsKey(ObjectModelHelpers.MSBuildDefaultToolsVersion), String.Format("Tools version {0} should be defined by default", ObjectModelHelpers.MSBuildDefaultToolsVersion)); Assert.Equal("2.0", defaultToolsVersion); // "Default tools version should be 2.0" } /// <summary> /// Tests we handle no default toolset specified in the registry /// </summary> [Fact] public void DefaultValueInRegistryDoesNotExist() { ToolsetReader reader = new ToolsetRegistryReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), new MockRegistryKey(testRegistryPath, "3.5" /* fail to find subkey 3.5 */)); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); // Should not throw string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Null(defaultToolsVersion); } /// <summary> /// The base key exists but contains no subkey or values: this is okay /// </summary> [Fact] public void ReadRegistry_NoSubkeyNoValues() { ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Empty(values); Assert.Null(defaultToolsVersion); } /// <summary> /// Here we validate that MSBuild does not fail when there are unrecognized values underneath /// the ToolsVersion key. /// </summary> [Fact] public void ReadRegistry_NoSubkeysOnlyValues() { _toolsVersionsRegistryKey.SetValue("Name1", "Value1"); _toolsVersionsRegistryKey.SetValue("Name2", "Value2"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Empty(values); Assert.Null(defaultToolsVersion); } /// <summary> /// Basekey has only 1 subkey /// </summary> [Fact] public void ReadRegistry_OnlyOneSubkey() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Null(defaultToolsVersion); Assert.Single(values); Assert.Empty(values["tv1"].Properties); Assert.Equal(0, String.Compare(xdir, values["tv1"].ToolsPath, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Basic case /// </summary> [Fact] public void ReadRegistry_Basic() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; string ydir = NativeMethodsShared.IsWindows ? "c:\\yyy" : "/yyy"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); key1.SetValue("name1", "value1"); RegistryKey key2 = _toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("name2", "value2"); key2.SetValue("msbuildtoolspath", ydir); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Equal(2, values.Count); Assert.Single(values["tv1"].Properties); Assert.Equal(0, String.Compare(xdir, values["tv1"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assert.Equal(0, String.Compare("value1", values["tv1"].Properties["name1"].EvaluatedValue, StringComparison.OrdinalIgnoreCase)); Assert.Single(values["tv2"].Properties); Assert.Equal(0, String.Compare(ydir, values["tv2"].ToolsPath, StringComparison.OrdinalIgnoreCase)); Assert.Equal(0, String.Compare("value2", values["tv2"].Properties["name2"].EvaluatedValue, StringComparison.OrdinalIgnoreCase)); } /// <summary> /// baseKey contains some non-String data /// </summary> [Fact] public void ReadRegistry_NonStringData() { Assert.Throws<InvalidToolsetDefinitionException>(() => { RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); key1.SetValue("name1", "value1"); RegistryKey key2 = _toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("msbuildtoolspath", "c:\\xxx"); key2.SetValue("name2", new String[] { "value2a", "value2b" }, RegistryValueKind.MultiString); ToolsetReader reader = GetStandardRegistryReader(); string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); } ); } /// <summary> /// Registry has the following structure /// [HKCU]\basekey\ /// Key1 /// SubKey1 /// Key2 /// SubKey2 /// SubKey3 /// </summary> [Fact] public void ReadRegistry_HasSubToolsets() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; string ydir = NativeMethodsShared.IsWindows ? "c:\\yyy" : "/yyy"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); key1.SetValue("name1", "value1"); RegistryKey subKey1 = key1.CreateSubKey("SubKey1"); subKey1.SetValue("name1a", "value1a"); subKey1.SetValue("name2a", "value2a"); RegistryKey key2 = _toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("msbuildtoolspath", ydir); key2.SetValue("name2", "value2"); RegistryKey subKey2 = key2.CreateSubKey("SubKey2"); subKey2.SetValue("name3a", "value3a"); subKey2.SetValue("name2a", "value2a"); RegistryKey subKey3 = key2.CreateSubKey("SubKey3"); subKey3.SetValue("name4a", "value4a"); subKey3.SetValue("name5a", "value5a"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Equal(2, values.Count); Assert.Single(values["tv1"].Properties); Assert.Equal(xdir, values["tv1"].ToolsPath); Assert.Equal("value1", values["tv1"].Properties["name1"].EvaluatedValue); Assert.Single(values["tv1"].SubToolsets); Assert.Equal(2, values["tv1"].SubToolsets["SubKey1"].Properties.Count); Assert.Equal("value1a", values["tv1"].SubToolsets["SubKey1"].Properties["name1a"].EvaluatedValue); Assert.Equal("value2a", values["tv1"].SubToolsets["SubKey1"].Properties["name2a"].EvaluatedValue); Assert.Single(values["tv2"].Properties); Assert.Equal(ydir, values["tv2"].ToolsPath); Assert.Equal("value2", values["tv2"].Properties["name2"].EvaluatedValue); Assert.Equal(2, values["tv2"].SubToolsets.Count); Assert.Equal(2, values["tv2"].SubToolsets["SubKey2"].Properties.Count); Assert.Equal("value3a", values["tv2"].SubToolsets["SubKey2"].Properties["name3a"].EvaluatedValue); Assert.Equal("value2a", values["tv2"].SubToolsets["SubKey2"].Properties["name2a"].EvaluatedValue); Assert.Equal(2, values["tv2"].SubToolsets["SubKey3"].Properties.Count); Assert.Equal("value4a", values["tv2"].SubToolsets["SubKey3"].Properties["name4a"].EvaluatedValue); Assert.Equal("value5a", values["tv2"].SubToolsets["SubKey3"].Properties["name5a"].EvaluatedValue); } /// <summary> /// Registry has the following structure /// [HKCU]\basekey\ /// Key1 /// SubKey1 /// SubSubKey1 /// </summary> [Fact] public void ReadRegistry_IgnoreSubToolsetSubKeys() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); key1.SetValue("name1", "value1"); RegistryKey subKey1 = key1.CreateSubKey("SubKey1"); subKey1.SetValue("name1a", "value1a"); subKey1.SetValue("name2a", "value2a"); RegistryKey subSubKey1 = subKey1.CreateSubKey("SubSubKey1"); subSubKey1.SetValue("name2b", "value2b"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Single(values); Assert.Single(values["tv1"].Properties); Assert.Equal(xdir, values["tv1"].ToolsPath); Assert.Equal("value1", values["tv1"].Properties["name1"].EvaluatedValue); Assert.Single(values["tv1"].SubToolsets); Assert.Equal(2, values["tv1"].SubToolsets["SubKey1"].Properties.Count); Assert.Equal("value1a", values["tv1"].SubToolsets["SubKey1"].Properties["name1a"].EvaluatedValue); Assert.Equal("value2a", values["tv1"].SubToolsets["SubKey1"].Properties["name2a"].EvaluatedValue); } /// <summary> /// Verifies that if a value is defined in both the base toolset and the /// selected subtoolset, the subtoolset value overrides -- even if that /// value is empty. /// </summary> [Fact] public void ReadRegistry_SubToolsetOverridesBaseToolsetEntries() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); key1.SetValue("name1", "value1"); key1.SetValue("name2", "value2"); RegistryKey subKey1 = key1.CreateSubKey("Foo"); subKey1.SetValue("name1", "value1a"); subKey1.SetValue("name2", ""); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Single(values); Assert.Equal(2, values["tv1"].Properties.Count); Assert.Equal(xdir, values["tv1"].ToolsPath); Assert.Equal("value1", values["tv1"].Properties["name1"].EvaluatedValue); Assert.Equal("value2", values["tv1"].Properties["name2"].EvaluatedValue); Assert.Single(values["tv1"].SubToolsets); Assert.Equal(2, values["tv1"].SubToolsets["Foo"].Properties.Count); Assert.Equal("value1a", values["tv1"].SubToolsets["Foo"].Properties["name1"].EvaluatedValue); Assert.Equal("", values["tv1"].SubToolsets["Foo"].Properties["name2"].EvaluatedValue); // Check when requesting the final evaluated value of the property in the context of its sub-toolset // that the sub-toolset overrides Assert.Equal("value1a", values["tv1"].GetProperty("name1", "Foo").EvaluatedValue); Assert.Equal("", values["tv1"].GetProperty("name2", "Foo").EvaluatedValue); } /// <summary> /// Verifies that if a value is defined in both the base toolset and the /// selected subtoolset, the subtoolset value overrides -- even if that /// value is empty. /// </summary> [Fact] public void ReadRegistry_UnselectedSubToolsetIsIgnored() { string xdir = NativeMethodsShared.IsWindows ? "c:\\xxx" : "/xxx"; RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", xdir); key1.SetValue("name1", "value1"); key1.SetValue("name2", "value2"); RegistryKey subKey1 = key1.CreateSubKey("Foo"); subKey1.SetValue("name1", "value1a"); subKey1.SetValue("name2", ""); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Single(values); Assert.Equal(2, values["tv1"].Properties.Count); Assert.Equal(xdir, values["tv1"].ToolsPath); Assert.Equal("value1", values["tv1"].Properties["name1"].EvaluatedValue); Assert.Equal("value2", values["tv1"].Properties["name2"].EvaluatedValue); } /// <summary> /// Regular case of getting default tools version /// </summary> [Fact] public void GetDefaultToolsVersionFromRegistry_Basic() { _currentVersionRegistryKey.SetValue("DefaultToolsVersion", "tv1"); RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); // Need matching tools version key1.SetValue("msbuildtoolspath", "c:\\xxx"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Equal("tv1", defaultToolsVersion); } /// <summary> /// Default value is not set /// </summary> [Fact] public void GetDefaultToolsVersionFromRegistry_DefaultValueNotSet() { ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; string defaultToolsVersion = reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Null(defaultToolsVersion); } /// <summary> /// "DefaultToolsVersion" has non-String data /// </summary> [Fact] public void GetDefaultToolsVersionFromRegistry_NonStringData() { Assert.Throws<InvalidToolsetDefinitionException>(() => { _currentVersionRegistryKey.SetValue("DefaultToolsVersion", new String[] { "2.0.xxxx.a", "2.0.xxxx.b" }, RegistryValueKind.MultiString); ToolsetReader reader = GetStandardRegistryReader(); string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); } ); } private ToolsetRegistryReader GetStandardRegistryReader() { return new ToolsetRegistryReader(new ProjectCollection().EnvironmentProperties, new PropertyDictionary<ProjectPropertyInstance>(), new MockRegistryKey(testRegistryPath)); } /// <summary> /// Regular case of getting overridetaskspath /// </summary> [Fact] public void GetOverrideTasksPathFromRegistry_Basic() { if (NativeMethodsShared.IsUnixLike) { return; // "Registry is not supported under Unix" } _currentVersionRegistryKey.SetValue("MsBuildOverrideTasksPath", "c:\\Foo"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Equal("c:\\Foo", msbuildOverrideTasksPath); } /// <summary> /// OverrideTasksPath is not set /// </summary> [Fact] public void GetOverrideTasksPathFromRegistry_ValueNotSet() { ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Null(msbuildOverrideTasksPath); } /// <summary> /// "OverrideTasksPath" has non-String data /// </summary> [Fact] public void GetOverrideTasksPathFromRegistry_NonStringData() { Assert.Throws<InvalidToolsetDefinitionException>(() => { _currentVersionRegistryKey.SetValue("MsBuildOverrideTasksPath", new String[] { "2938304894", "3948394.2.3.3.3" }, RegistryValueKind.MultiString); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); } ); } /// <summary> /// Regular case of getting the default override toolsversion /// </summary> [Fact] public void GetDefaultOverrideToolsVersionFromRegistry_Basic() { _currentVersionRegistryKey.SetValue("DefaultOverrideToolsVersion", "Current"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Equal("Current", defaultOverrideToolsVersion); } /// <summary> /// DefaultOverrideToolsVersion is not set /// </summary> [Fact] public void GetDefaultOverrideToolsVersionFromRegistry_ValueNotSet() { ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.Null(defaultOverrideToolsVersion); } /// <summary> /// "DefaultOverrideToolsVersion" has non-String data /// </summary> [Fact] public void GetDefaultOverrideToolsVersionFromRegistry_NonStringData() { Assert.Throws<InvalidToolsetDefinitionException>(() => { _currentVersionRegistryKey.SetValue("DefaultOverrideToolsVersion", new String[] { "2938304894", "3948394.2.3.3.3" }, RegistryValueKind.MultiString); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath = null; string defaultOverrideToolsVersion = null; reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); } ); } [Fact] public void ReadToolsets_NoBinPathOrToolsPath() { RegistryKey key1 = _toolsVersionsRegistryKey.CreateSubKey("tv1"); key1.SetValue("msbuildtoolspath", "c:\\xxx"); key1.SetValue("name1", "value1"); RegistryKey key2 = _toolsVersionsRegistryKey.CreateSubKey("tv2"); key2.SetValue("name2", "value2"); RegistryKey key3 = _toolsVersionsRegistryKey.CreateSubKey("tv3"); key3.SetValue("msbuildtoolspath", "c:\\zzz"); key3.SetValue("name3", "value3"); ToolsetReader reader = GetStandardRegistryReader(); Dictionary<string, Toolset> values = new Dictionary<string, Toolset>(StringComparer.OrdinalIgnoreCase); string msbuildOverrideTasksPath; string defaultOverrideToolsVersion; //should not throw reader.ReadToolsets(values, new PropertyDictionary<ProjectPropertyInstance>(), new PropertyDictionary<ProjectPropertyInstance>(), false, out msbuildOverrideTasksPath, out defaultOverrideToolsVersion); Assert.True(values.ContainsKey("tv1")); //should not contain the second toolset because it does not define a tools/bin path Assert.False(values.ContainsKey("tv2")); Assert.True(values.ContainsKey("tv3")); } } } #endif
using System; using Microsoft.SPOT.Hardware; using System.Threading; // class alias to avoid ambiguous reference with Microsoft.SPOT.Hardware.Utility using upUtility = uPLibrary.Utilities.Utility; namespace uPLibrary.Hardware.Nfc { /// <summary> /// SPI communication layer /// </summary> public class PN532CommunicationSPI : IPN532CommunicationLayer { #region SPI Constants ... private const bool SPI_CS_ACTIVE_STATE = false; // LOW (pn532um.pdf, pag. 25) private const uint SPI_CS_SETUP_TIME = 2; private const uint SPI_CS_HOLD_TIME = 2; private const bool SPI_CLK_IDLE_STATE = false; // LOW (pn532um.pdf, pag. 25) private const bool SPI_CLK_EDGE = true; // LOW (pn532um.pdf, pag. 25) private const uint SPI_CLK_RATE = 1000; // 1 Mhz (up to 5 Mhz as pn532um.pdf, pag. 45) // (pn532um.pdf, pag. 45) private const byte PN532_SPI_DATAWRITE = 0x01; private const byte PN532_SPI_STATREAD = 0x02; private const byte PN532_SPI_DATAREAD = 0x03; #endregion // spi interface private SPI spi; // spi slave selection port private OutputPort nssPort; // irq interrupt port and event related InterruptPort irq; AutoResetEvent whIrq; /// <summary> /// Constructor /// </summary> /// <param name="spiModule">SPI device module</param> /// <param name="nss">Slave Selection</param> public PN532CommunicationSPI(SPI.SPI_module spiModule, Cpu.Pin nss) : this(spiModule, nss, Cpu.Pin.GPIO_NONE) { } public PN532CommunicationSPI(SPI.SPI_module spiModule, Cpu.Pin nss, Cpu.Pin irq) { SPI.Configuration spiCfg = new SPI.Configuration(Cpu.Pin.GPIO_NONE, // chip select pin SPI_CS_ACTIVE_STATE, // chip select active state SPI_CS_SETUP_TIME, // chip select setup time SPI_CS_HOLD_TIME, // chip select hold time SPI_CLK_IDLE_STATE, // clock idle state SPI_CLK_EDGE, // clock edge SPI_CLK_RATE, // clock rate (Khz) spiModule); // spi module used this.spi = new SPI(spiCfg); this.nssPort = new OutputPort(nss, true); this.irq = null; // use advanced handshake with IRQ pin (pn532um.pdf, pag. 47) if (irq != Cpu.Pin.GPIO_NONE) { this.irq = new InterruptPort(irq, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow); this.irq.OnInterrupt += irq_OnInterrupt; this.whIrq = new AutoResetEvent(false); } } #region IPN532CommunicationLayer interface ... public bool SendNormalFrame(byte[] frame) { byte[] write = upUtility.ReverseBytes(frame); // send frame this.nssPort.Write(false); Thread.Sleep(2); this.spi.Write(new byte[] { upUtility.ReverseBits(PN532_SPI_DATAWRITE) }); this.spi.Write(write); this.nssPort.Write(true); // using IRQ enabled if (this.irq != null) { // wait for IRQ from PN532 if enabled if (!this.whIrq.WaitOne(PN532.PN532_READY_TIMEOUT, false)) return false; // IRQ signaled, read status byte //if (this.ReadStatus() != PN532.PN532_READY) // return false; } else { long start = DateTime.Now.Ticks; // waiting for status ready while (this.ReadStatus() != PN532.PN532_READY) { // check timeout if ((DateTime.Now.Ticks - start) / PN532.TICKS_PER_MILLISECONDS < PN532.PN532_READY_TIMEOUT) Thread.Sleep(10); else return false; } } // read acknowledge byte[] acknowledge = this.ReadAcknowledge(); // return true or flase if ACK or NACK if ((acknowledge[0] == PN532.ACK_PACKET_CODE[0] && acknowledge[1] == PN532.ACK_PACKET_CODE[1])) return true; else return false; } public byte[] ReadNormalFrame() { // using IRQ enabled if (this.irq != null) { // wait for IRQ from PN532 if enabled if (!this.whIrq.WaitOne(PN532.PN532_READY_TIMEOUT, false)) return null; } else { long start = DateTime.Now.Ticks; // waiting for status ready while (this.ReadStatus() != PN532.PN532_READY) { // check timeout if ((DateTime.Now.Ticks - start) / PN532.TICKS_PER_MILLISECONDS < PN532.PN532_READY_TIMEOUT) Thread.Sleep(10); else return null; } } // dummy bytes from master to force clock a reading from slave byte[] write = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; byte[] read = new byte[PN532.PN532_LCS_OFFSET + 1]; this.nssPort.Write(false); Thread.Sleep(2); // send data reading request and read response this.spi.Write(new byte[] { upUtility.ReverseBits(PN532_SPI_DATAREAD) }); // write 5 (PN532_LCS_OFFSET + 1) dummy bytes to read until LCS byte this.spi.WriteRead(write, read); // extract data len byte len = upUtility.ReverseBits(read[PN532.PN532_LEN_OFFSET]); // create buffer for all frame bytes byte[] frame = new byte[5 + len + 2]; // save first part of received frame (first 5 bytes until LCS) Array.Copy(read, frame, read.Length); write = new byte[len + 2]; // dummy bytes for reading remaining bytes (data + DCS + POSTAMBLE) for (int i = 0; i < write.Length; i++) write[i] = 0xFF; read = new byte[len + 2]; // write dummy bytes to read data, DCS and POSTAMBLE this.spi.WriteRead(write, read); this.nssPort.Write(true); // copy last part of the frame (data + DCS + POSTAMBLE) Array.Copy(read, 0, frame, 5, read.Length); byte[] reversed = upUtility.ReverseBytes(frame); return reversed; } public void WakeUp() { // TODO : SPI need wake up ?? Is there a 2 ms delay after SS goes low..it is alredy weak up ! } #endregion void irq_OnInterrupt(uint data1, uint data2, DateTime time) { this.whIrq.Set(); } /// <summary> /// Read status from PN532 /// </summary> /// <returns>Status byte</returns> private byte ReadStatus() { // prepare byte[] write = { upUtility.ReverseBits(PN532_SPI_STATREAD) }; byte[] read = new byte[1]; this.nssPort.Write(false); Thread.Sleep(2); this.spi.WriteRead(write, read); this.nssPort.Write(true); byte[] status = upUtility.ReverseBytes(read); return status[0]; } /// <summary> /// Read ACK/NACK frame fromPN532 /// </summary> /// <returns>ACK/NACK frame</returns> private byte[] ReadAcknowledge() { // dummy bytes from master to force clock a reading from slave byte[] write = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; byte[] read = new byte[PN532.ACK_PACKET_SIZE]; // send data reading request and read response this.nssPort.Write(false); Thread.Sleep(2); this.spi.Write(new byte[] { upUtility.ReverseBits(PN532_SPI_DATAREAD) }); this.spi.WriteRead(write, read); this.nssPort.Write(true); byte[] acknowledge = upUtility.ReverseBytes(read); // return only ACK/NACK packet code from frame received return new byte[] { acknowledge[3], acknowledge[4] }; } } }
// 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 CompareEqualInt64() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt64 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[ElementCount]; private static Int64[] _data2 = new Int64[ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64> _dataTable; static SimpleBinaryOpTest__CompareEqualInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.CompareEqual( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.CompareEqual( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.CompareEqual( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.CompareEqual), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); var result = Sse41.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.CompareEqual)}<Int64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.InlineDeclaration; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.UseImplicitType; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InlineDeclaration { public partial class CSharpInlineDeclarationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new CSharpInlineDeclarationDiagnosticAnalyzer(), new CSharpInlineDeclarationCodeFixProvider()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariable1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineInNestedCall() { await TestAsync( @"class C { void M() { [|int|] i; if (Foo(int.TryParse(v, out i))) { } } }", @"class C { void M() { if (Foo(int.TryParse(v, out int i))) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableWithConstructor1() { await TestAsync( @"class C { void M() { [|int|] i; if (new C1(v, out i)) { } } }", @"class C { void M() { if (new C1(v, out int i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableMissingWithIndexer1() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (this[out i]) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariableIntoFirstOut2() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } if (int.TryParse(v, out i)) { } } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInCSharp6() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVar1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out var i)) { } } }", options: UseImplicitTypeTests.ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task InlineVariablePreferVarExceptForPredefinedTypes1() { await TestAsync( @"class C { void M(string v) { [|int|] i; if (int.TryParse(v, out i)) { } } }", @"class C { void M(string v) { if (int.TryParse(v, out int i)) { } } }", options: UseImplicitTypeTests.ImplicitTypeButKeepIntrinsics()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableWhenWrittenAfter1() { await TestAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, out i)) { } i = 0; } }", @"class C { void M() { if (int.TryParse(v, out int i)) { } i = 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenWrittenBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i; i = 0; if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWhenReadBetween1() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; M1(i); if (int.TryParse(v, out i)) { } } void M1(int i) { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingWithComplexInitializer() { await TestMissingAsync( @"class C { void M() { [|int|] i = M1(); if (int.TryParse(v, out i)) { } } int M1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInOuterScopeIfNotWrittenOutside() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenAfterInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { if (int.TryParse(v, out i)) { } } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingIfWrittenBetweenInOuterScope() { await TestMissingAsync( @"class C { void M() { [|int|] i = 0; { i = 1; if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonOut() { await TestMissingAsync( @"class C { void M() { [|int|] i; if (int.TryParse(v, i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out this.i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInField2() { await TestMissingAsync( @"class C { [|int|] i; void M() { if (int.TryParse(v, out i)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInNonLocalStatement() { await TestMissingAsync( @"class C { void M() { foreach ([|int|] i in e) { if (int.TryParse(v, out i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestMissingInEmbeddedStatementWithWriteAfterwards() { await TestMissingAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { } i = 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestInEmbeddedStatement() { await TestAsync( @"class C { void M() { [|int|] i; while (true) if (int.TryParse(v, out i)) { i = 1; } } }", @"class C { void M() { while (true) if (int.TryParse(v, out int i)) { i = 1; } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestAvailableInNestedBlock() { await TestAsync( @"class C { void M() { [|int|] i; while (true) { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { while (true) { if (int.TryParse(v, out int i)) { } } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar1() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: UseImplicitTypeTests.ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestOverloadResolutionDoNotUseVar2() { await TestAsync( @"class C { void M() { [|var|] i = 0; if (M2(out i)) { } } void M2(out int i) { } void M2(out string s) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2(out int i) { } void M2(out string s) { } }", options: UseImplicitTypeTests.ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestGenericInferenceDoNotUseVar3() { await TestAsync( @"class C { void M() { [|int|] i; if (M2(out i)) { } } void M2<T>(out T i) { } }", @"class C { void M() { if (M2(out int i)) { } } void M2<T>(out T i) { } }", options: UseImplicitTypeTests.ImplicitTypeEverywhere()); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments1() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments2() { await TestAsync( @"class C { void M() { [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments3() { await TestAsync( @"class C { void M() { // prefix comment [|int|] i; // suffix comment { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { { // prefix comment // suffix comment if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments4() { await TestAsync( @"class C { void M() { int [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments5() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|], j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments6() { await TestAsync( @"class C { void M() { int /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments7() { await TestAsync( @"class C { void M() { int j, /*prefix*/ [|i|] /*suffix*/; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments8() { await TestAsync( @"class C { void M() { // prefix int j, [|i|]; // suffix { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { // prefix int j; // suffix { if (int.TryParse(v, out int i)) { } } } }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineDeclaration)] public async Task TestComments9() { await TestAsync( @"class C { void M() { int /*int comment*/ /*prefix*/ [|i|] /*suffix*/, j; { if (int.TryParse(v, out i)) { } } } }", @"class C { void M() { int /*int comment*/ j; { if (int.TryParse(v, out int /*prefix*/ i /*suffix*/)) { } } } }", compareTokens: false); } } }
/* * 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 OpenMetaverse.StructuredData; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; namespace OpenSim.Framework.Monitoring { /// <summary> /// Static class used to register/deregister/fetch statistics /// </summary> public static class StatsManager { // Subcommand used to list other stats. public const string AllSubCommand = "all"; // Subcommand used to list other stats. public const string ListSubCommand = "list"; // All subcommands public static HashSet<string> SubCommands = new HashSet<string> { AllSubCommand, ListSubCommand }; /// <summary> /// Registered stats categorized by category/container/shortname /// </summary> /// <remarks> /// Do not add or remove directly from this dictionary. /// </remarks> private static SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>> RegisteredStats = new SortedDictionary<string, SortedDictionary<string, SortedDictionary<string, Stat>>>(); private static ReaderWriterLock RegisteredStatsRwLock = new ReaderWriterLock(); // private static AssetStatsCollector assetStats; // private static UserStatsCollector userStats; // private static SimExtraStatsCollector simExtraStats = new SimExtraStatsCollector(); // public static AssetStatsCollector AssetStats { get { return assetStats; } } // public static UserStatsCollector UserStats { get { return userStats; } } public static SimExtraStatsCollector SimExtraStats { get; set; } public static void RegisterConsoleCommands(ICommandConsole console) { console.Commands.AddCommand( "General", false, "stats show", "stats show [list|all|(<category>[.<container>])+", "Show statistical information for this server", "If no final argument is specified then legacy statistics information is currently shown.\n" + "'list' argument will show statistic categories.\n" + "'all' will show all statistics.\n" + "A <category> name will show statistics from that category.\n" + "A <category>.<container> name will show statistics from that category in that container.\n" + "More than one name can be given separated by spaces.\n" + "THIS STATS FACILITY IS EXPERIMENTAL AND DOES NOT YET CONTAIN ALL STATS", HandleShowStatsCommand); console.Commands.AddCommand( "General", false, "show stats", "show stats [list|all|(<category>[.<container>])+", "Alias for 'stats show' command", HandleShowStatsCommand); StatsLogger.RegisterConsoleCommands(console); } public static void HandleShowStatsCommand(string module, string[] cmd) { ICommandConsole con = MainConsole.Instance; if (cmd.Length > 2) { foreach (string name in cmd.Skip(2)) { string[] components = name.Split('.'); string categoryName = components[0]; string containerName = components.Length > 1 ? components[1] : null; string statName = components.Length > 2 ? components[2] : null; if (categoryName == AllSubCommand) { OutputAllStatsToConsole(con); } else if (categoryName == ListSubCommand) { con.Output("Statistic categories available are:"); foreach (string category in RegisteredStats.Keys) con.OutputFormat(" {0}", category); } else { SortedDictionary<string, SortedDictionary<string, Stat>> category; if (!RegisteredStats.TryGetValue(categoryName, out category)) { con.OutputFormat("No such category as {0}", categoryName); } else { if (String.IsNullOrEmpty(containerName)) { OutputCategoryStatsToConsole(con, category); } else { SortedDictionary<string, Stat> container; if (category.TryGetValue(containerName, out container)) { if (String.IsNullOrEmpty(statName)) { OutputContainerStatsToConsole(con, container); } else { Stat stat; if (container.TryGetValue(statName, out stat)) { OutputStatToConsole(con, stat); } else { con.OutputFormat( "No such stat {0} in {1}.{2}", statName, categoryName, containerName); } } } else { con.OutputFormat("No such container {0} in category {1}", containerName, categoryName); } } } } } } else { // Legacy if (SimExtraStats != null) con.Output(SimExtraStats.Report()); else OutputAllStatsToConsole(con); } } public static List<string> GetAllStatsReports() { List<string> reports = new List<string>(); foreach (var category in RegisteredStats.Values) reports.AddRange(GetCategoryStatsReports(category)); return reports; } private static void OutputAllStatsToConsole(ICommandConsole con) { foreach (string report in GetAllStatsReports()) con.Output(report); } private static List<string> GetCategoryStatsReports( SortedDictionary<string, SortedDictionary<string, Stat>> category) { List<string> reports = new List<string>(); foreach (var container in category.Values) reports.AddRange(GetContainerStatsReports(container)); return reports; } private static void OutputCategoryStatsToConsole( ICommandConsole con, SortedDictionary<string, SortedDictionary<string, Stat>> category) { foreach (string report in GetCategoryStatsReports(category)) con.Output(report); } private static List<string> GetContainerStatsReports(SortedDictionary<string, Stat> container) { List<string> reports = new List<string>(); foreach (Stat stat in container.Values) reports.Add(stat.ToConsoleString()); return reports; } private static void OutputContainerStatsToConsole( ICommandConsole con, SortedDictionary<string, Stat> container) { foreach (string report in GetContainerStatsReports(container)) con.Output(report); } private static void OutputStatToConsole(ICommandConsole con, Stat stat) { con.Output(stat.ToConsoleString()); } // Creates an OSDMap of the format: // { categoryName: { // containerName: { // statName: { // "Name": name, // "ShortName": shortName, // ... // }, // statName: { // "Name": name, // "ShortName": shortName, // ... // }, // ... // }, // containerName: { // ... // }, // ... // }, // categoryName: { // ... // }, // ... // } // The passed in parameters will filter the categories, containers and stats returned. If any of the // parameters are either EmptyOrNull or the AllSubCommand value, all of that type will be returned. // Case matters. public static OSDMap GetStatsAsOSDMap(string pCategoryName, string pContainerName, string pStatName) { OSDMap map = new OSDMap(); foreach (string catName in RegisteredStats.Keys) { // Do this category if null spec, "all" subcommand or category name matches passed parameter. // Skip category if none of the above. if (!(String.IsNullOrEmpty(pCategoryName) || pCategoryName == AllSubCommand || pCategoryName == catName)) continue; OSDMap contMap = new OSDMap(); foreach (string contName in RegisteredStats[catName].Keys) { if (!(string.IsNullOrEmpty(pContainerName) || pContainerName == AllSubCommand || pContainerName == contName)) continue; OSDMap statMap = new OSDMap(); SortedDictionary<string, Stat> theStats = RegisteredStats[catName][contName]; foreach (string statName in theStats.Keys) { if (!(String.IsNullOrEmpty(pStatName) || pStatName == AllSubCommand || pStatName == statName)) continue; statMap.Add(statName, theStats[statName].ToOSDMap()); } contMap.Add(contName, statMap); } map.Add(catName, contMap); } return map; } public static Hashtable HandleStatsRequest(Hashtable request) { Hashtable responsedata = new Hashtable(); // string regpath = request["uri"].ToString(); int response_code = 200; string contenttype = "text/json"; string pCategoryName = StatsManager.AllSubCommand; string pContainerName = StatsManager.AllSubCommand; string pStatName = StatsManager.AllSubCommand; if (request.ContainsKey("cat")) pCategoryName = request["cat"].ToString(); if (request.ContainsKey("cont")) pContainerName = request["cat"].ToString(); if (request.ContainsKey("stat")) pStatName = request["cat"].ToString(); string strOut = StatsManager.GetStatsAsOSDMap(pCategoryName, pContainerName, pStatName).ToString(); // If requestor wants it as a callback function, build response as a function rather than just the JSON string. if (request.ContainsKey("callback")) { strOut = request["callback"].ToString() + "(" + strOut + ");"; } // m_log.DebugFormat("{0} StatFetch: uri={1}, cat={2}, cont={3}, stat={4}, resp={5}", // LogHeader, regpath, pCategoryName, pContainerName, pStatName, strOut); responsedata["int_response_code"] = response_code; responsedata["content_type"] = contenttype; responsedata["keepalive"] = false; responsedata["str_response_string"] = strOut; responsedata["access_control_allow_origin"] = "*"; return responsedata; } // /// <summary> // /// Start collecting statistics related to assets. // /// Should only be called once. // /// </summary> // public static AssetStatsCollector StartCollectingAssetStats() // { // assetStats = new AssetStatsCollector(); // // return assetStats; // } // // /// <summary> // /// Start collecting statistics related to users. // /// Should only be called once. // /// </summary> // public static UserStatsCollector StartCollectingUserStats() // { // userStats = new UserStatsCollector(); // // return userStats; // } /// <summary> /// Register a statistic. /// </summary> /// <param name='stat'></param> /// <returns></returns> public static bool RegisterStat(Stat stat) { SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory; SortedDictionary<string, Stat> container = null, newContainer; RegisteredStatsRwLock.AcquireWriterLock(-1); try { // Stat name is not unique across category/container/shortname key. // XXX: For now just return false. This is to avoid problems in regression tests where all tests // in a class are run in the same instance of the VM. if (TryGetStatParents(stat, out category, out container)) return false; // We take a copy-on-write approach here of replacing dictionaries when keys are added or removed. // This means that we don't need to lock or copy them on iteration, which will be a much more // common operation after startup. if (container != null) newContainer = new SortedDictionary<string, Stat>(container); else newContainer = new SortedDictionary<string, Stat>(); if (category != null) newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category); else newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(); newContainer[stat.ShortName] = stat; newCategory[stat.Container] = newContainer; RegisteredStats[stat.Category] = newCategory; } finally { RegisteredStatsRwLock.ReleaseWriterLock(); } return true; } /// <summary> /// Deregister a statistic /// </summary>> /// <param name='stat'></param> /// <returns></returns> public static bool DeregisterStat(Stat stat) { SortedDictionary<string, SortedDictionary<string, Stat>> category = null, newCategory; SortedDictionary<string, Stat> container = null, newContainer; RegisteredStatsRwLock.AcquireWriterLock(-1); try { if (!TryGetStatParents(stat, out category, out container)) return false; newContainer = new SortedDictionary<string, Stat>(container); newContainer.Remove(stat.ShortName); newCategory = new SortedDictionary<string, SortedDictionary<string, Stat>>(category); newCategory.Remove(stat.Container); newCategory[stat.Container] = newContainer; RegisteredStats[stat.Category] = newCategory; return true; } finally { RegisteredStatsRwLock.ReleaseWriterLock(); } } public static bool TryGetStat(string category, string container, string statShortName, out Stat stat) { stat = null; SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats; RegisteredStatsRwLock.AcquireReaderLock(-1); try { if (!TryGetStatsForCategory(category, out categoryStats)) return false; SortedDictionary<string, Stat> containerStats; if (!categoryStats.TryGetValue(container, out containerStats)) return false; return containerStats.TryGetValue(statShortName, out stat); } finally { RegisteredStatsRwLock.ReleaseReaderLock(); } } public static bool TryGetStatsForCategory( string category, out SortedDictionary<string, SortedDictionary<string, Stat>> stats) { RegisteredStatsRwLock.AcquireReaderLock(-1); try { return RegisteredStats.TryGetValue(category, out stats); } finally { RegisteredStatsRwLock.ReleaseReaderLock(); } } /// <summary> /// Get the same stat for each container in a given category. /// </summary> /// <returns> /// The stats if there were any to fetch. Otherwise null. /// </returns> /// <param name='category'></param> /// <param name='statShortName'></param> public static List<Stat> GetStatsFromEachContainer(string category, string statShortName) { SortedDictionary<string, SortedDictionary<string, Stat>> categoryStats; RegisteredStatsRwLock.AcquireReaderLock(-1); try { if (!RegisteredStats.TryGetValue(category, out categoryStats)) return null; List<Stat> stats = null; foreach (SortedDictionary<string, Stat> containerStats in categoryStats.Values) { if (containerStats.ContainsKey(statShortName)) { if (stats == null) stats = new List<Stat>(); stats.Add(containerStats[statShortName]); } } return stats; } finally { RegisteredStatsRwLock.ReleaseReaderLock(); } } public static bool TryGetStatParents( Stat stat, out SortedDictionary<string, SortedDictionary<string, Stat>> category, out SortedDictionary<string, Stat> container) { category = null; container = null; RegisteredStatsRwLock.AcquireReaderLock(-1); try { if (RegisteredStats.TryGetValue(stat.Category, out category)) { if (category.TryGetValue(stat.Container, out container)) { if (container.ContainsKey(stat.ShortName)) return true; } } } finally { RegisteredStatsRwLock.ReleaseReaderLock(); } return false; } public static void RecordStats() { RegisteredStatsRwLock.AcquireReaderLock(-1); try { foreach (SortedDictionary<string, SortedDictionary<string, Stat>> category in RegisteredStats.Values) { foreach (SortedDictionary<string, Stat> container in category.Values) { foreach (Stat stat in container.Values) { if (stat.MeasuresOfInterest != MeasuresOfInterest.None) stat.RecordValue(); } } } } finally { RegisteredStatsRwLock.ReleaseReaderLock(); } } } /// <summary> /// Stat type. /// </summary> /// <remarks> /// A push stat is one which is continually updated and so it's value can simply by read. /// A pull stat is one where reading the value triggers a collection method - the stat is not continually updated. /// </remarks> public enum StatType { Push, Pull } /// <summary> /// Measures of interest for this stat. /// </summary> [Flags] public enum MeasuresOfInterest { None, AverageChangeOverTime } /// <summary> /// Verbosity of stat. /// </summary> /// <remarks> /// Info will always be displayed. /// </remarks> public enum StatVerbosity { Debug, Info } }
// // ServiceManager.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.MediaProfiles; using Banshee.Sources; using Banshee.Database; using Banshee.MediaEngine; using Banshee.PlaybackController; using Banshee.Library; using Banshee.Hardware; namespace Banshee.ServiceStack { public static class ServiceManager { private static Dictionary<string, IService> services = new Dictionary<string, IService> (); private static Dictionary<string, IExtensionService> extension_services = new Dictionary<string, IExtensionService> (); private static Stack<IService> dispose_services = new Stack<IService> (); private static List<Type> service_types = new List<Type> (); private static ExtensionNodeList extension_nodes; private static bool is_initialized = false; private static readonly object self_mutex = new object (); public static event EventHandler StartupBegin; public static event EventHandler StartupFinished; public static event ServiceStartedHandler ServiceStarted; public static void Initialize () { Application.ClientStarted += OnClientStarted; } public static void InitializeAddins () { AddinManager.Initialize (ApplicationContext.CommandLine.Contains ("uninstalled") ? "." : Paths.ApplicationData); IProgressStatus monitor = ApplicationContext.CommandLine.Contains ("debug-addins") ? new ConsoleProgressStatus (true) : null; if (ApplicationContext.Debugging) { AddinManager.Registry.Rebuild (monitor); } else { AddinManager.Registry.Update (monitor); } } public static void RegisterAddinServices () { extension_nodes = AddinManager.GetExtensionNodes ("/Banshee/ServiceManager/Service"); } public static void RegisterDefaultServices () { RegisterService<DBusServiceManager> (); RegisterService<DBusCommandService> (); RegisterService<BansheeDbConnection> (); RegisterService<Banshee.Preferences.PreferenceService> (); RegisterService<SourceManager> (); RegisterService<MediaProfileManager> (); RegisterService<PlayerEngineService> (); RegisterService<TranscoderService> (); RegisterService<PlaybackControllerService> (); RegisterService<ImportSourceManager> (); RegisterService<LibraryImportManager> (); RegisterService<JobScheduler> (); RegisterService<Banshee.Hardware.HardwareManager> (); RegisterService<Banshee.Collection.Indexer.CollectionIndexerService> (); RegisterService<Banshee.Metadata.SaveTrackMetadataService> (); } public static void DefaultInitialize () { Initialize (); InitializeAddins (); RegisterDefaultServices (); RegisterAddinServices (); } private static void OnClientStarted (Client client) { DelayedInitialize (); } public static void Run() { lock (self_mutex) { OnStartupBegin (); uint cumulative_timer_id = Log.InformationTimerStart (); foreach (Type type in service_types) { RegisterService (type); } if (extension_nodes != null) { foreach (TypeExtensionNode node in extension_nodes) { StartExtension (node); } } if (AddinManager.IsInitialized) { AddinManager.AddExtensionNodeHandler ("/Banshee/ServiceManager/Service", OnExtensionChanged); } is_initialized = true; Log.InformationTimerPrint (cumulative_timer_id, "All services are started {0}"); OnStartupFinished (); } } private static IService RegisterService (Type type) { IService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IService)Activator.CreateInstance (type); RegisterService (service); Log.DebugTimerPrint (timer_id, String.Format ( "Core service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); if (service is IDisposable) { dispose_services.Push (service); } if (service is IInitializeService) { ((IInitializeService)service).Initialize (); } return service; } catch (Exception e) { if (service is IRequiredService) { Log.ErrorFormat ("Error initializing required service {0}", service == null ? type.ToString () : service.ServiceName, false); throw; } Log.Warning (String.Format ("Service `{0}' not started: {1}", type.FullName, e.InnerException != null ? e.InnerException.Message : e.Message)); Log.Exception (e.InnerException ?? e); } return null; } private static void StartExtension (TypeExtensionNode node) { if (extension_services.ContainsKey (node.Path)) { return; } IExtensionService service = null; try { uint timer_id = Log.DebugTimerStart (); service = (IExtensionService)node.CreateInstance (typeof (IExtensionService)); service.Initialize (); RegisterService (service); DelayedInitialize (service); Log.DebugTimerPrint (timer_id, String.Format ( "Extension service started ({0}, {{0}})", service.ServiceName)); OnServiceStarted (service); extension_services.Add (node.Path, service); dispose_services.Push (service); } catch (Exception e) { Log.Exception (e.InnerException ?? e); Log.Warning (String.Format ("Extension `{0}' not started: {1}", service == null ? node.Path : service.GetType ().FullName, e.Message)); } } private static void OnExtensionChanged (object o, ExtensionNodeEventArgs args) { lock (self_mutex) { TypeExtensionNode node = (TypeExtensionNode)args.ExtensionNode; if (args.Change == ExtensionChange.Add) { StartExtension (node); } else if (args.Change == ExtensionChange.Remove && extension_services.ContainsKey (node.Path)) { IExtensionService service = extension_services[node.Path]; extension_services.Remove (node.Path); services.Remove (service.ServiceName); ((IDisposable)service).Dispose (); Log.DebugFormat ("Extension service disposed ({0})", service.ServiceName); // Rebuild the dispose stack excluding the extension service IService [] tmp_services = new IService[dispose_services.Count - 1]; int count = tmp_services.Length; foreach (IService tmp_service in dispose_services) { if (tmp_service != service) { tmp_services[--count] = tmp_service; } } dispose_services = new Stack<IService> (tmp_services); } } } private static bool delayed_initialized, have_client; private static void DelayedInitialize () { lock (self_mutex) { if (!delayed_initialized) { have_client = true; foreach (IService service in services.Values) { DelayedInitialize (service); } delayed_initialized = true; } } } private static void DelayedInitialize (IService service) { try { if (have_client && service is IDelayedInitializeService) { Log.DebugFormat ("Delayed Initializating {0}", service); ((IDelayedInitializeService)service).DelayedInitialize (); } } catch (Exception e) { Log.Exception (e.InnerException ?? e); Log.Warning (String.Format ("Service `{0}' not initialized: {1}", service.GetType ().FullName, e.Message)); } } public static void Shutdown () { lock (self_mutex) { while (dispose_services.Count > 0) { IService service = dispose_services.Pop (); try { ((IDisposable)service).Dispose (); Log.DebugFormat ("Service disposed ({0})", service.ServiceName); } catch (Exception e) { Log.Exception (String.Format ("Service disposal ({0}) threw an exception", service.ServiceName), e); } } services.Clear (); } } public static void RegisterService (IService service) { lock (self_mutex) { services.Add (service.ServiceName, service); if(service is IDBusExportable) { DBusServiceManager.RegisterObject ((IDBusExportable)service); } } } public static void RegisterService<T> () where T : IService { lock (self_mutex) { if (is_initialized) { RegisterService (Activator.CreateInstance <T> ()); } else { service_types.Add (typeof (T)); } } } public static bool Contains (string serviceName) { lock (self_mutex) { return services.ContainsKey (serviceName); } } public static bool Contains<T> () where T : class, IService { return Contains (typeof (T).Name); } public static IService Get (string serviceName) { if (services.ContainsKey (serviceName)) { return services[serviceName]; } return null; } public static T Get<T> (string serviceName) where T : class, IService { return Get (serviceName) as T; } public static T Get<T> () where T : class, IService { Type type = typeof (T); T service = Get (type.Name) as T; if (service == null && type.GetInterface ("Banshee.ServiceStack.IRegisterOnDemandService") != null) { return RegisterService (type) as T; } return service; } private static void OnStartupBegin () { EventHandler handler = StartupBegin; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnStartupFinished () { EventHandler handler = StartupFinished; if (handler != null) { handler (null, EventArgs.Empty); } } private static void OnServiceStarted (IService service) { ServiceStartedHandler handler = ServiceStarted; if (handler != null) { handler (new ServiceStartedArgs (service)); } } public static int StartupServiceCount { get { return service_types.Count + (extension_nodes == null ? 0 : extension_nodes.Count) + 1; } } public static int ServiceCount { get { return services.Count; } } public static bool IsInitialized { get { return is_initialized; } } public static DBusServiceManager DBusServiceManager { get { return Get<DBusServiceManager> (); } } public static BansheeDbConnection DbConnection { get { return (BansheeDbConnection)Get ("DbConnection"); } } public static MediaProfileManager MediaProfileManager { get { return Get<MediaProfileManager> (); } } public static SourceManager SourceManager { get { return (SourceManager)Get ("SourceManager"); } } public static JobScheduler JobScheduler { get { return (JobScheduler)Get ("JobScheduler"); } } public static PlayerEngineService PlayerEngine { get { return (PlayerEngineService)Get ("PlayerEngine"); } } public static PlaybackControllerService PlaybackController { get { return (PlaybackControllerService)Get ("PlaybackController"); } } public static HardwareManager HardwareManager { get { return Get<HardwareManager> (); } } } }
using System; using Org.BouncyCastle.Asn1.X509; namespace Org.BouncyCastle.Asn1.Cmp { public class PkiHeaderBuilder { private DerInteger pvno; private GeneralName sender; private GeneralName recipient; private DerGeneralizedTime messageTime; private AlgorithmIdentifier protectionAlg; private Asn1OctetString senderKID; // KeyIdentifier private Asn1OctetString recipKID; // KeyIdentifier private Asn1OctetString transactionID; private Asn1OctetString senderNonce; private Asn1OctetString recipNonce; private PkiFreeText freeText; private Asn1Sequence generalInfo; public PkiHeaderBuilder( int pvno, GeneralName sender, GeneralName recipient) : this(new DerInteger(pvno), sender, recipient) { } private PkiHeaderBuilder( DerInteger pvno, GeneralName sender, GeneralName recipient) { this.pvno = pvno; this.sender = sender; this.recipient = recipient; } public virtual PkiHeaderBuilder SetMessageTime(DerGeneralizedTime time) { messageTime = time; return this; } public virtual PkiHeaderBuilder SetProtectionAlg(AlgorithmIdentifier aid) { protectionAlg = aid; return this; } public virtual PkiHeaderBuilder SetSenderKID(byte[] kid) { return SetSenderKID(new DerOctetString(kid)); } public virtual PkiHeaderBuilder SetSenderKID(Asn1OctetString kid) { senderKID = kid; return this; } public virtual PkiHeaderBuilder SetRecipKID(byte[] kid) { return SetRecipKID(new DerOctetString(kid)); } public virtual PkiHeaderBuilder SetRecipKID(DerOctetString kid) { recipKID = kid; return this; } public virtual PkiHeaderBuilder SetTransactionID(byte[] tid) { return SetTransactionID(new DerOctetString(tid)); } public virtual PkiHeaderBuilder SetTransactionID(Asn1OctetString tid) { transactionID = tid; return this; } public virtual PkiHeaderBuilder SetSenderNonce(byte[] nonce) { return SetSenderNonce(new DerOctetString(nonce)); } public virtual PkiHeaderBuilder SetSenderNonce(Asn1OctetString nonce) { senderNonce = nonce; return this; } public virtual PkiHeaderBuilder SetRecipNonce(byte[] nonce) { return SetRecipNonce(new DerOctetString(nonce)); } public virtual PkiHeaderBuilder SetRecipNonce(Asn1OctetString nonce) { recipNonce = nonce; return this; } public virtual PkiHeaderBuilder SetFreeText(PkiFreeText text) { freeText = text; return this; } public virtual PkiHeaderBuilder SetGeneralInfo(InfoTypeAndValue genInfo) { return SetGeneralInfo(MakeGeneralInfoSeq(genInfo)); } public virtual PkiHeaderBuilder SetGeneralInfo(InfoTypeAndValue[] genInfos) { return SetGeneralInfo(MakeGeneralInfoSeq(genInfos)); } public virtual PkiHeaderBuilder SetGeneralInfo(Asn1Sequence seqOfInfoTypeAndValue) { generalInfo = seqOfInfoTypeAndValue; return this; } private static Asn1Sequence MakeGeneralInfoSeq( InfoTypeAndValue generalInfo) { return new DerSequence(generalInfo); } private static Asn1Sequence MakeGeneralInfoSeq( InfoTypeAndValue[] generalInfos) { Asn1Sequence genInfoSeq = null; if (generalInfos != null) { Asn1EncodableVector v = new Asn1EncodableVector(); for (int i = 0; i < generalInfos.Length; ++i) { v.Add(generalInfos[i]); } genInfoSeq = new DerSequence(v); } return genInfoSeq; } /** * <pre> * PKIHeader ::= SEQUENCE { * pvno INTEGER { cmp1999(1), cmp2000(2) }, * sender GeneralName, * -- identifies the sender * recipient GeneralName, * -- identifies the intended recipient * messageTime [0] GeneralizedTime OPTIONAL, * -- time of production of this message (used when sender * -- believes that the transport will be "suitable"; i.e., * -- that the time will still be meaningful upon receipt) * protectionAlg [1] AlgorithmIdentifier OPTIONAL, * -- algorithm used for calculation of protection bits * senderKID [2] KeyIdentifier OPTIONAL, * recipKID [3] KeyIdentifier OPTIONAL, * -- to identify specific keys used for protection * transactionID [4] OCTET STRING OPTIONAL, * -- identifies the transaction; i.e., this will be the same in * -- corresponding request, response, certConf, and PKIConf * -- messages * senderNonce [5] OCTET STRING OPTIONAL, * recipNonce [6] OCTET STRING OPTIONAL, * -- nonces used to provide replay protection, senderNonce * -- is inserted by the creator of this message; recipNonce * -- is a nonce previously inserted in a related message by * -- the intended recipient of this message * freeText [7] PKIFreeText OPTIONAL, * -- this may be used to indicate context-specific instructions * -- (this field is intended for human consumption) * generalInfo [8] SEQUENCE SIZE (1..MAX) OF * InfoTypeAndValue OPTIONAL * -- this may be used to convey context-specific information * -- (this field not primarily intended for human consumption) * } * </pre> * @return a basic ASN.1 object representation. */ public virtual PkiHeader Build() { Asn1EncodableVector v = new Asn1EncodableVector(pvno, sender, recipient); AddOptional(v, 0, messageTime); AddOptional(v, 1, protectionAlg); AddOptional(v, 2, senderKID); AddOptional(v, 3, recipKID); AddOptional(v, 4, transactionID); AddOptional(v, 5, senderNonce); AddOptional(v, 6, recipNonce); AddOptional(v, 7, freeText); AddOptional(v, 8, generalInfo); messageTime = null; protectionAlg = null; senderKID = null; recipKID = null; transactionID = null; senderNonce = null; recipNonce = null; freeText = null; generalInfo = null; return PkiHeader.GetInstance(new DerSequence(v)); } private void AddOptional(Asn1EncodableVector v, int tagNo, Asn1Encodable obj) { if (obj != null) { v.Add(new DerTaggedObject(true, tagNo, obj)); } } } }
using WixSharp; using WixSharp.UI.Forms; namespace WixSharpSetup.Dialogs { partial class WelcomeDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.imgPanel = new System.Windows.Forms.Panel(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.image = new System.Windows.Forms.PictureBox(); this.bottomPanel = new System.Windows.Forms.Panel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.back = new System.Windows.Forms.Button(); this.next = new System.Windows.Forms.Button(); this.cancel = new System.Windows.Forms.Button(); this.bottomBorder = new System.Windows.Forms.Panel(); this.textPanel = new System.Windows.Forms.Panel(); this.imgPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.image)).BeginInit(); this.bottomPanel.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this.textPanel.SuspendLayout(); this.SuspendLayout(); // // panel2 // this.imgPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.imgPanel.Controls.Add(this.textPanel); this.imgPanel.Controls.Add(this.image); this.imgPanel.Location = new System.Drawing.Point(0, 0); this.imgPanel.Name = "panel2"; this.imgPanel.Size = new System.Drawing.Size(494, 312); this.imgPanel.TabIndex = 4; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(3, 14); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(317, 61); this.label1.TabIndex = 2; this.label1.Text = "[WelcomeDlgTitle]"; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label2.Location = new System.Drawing.Point(4, 75); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(316, 209); this.label2.TabIndex = 3; this.label2.Text = "[WelcomeDlgDescription]"; // // image // this.image.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.image.BackColor = System.Drawing.Color.White; this.image.Location = new System.Drawing.Point(0, 0); this.image.Name = "image"; this.image.Size = new System.Drawing.Size(156, 312); this.image.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.image.TabIndex = 0; this.image.TabStop = false; // // bottomPanel // this.bottomPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bottomPanel.BackColor = System.Drawing.SystemColors.Control; this.bottomPanel.Controls.Add(this.bottomBorder); this.bottomPanel.Controls.Add(this.tableLayoutPanel1); this.bottomPanel.Location = new System.Drawing.Point(0, 312); this.bottomPanel.Name = "bottomPanel"; this.bottomPanel.Size = new System.Drawing.Size(494, 49); this.bottomPanel.TabIndex = 1; // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 5; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 14F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel1.Controls.Add(this.back, 1, 0); this.tableLayoutPanel1.Controls.Add(this.next, 2, 0); this.tableLayoutPanel1.Controls.Add(this.cancel, 4, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 5); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 1; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 41); this.tableLayoutPanel1.TabIndex = 6; // // back // this.back.Anchor = System.Windows.Forms.AnchorStyles.Right; this.back.AutoSize = true; this.back.Enabled = false; this.back.Location = new System.Drawing.Point(222, 9); this.back.MinimumSize = new System.Drawing.Size(75, 0); this.back.Name = "back"; this.back.Size = new System.Drawing.Size(77, 23); this.back.TabIndex = 0; this.back.Text = "[WixUIBack]"; this.back.UseVisualStyleBackColor = true; this.back.Click += new System.EventHandler(this.back_Click); // // next // this.next.Anchor = System.Windows.Forms.AnchorStyles.Right; this.next.AutoSize = true; this.next.Location = new System.Drawing.Point(305, 9); this.next.MinimumSize = new System.Drawing.Size(75, 0); this.next.Name = "next"; this.next.Size = new System.Drawing.Size(77, 23); this.next.TabIndex = 0; this.next.Text = "[WixUINext]"; this.next.UseVisualStyleBackColor = true; this.next.Click += new System.EventHandler(this.next_Click); // // cancel // this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right; this.cancel.AutoSize = true; this.cancel.Location = new System.Drawing.Point(402, 9); this.cancel.MinimumSize = new System.Drawing.Size(75, 0); this.cancel.Name = "cancel"; this.cancel.Size = new System.Drawing.Size(86, 23); this.cancel.TabIndex = 0; this.cancel.Text = "[WixUICancel]"; this.cancel.UseVisualStyleBackColor = true; this.cancel.Click += new System.EventHandler(this.cancel_Click); // // bottomBorder // this.bottomBorder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.bottomBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.bottomBorder.Location = new System.Drawing.Point(0, 0); this.bottomBorder.Name = "bottomBorder"; this.bottomBorder.Size = new System.Drawing.Size(494, 1); this.bottomBorder.TabIndex = 5; // // panel // this.textPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textPanel.Controls.Add(this.label1); this.textPanel.Controls.Add(this.label2); this.textPanel.Location = new System.Drawing.Point(162, 12); this.textPanel.Name = "panel"; this.textPanel.Size = new System.Drawing.Size(326, 294); this.textPanel.TabIndex = 4; // // WelcomeDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(494, 361); this.Controls.Add(this.imgPanel); this.Controls.Add(this.bottomPanel); this.Name = "WelcomeDialog"; this.Text = "[WelcomeDlg_Title]"; this.Load += new System.EventHandler(this.WelcomeDialog_Load); this.imgPanel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.image)).EndInit(); this.bottomPanel.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.textPanel.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox image; private System.Windows.Forms.Panel bottomPanel; private System.Windows.Forms.Button back; private System.Windows.Forms.Button next; private System.Windows.Forms.Button cancel; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel imgPanel; private System.Windows.Forms.Panel bottomBorder; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Panel textPanel; } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Census Class Sizes Validation Data Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SCEN_CLVDataSet : EduHubDataSet<SCEN_CLV> { /// <inheritdoc /> public override string Name { get { return "SCEN_CLV"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return false; } } internal SCEN_CLVDataSet(EduHubContext Context) : base(Context) { Index_ID = new Lazy<Dictionary<int, SCEN_CLV>>(() => this.ToDictionary(i => i.ID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SCEN_CLV" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SCEN_CLV" /> fields for each CSV column header</returns> internal override Action<SCEN_CLV, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SCEN_CLV, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "ID": mapper[i] = (e, v) => e.ID = int.Parse(v); break; case "CLASSCODE": mapper[i] = (e, v) => e.CLASSCODE = v; break; case "ID_CLASSVALIDATIONTYPE": mapper[i] = (e, v) => e.ID_CLASSVALIDATIONTYPE = v == null ? (short?)null : short.Parse(v); break; case "STATUS": mapper[i] = (e, v) => e.STATUS = v; break; case "CREATEUSER": mapper[i] = (e, v) => e.CREATEUSER = v; break; case "CREATED": mapper[i] = (e, v) => e.CREATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LUPDATEUSER": mapper[i] = (e, v) => e.LUPDATEUSER = v; break; case "LUPDATED": mapper[i] = (e, v) => e.LUPDATED = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SCEN_CLV" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SCEN_CLV" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SCEN_CLV" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SCEN_CLV}"/> of entities</returns> internal override IEnumerable<SCEN_CLV> ApplyDeltaEntities(IEnumerable<SCEN_CLV> Entities, List<SCEN_CLV> DeltaEntities) { HashSet<int> Index_ID = new HashSet<int>(DeltaEntities.Select(i => i.ID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ID; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_ID.Remove(entity.ID); if (entity.ID.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, SCEN_CLV>> Index_ID; #endregion #region Index Methods /// <summary> /// Find SCEN_CLV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_CLV</param> /// <returns>Related SCEN_CLV entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_CLV FindByID(int ID) { return Index_ID.Value[ID]; } /// <summary> /// Attempt to find SCEN_CLV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_CLV</param> /// <param name="Value">Related SCEN_CLV entity</param> /// <returns>True if the related SCEN_CLV entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByID(int ID, out SCEN_CLV Value) { return Index_ID.Value.TryGetValue(ID, out Value); } /// <summary> /// Attempt to find SCEN_CLV by ID field /// </summary> /// <param name="ID">ID value used to find SCEN_CLV</param> /// <returns>Related SCEN_CLV entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SCEN_CLV TryFindByID(int ID) { SCEN_CLV value; if (Index_ID.Value.TryGetValue(ID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SCEN_CLV table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SCEN_CLV]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SCEN_CLV]( [ID] int IDENTITY NOT NULL, [CLASSCODE] varchar(5) NULL, [ID_CLASSVALIDATIONTYPE] smallint NULL, [STATUS] varchar(1) NULL, [CREATEUSER] varchar(128) NULL, [CREATED] datetime NULL, [LUPDATEUSER] varchar(128) NULL, [LUPDATED] datetime NULL, CONSTRAINT [SCEN_CLV_Index_ID] PRIMARY KEY CLUSTERED ( [ID] ASC ) ); END"); } /// <summary> /// Returns null as <see cref="SCEN_CLVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns null as <see cref="SCEN_CLVDataSet"/> has no non-clustered indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>null</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return null; } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SCEN_CLV"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SCEN_CLV"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SCEN_CLV> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_ID = new List<int>(); foreach (var entity in Entities) { Index_ID.Add(entity.ID); } builder.AppendLine("DELETE [dbo].[SCEN_CLV] WHERE"); // Index_ID builder.Append("[ID] IN ("); for (int index = 0; index < Index_ID.Count; index++) { if (index != 0) builder.Append(", "); // ID var parameterID = $"@p{parameterIndex++}"; builder.Append(parameterID); command.Parameters.Add(parameterID, SqlDbType.Int).Value = Index_ID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_CLV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_CLV data set</returns> public override EduHubDataSetDataReader<SCEN_CLV> GetDataSetDataReader() { return new SCEN_CLVDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SCEN_CLV data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SCEN_CLV data set</returns> public override EduHubDataSetDataReader<SCEN_CLV> GetDataSetDataReader(List<SCEN_CLV> Entities) { return new SCEN_CLVDataReader(new EduHubDataSetLoadedReader<SCEN_CLV>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SCEN_CLVDataReader : EduHubDataSetDataReader<SCEN_CLV> { public SCEN_CLVDataReader(IEduHubDataSetReader<SCEN_CLV> Reader) : base (Reader) { } public override int FieldCount { get { return 8; } } public override object GetValue(int i) { switch (i) { case 0: // ID return Current.ID; case 1: // CLASSCODE return Current.CLASSCODE; case 2: // ID_CLASSVALIDATIONTYPE return Current.ID_CLASSVALIDATIONTYPE; case 3: // STATUS return Current.STATUS; case 4: // CREATEUSER return Current.CREATEUSER; case 5: // CREATED return Current.CREATED; case 6: // LUPDATEUSER return Current.LUPDATEUSER; case 7: // LUPDATED return Current.LUPDATED; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // CLASSCODE return Current.CLASSCODE == null; case 2: // ID_CLASSVALIDATIONTYPE return Current.ID_CLASSVALIDATIONTYPE == null; case 3: // STATUS return Current.STATUS == null; case 4: // CREATEUSER return Current.CREATEUSER == null; case 5: // CREATED return Current.CREATED == null; case 6: // LUPDATEUSER return Current.LUPDATEUSER == null; case 7: // LUPDATED return Current.LUPDATED == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // ID return "ID"; case 1: // CLASSCODE return "CLASSCODE"; case 2: // ID_CLASSVALIDATIONTYPE return "ID_CLASSVALIDATIONTYPE"; case 3: // STATUS return "STATUS"; case 4: // CREATEUSER return "CREATEUSER"; case 5: // CREATED return "CREATED"; case 6: // LUPDATEUSER return "LUPDATEUSER"; case 7: // LUPDATED return "LUPDATED"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "ID": return 0; case "CLASSCODE": return 1; case "ID_CLASSVALIDATIONTYPE": return 2; case "STATUS": return 3; case "CREATEUSER": return 4; case "CREATED": return 5; case "LUPDATEUSER": return 6; case "LUPDATED": return 7; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Net.NetworkInformation; using Couchbase.Lite.Util; using System.Threading; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Linq; using System.Net.Http; #if __ANDROID__ using Android.App; using Android.Net; using Android.Content; using Android.Webkit; #endif #if NET_3_5 using WebRequest = System.Net.Couchbase.WebRequest; using HttpWebRequest = System.Net.Couchbase.HttpWebRequest; using HttpWebResponse = System.Net.Couchbase.HttpWebResponse; using WebException = System.Net.Couchbase.WebException; #endif namespace Couchbase.Lite { // NOTE: The Android specific #ifdefs are in here solely // to work around Xamarin.Android bug // https://bugzilla.xamarin.com/show_bug.cgi?id=1969 // NOTE: The issue above was fixed as of Xamarin.Android 4.18, but seems // to have regressed in 4.20 /// <summary> /// This uses the NetworkAvailability API to listen for network reachability /// change events and fires off changes internally. /// </summary> internal sealed class NetworkReachabilityManager : INetworkReachabilityManager { private int _startCount = 0; private const string TAG = "NetworkReachabilityManager"; public bool CanReach(string remoteUri) { HttpWebRequest request = WebRequest.CreateHttp(remoteUri); request.AllowWriteStreamBuffering = true; request.Timeout = 5000; request.Method = "GET"; try { using(var response = (HttpWebResponse)request.GetResponse()) { return true; //We only care that the server responded } } catch(Exception e) { var we = e as WebException; if(we != null && we.Status == WebExceptionStatus.ProtocolError) { return true; //Getting an HTTP error technically means we can connect } Log.I(TAG, "Didn't get successful connection to {0}", remoteUri); Log.D(TAG, " Cause: ", e); return false; } } #if __ANDROID__ private class AndroidNetworkChangeReceiver : BroadcastReceiver { const string Tag = "AndroidNetworkChangeReceiver"; readonly private Action<NetworkReachabilityStatus> _callback; object lockObject; private volatile Boolean _ignoreNotifications; private NetworkReachabilityStatus _lastStatus; public AndroidNetworkChangeReceiver(Action<NetworkReachabilityStatus> callback) { _callback = callback; _ignoreNotifications = true; lockObject = new object(); } public override void OnReceive(Context context, Intent intent) { Log.D(Tag + ".OnReceive", "Received intent: {0}", intent.ToString()); if (_ignoreNotifications) { Log.D(Tag + ".OnReceive", "Ignoring received intent: {0}", intent.ToString()); _ignoreNotifications = false; return; } Log.D(Tag + ".OnReceive", "Received intent: {0}", intent.ToString()); var manager = (ConnectivityManager)context.GetSystemService(Context.ConnectivityService); var networkInfo = manager.ActiveNetworkInfo; var status = networkInfo == null || !networkInfo.IsConnected ? NetworkReachabilityStatus.Unreachable : NetworkReachabilityStatus.Reachable; if (!status.Equals(_lastStatus)) { _callback(status); } lock(lockObject) { _lastStatus = status; } } public void EnableListening() { _ignoreNotifications = false; } public void DisableListening() { _ignoreNotifications = true; } } private AndroidNetworkChangeReceiver _receiver; #endif #region INetworkReachabilityManager implementation public event EventHandler<NetworkReachabilityChangeEventArgs> StatusChanged { add { _statusChanged = (EventHandler<NetworkReachabilityChangeEventArgs>)Delegate.Combine(_statusChanged, value); } remove { _statusChanged = (EventHandler<NetworkReachabilityChangeEventArgs>)Delegate.Remove(_statusChanged, value); } } private EventHandler<NetworkReachabilityChangeEventArgs> _statusChanged; /// <summary>This method starts listening for network connectivity state changes.</summary> /// <remarks>This method starts listening for network connectivity state changes.</remarks> public void StartListening() { Interlocked.Increment(ref _startCount); #if __ANDROID__ if (_receiver != null) { return; // We only need one handler. } var intent = new IntentFilter(ConnectivityManager.ConnectivityAction); _receiver = new AndroidNetworkChangeReceiver(InvokeNetworkChangeEvent); Application.Context.RegisterReceiver(_receiver, intent); #else if (_isListening) { return; } NetworkChange.NetworkAvailabilityChanged += OnNetworkChange; _isListening = true; #endif } /// <summary>This method stops this class from listening for network changes.</summary> /// <remarks>This method stops this class from listening for network changes.</remarks> public void StopListening() { var count = Interlocked.Decrement(ref _startCount); if (count > 0) { return; } if (count < 0) { Log.W(TAG, "Too many calls to INetworkReachabilityManager.StopListening()"); Interlocked.Exchange(ref _startCount, 0); return; } #if __ANDROID__ if (_receiver == null) { return; } _receiver.DisableListening(); Application.Context.UnregisterReceiver(_receiver); _receiver = null; #else if (!_isListening) { return; } NetworkChange.NetworkAvailabilityChanged -= OnNetworkChange; #endif } #endregion #region Private Members #if !__ANDROID__ private volatile Boolean _isListening; #endif #endregion /// <summary>Notify listeners that the network is now reachable/unreachable.</summary> internal void OnNetworkChange(Object sender, NetworkAvailabilityEventArgs args) { var status = args.IsAvailable ? NetworkReachabilityStatus.Reachable : NetworkReachabilityStatus.Unreachable; InvokeNetworkChangeEvent(status); } void InvokeNetworkChangeEvent(NetworkReachabilityStatus status) { var evt = _statusChanged; if (evt == null) { return; } var eventArgs = new NetworkReachabilityChangeEventArgs(status); evt(this, eventArgs); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.BinaryAuthorization.V1Beta1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedBinauthzManagementServiceV1Beta1ClientSnippets { /// <summary>Snippet for GetPolicy</summary> public void GetPolicyRequestObject() { // Snippet: GetPolicy(GetPolicyRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; // Make the request Policy response = binauthzManagementServiceV1Beta1Client.GetPolicy(request); // End snippet } /// <summary>Snippet for GetPolicyAsync</summary> public async Task GetPolicyRequestObjectAsync() { // Snippet: GetPolicyAsync(GetPolicyRequest, CallSettings) // Additional: GetPolicyAsync(GetPolicyRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) GetPolicyRequest request = new GetPolicyRequest { PolicyName = PolicyName.FromProject("[PROJECT]"), }; // Make the request Policy response = await binauthzManagementServiceV1Beta1Client.GetPolicyAsync(request); // End snippet } /// <summary>Snippet for GetPolicy</summary> public void GetPolicy() { // Snippet: GetPolicy(string, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/policy"; // Make the request Policy response = binauthzManagementServiceV1Beta1Client.GetPolicy(name); // End snippet } /// <summary>Snippet for GetPolicyAsync</summary> public async Task GetPolicyAsync() { // Snippet: GetPolicyAsync(string, CallSettings) // Additional: GetPolicyAsync(string, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/policy"; // Make the request Policy response = await binauthzManagementServiceV1Beta1Client.GetPolicyAsync(name); // End snippet } /// <summary>Snippet for GetPolicy</summary> public void GetPolicyResourceNames() { // Snippet: GetPolicy(PolicyName, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) PolicyName name = PolicyName.FromProject("[PROJECT]"); // Make the request Policy response = binauthzManagementServiceV1Beta1Client.GetPolicy(name); // End snippet } /// <summary>Snippet for GetPolicyAsync</summary> public async Task GetPolicyResourceNamesAsync() { // Snippet: GetPolicyAsync(PolicyName, CallSettings) // Additional: GetPolicyAsync(PolicyName, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) PolicyName name = PolicyName.FromProject("[PROJECT]"); // Make the request Policy response = await binauthzManagementServiceV1Beta1Client.GetPolicyAsync(name); // End snippet } /// <summary>Snippet for UpdatePolicy</summary> public void UpdatePolicyRequestObject() { // Snippet: UpdatePolicy(UpdatePolicyRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; // Make the request Policy response = binauthzManagementServiceV1Beta1Client.UpdatePolicy(request); // End snippet } /// <summary>Snippet for UpdatePolicyAsync</summary> public async Task UpdatePolicyRequestObjectAsync() { // Snippet: UpdatePolicyAsync(UpdatePolicyRequest, CallSettings) // Additional: UpdatePolicyAsync(UpdatePolicyRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) UpdatePolicyRequest request = new UpdatePolicyRequest { Policy = new Policy(), }; // Make the request Policy response = await binauthzManagementServiceV1Beta1Client.UpdatePolicyAsync(request); // End snippet } /// <summary>Snippet for UpdatePolicy</summary> public void UpdatePolicy() { // Snippet: UpdatePolicy(Policy, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) Policy policy = new Policy(); // Make the request Policy response = binauthzManagementServiceV1Beta1Client.UpdatePolicy(policy); // End snippet } /// <summary>Snippet for UpdatePolicyAsync</summary> public async Task UpdatePolicyAsync() { // Snippet: UpdatePolicyAsync(Policy, CallSettings) // Additional: UpdatePolicyAsync(Policy, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) Policy policy = new Policy(); // Make the request Policy response = await binauthzManagementServiceV1Beta1Client.UpdatePolicyAsync(policy); // End snippet } /// <summary>Snippet for CreateAttestor</summary> public void CreateAttestorRequestObject() { // Snippet: CreateAttestor(CreateAttestorRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), AttestorId = "", Attestor = new Attestor(), }; // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.CreateAttestor(request); // End snippet } /// <summary>Snippet for CreateAttestorAsync</summary> public async Task CreateAttestorRequestObjectAsync() { // Snippet: CreateAttestorAsync(CreateAttestorRequest, CallSettings) // Additional: CreateAttestorAsync(CreateAttestorRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) CreateAttestorRequest request = new CreateAttestorRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), AttestorId = "", Attestor = new Attestor(), }; // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.CreateAttestorAsync(request); // End snippet } /// <summary>Snippet for CreateAttestor</summary> public void CreateAttestor() { // Snippet: CreateAttestor(string, string, Attestor, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string attestorId = ""; Attestor attestor = new Attestor(); // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.CreateAttestor(parent, attestorId, attestor); // End snippet } /// <summary>Snippet for CreateAttestorAsync</summary> public async Task CreateAttestorAsync() { // Snippet: CreateAttestorAsync(string, string, Attestor, CallSettings) // Additional: CreateAttestorAsync(string, string, Attestor, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; string attestorId = ""; Attestor attestor = new Attestor(); // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.CreateAttestorAsync(parent, attestorId, attestor); // End snippet } /// <summary>Snippet for CreateAttestor</summary> public void CreateAttestorResourceNames() { // Snippet: CreateAttestor(ProjectName, string, Attestor, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string attestorId = ""; Attestor attestor = new Attestor(); // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.CreateAttestor(parent, attestorId, attestor); // End snippet } /// <summary>Snippet for CreateAttestorAsync</summary> public async Task CreateAttestorResourceNamesAsync() { // Snippet: CreateAttestorAsync(ProjectName, string, Attestor, CallSettings) // Additional: CreateAttestorAsync(ProjectName, string, Attestor, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); string attestorId = ""; Attestor attestor = new Attestor(); // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.CreateAttestorAsync(parent, attestorId, attestor); // End snippet } /// <summary>Snippet for GetAttestor</summary> public void GetAttestorRequestObject() { // Snippet: GetAttestor(GetAttestorRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.GetAttestor(request); // End snippet } /// <summary>Snippet for GetAttestorAsync</summary> public async Task GetAttestorRequestObjectAsync() { // Snippet: GetAttestorAsync(GetAttestorRequest, CallSettings) // Additional: GetAttestorAsync(GetAttestorRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) GetAttestorRequest request = new GetAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.GetAttestorAsync(request); // End snippet } /// <summary>Snippet for GetAttestor</summary> public void GetAttestor() { // Snippet: GetAttestor(string, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/attestors/[ATTESTOR]"; // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.GetAttestor(name); // End snippet } /// <summary>Snippet for GetAttestorAsync</summary> public async Task GetAttestorAsync() { // Snippet: GetAttestorAsync(string, CallSettings) // Additional: GetAttestorAsync(string, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/attestors/[ATTESTOR]"; // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.GetAttestorAsync(name); // End snippet } /// <summary>Snippet for GetAttestor</summary> public void GetAttestorResourceNames() { // Snippet: GetAttestor(AttestorName, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) AttestorName name = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"); // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.GetAttestor(name); // End snippet } /// <summary>Snippet for GetAttestorAsync</summary> public async Task GetAttestorResourceNamesAsync() { // Snippet: GetAttestorAsync(AttestorName, CallSettings) // Additional: GetAttestorAsync(AttestorName, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) AttestorName name = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"); // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.GetAttestorAsync(name); // End snippet } /// <summary>Snippet for UpdateAttestor</summary> public void UpdateAttestorRequestObject() { // Snippet: UpdateAttestor(UpdateAttestorRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.UpdateAttestor(request); // End snippet } /// <summary>Snippet for UpdateAttestorAsync</summary> public async Task UpdateAttestorRequestObjectAsync() { // Snippet: UpdateAttestorAsync(UpdateAttestorRequest, CallSettings) // Additional: UpdateAttestorAsync(UpdateAttestorRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) UpdateAttestorRequest request = new UpdateAttestorRequest { Attestor = new Attestor(), }; // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.UpdateAttestorAsync(request); // End snippet } /// <summary>Snippet for UpdateAttestor</summary> public void UpdateAttestor() { // Snippet: UpdateAttestor(Attestor, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) Attestor attestor = new Attestor(); // Make the request Attestor response = binauthzManagementServiceV1Beta1Client.UpdateAttestor(attestor); // End snippet } /// <summary>Snippet for UpdateAttestorAsync</summary> public async Task UpdateAttestorAsync() { // Snippet: UpdateAttestorAsync(Attestor, CallSettings) // Additional: UpdateAttestorAsync(Attestor, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) Attestor attestor = new Attestor(); // Make the request Attestor response = await binauthzManagementServiceV1Beta1Client.UpdateAttestorAsync(attestor); // End snippet } /// <summary>Snippet for ListAttestors</summary> public void ListAttestorsRequestObject() { // Snippet: ListAttestors(ListAttestorsRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) ListAttestorsRequest request = new ListAttestorsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestors(request); // Iterate over all response items, lazily performing RPCs as required foreach (Attestor item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAttestorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAttestorsAsync</summary> public async Task ListAttestorsRequestObjectAsync() { // Snippet: ListAttestorsAsync(ListAttestorsRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) ListAttestorsRequest request = new ListAttestorsRequest { ParentAsProjectName = ProjectName.FromProject("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestorsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Attestor item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAttestorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAttestors</summary> public void ListAttestors() { // Snippet: ListAttestors(string, string, int?, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestors(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Attestor item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAttestorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAttestorsAsync</summary> public async Task ListAttestorsAsync() { // Snippet: ListAttestorsAsync(string, string, int?, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]"; // Make the request PagedAsyncEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestorsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Attestor item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAttestorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAttestors</summary> public void ListAttestorsResourceNames() { // Snippet: ListAttestors(ProjectName, string, int?, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestors(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Attestor item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListAttestorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListAttestorsAsync</summary> public async Task ListAttestorsResourceNamesAsync() { // Snippet: ListAttestorsAsync(ProjectName, string, int?, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) ProjectName parent = ProjectName.FromProject("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListAttestorsResponse, Attestor> response = binauthzManagementServiceV1Beta1Client.ListAttestorsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Attestor item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListAttestorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Attestor item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Attestor> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Attestor item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for DeleteAttestor</summary> public void DeleteAttestorRequestObject() { // Snippet: DeleteAttestor(DeleteAttestorRequest, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; // Make the request binauthzManagementServiceV1Beta1Client.DeleteAttestor(request); // End snippet } /// <summary>Snippet for DeleteAttestorAsync</summary> public async Task DeleteAttestorRequestObjectAsync() { // Snippet: DeleteAttestorAsync(DeleteAttestorRequest, CallSettings) // Additional: DeleteAttestorAsync(DeleteAttestorRequest, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) DeleteAttestorRequest request = new DeleteAttestorRequest { AttestorName = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"), }; // Make the request await binauthzManagementServiceV1Beta1Client.DeleteAttestorAsync(request); // End snippet } /// <summary>Snippet for DeleteAttestor</summary> public void DeleteAttestor() { // Snippet: DeleteAttestor(string, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/attestors/[ATTESTOR]"; // Make the request binauthzManagementServiceV1Beta1Client.DeleteAttestor(name); // End snippet } /// <summary>Snippet for DeleteAttestorAsync</summary> public async Task DeleteAttestorAsync() { // Snippet: DeleteAttestorAsync(string, CallSettings) // Additional: DeleteAttestorAsync(string, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/attestors/[ATTESTOR]"; // Make the request await binauthzManagementServiceV1Beta1Client.DeleteAttestorAsync(name); // End snippet } /// <summary>Snippet for DeleteAttestor</summary> public void DeleteAttestorResourceNames() { // Snippet: DeleteAttestor(AttestorName, CallSettings) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = BinauthzManagementServiceV1Beta1Client.Create(); // Initialize request argument(s) AttestorName name = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"); // Make the request binauthzManagementServiceV1Beta1Client.DeleteAttestor(name); // End snippet } /// <summary>Snippet for DeleteAttestorAsync</summary> public async Task DeleteAttestorResourceNamesAsync() { // Snippet: DeleteAttestorAsync(AttestorName, CallSettings) // Additional: DeleteAttestorAsync(AttestorName, CancellationToken) // Create client BinauthzManagementServiceV1Beta1Client binauthzManagementServiceV1Beta1Client = await BinauthzManagementServiceV1Beta1Client.CreateAsync(); // Initialize request argument(s) AttestorName name = AttestorName.FromProjectAttestor("[PROJECT]", "[ATTESTOR]"); // Make the request await binauthzManagementServiceV1Beta1Client.DeleteAttestorAsync(name); // End snippet } } }
using EncompassRest.Loans.Enums; using EncompassRest.Schema; namespace EncompassRest.Loans { /// <summary> /// Hmda /// </summary> public sealed partial class Hmda : DirtyExtensibleObject, IIdentifiable { private DirtyValue<StringEnumValue<ActionTaken>>? _actionTaken; private DirtyValue<string?>? _applicationDate; private DirtyValue<StringEnumValue<AUS>>? _aUS1; private DirtyValue<StringEnumValue<AUS>>? _aUS2; private DirtyValue<StringEnumValue<AUS>>? _aUS3; private DirtyValue<StringEnumValue<AUS>>? _aUS4; private DirtyValue<StringEnumValue<AUS>>? _aUS5; private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation1; private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation2; private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation3; private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation4; private DirtyValue<StringEnumValue<AUSRecommendation>>? _aUSRecommendation5; private DirtyValue<StringEnumValue<YNOrExempt>>? _balloonIndicator; private DirtyValue<StringEnumValue<BusinessOrCommercialPurpose>>? _businessOrCommercialPurpose; private DirtyValue<bool?>? _cDRequired; private DirtyValue<string?>? _censusTrack; private DirtyValue<StringDecimalValue>? _cLTV; private DirtyValue<string?>? _contactEmailAddress; private DirtyValue<string?>? _contactFaxNumber; private DirtyValue<string?>? _contactName; private DirtyValue<string?>? _contactOfficeCity; private DirtyValue<StringEnumValue<State>>? _contactOfficeState; private DirtyValue<string?>? _contactOfficeStreetAddress; private DirtyValue<string?>? _contactOfficeZIPCode; private DirtyValue<string?>? _contactPhoneNumber; private DirtyValue<string?>? _countyCode; private DirtyValue<StringDecimalValue>? _debtToIncomeRatio; private DirtyValue<StringEnumValue<DenialReason>>? _denialReason1; private DirtyValue<StringEnumValue<DenialReason>>? _denialReason2; private DirtyValue<StringEnumValue<DenialReason>>? _denialReason3; private DirtyValue<StringEnumValue<DenialReason>>? _denialReason4; private DirtyValue<StringDecimalValue>? _discountPoints; private DirtyValue<bool?>? _excludeLoanFromHMDAReportIndicator; private DirtyValue<StringEnumValue<FederalAgency>>? _federalAgency; private DirtyValue<string?>? _federalTaxpayerIdNumber; private DirtyValue<string?>? _financialInstitutionName; private DirtyValue<StringEnumValue<YNOrExempt>>? _hmda2InterestOnlyIndicator; private DirtyValue<string?>? _hMDACensusTrack; private DirtyValue<bool?>? _hmdaCltvIndicator; private DirtyValue<string?>? _hMDACountyCode; private DirtyValue<bool?>? _hmdaDtiIndicator; private DirtyValue<bool?>? _hmdaIncomeIndicator; private DirtyValue<bool?>? _hmdaInterestOnlyIndicator; private DirtyValue<StringEnumValue<HmdaLoanPurpose>>? _hMDALoanPurpose; private DirtyValue<string?>? _hMDAProfileApplicationDateValue; private DirtyValue<string?>? _hMDAProfileCLTVValue; private DirtyValue<string?>? _hMDAProfileDTIValue; private DirtyValue<string?>? _hMDAProfileID; private DirtyValue<string?>? _hMDAProfileIncomeValue; private DirtyValue<string?>? _hmdaPropertyAddress; private DirtyValue<string?>? _hmdaPropertyCity; private DirtyValue<StringEnumValue<State>>? _hmdaPropertyState; private DirtyValue<bool?>? _hmdaPropertyValueNotReliedUponIndicator; private DirtyValue<string?>? _hmdaPropertyZipCode; private DirtyValue<bool?>? _hmdaSyncAddressIndicator; private DirtyValue<StringEnumValue<HOEPAStatus>>? _hOEPAStatus; private DirtyValue<string?>? _id; private DirtyValue<NA<decimal>>? _income; private DirtyValue<decimal?>? _incomeExcludedFromHmda; private DirtyValue<StringEnumValue<InitiallyPayableToYourInstitution>>? _initiallyPayableToYourInstitution; private DirtyValue<StringDecimalValue>? _interestRate; private DirtyValue<string?>? _introRatePeriod; private DirtyValue<string?>? _legalEntityIdentifier; private DirtyValue<string?>? _legalEntityIdentifierReporting; private DirtyValue<StringEnumValue<LegalEntityIdentifierUsed>>? _legalEntityIdentifierUsed; private DirtyValue<StringDecimalValue>? _lenderCredits; private DirtyValue<StringEnumValue<LienStatus>>? _lienStatus; private DirtyValue<decimal?>? _loanAmount; private DirtyValue<StringEnumValue<YNOrExempt>>? _loanBalanceRiseIndicator; private DirtyValue<StringEnumValue<HmdaLoanPurpose>>? _loanPurpose; private DirtyValue<string?>? _loanTerm; private DirtyValue<StringEnumValue<HmdaLoanType>>? _loanType; private DirtyValue<StringEnumValue<ManufacturedHomeLandPropertyInterest>>? _manufacturedHomeLandPropertyInterest; private DirtyValue<StringEnumValue<ManufacturedSecuredProperyType>>? _manufacturedSecuredProperyType; private DirtyValue<string?>? _mSANumber; private DirtyValue<string?>? _multifamilyNoUnits; private DirtyValue<string?>? _nMLSLoanOriginatorID; private DirtyValue<StringEnumValue<OpenEndLineOfCredit>>? _openEndLineOfCredit; private DirtyValue<string?>? _originationCharges; private DirtyValue<string?>? _otherAUS; private DirtyValue<string?>? _otherAUSRecommendations; private DirtyValue<string?>? _otherDenialReason; private DirtyValue<StringEnumValue<OtherNonAmortization>>? _otherNonAmortization; private DirtyValue<string?>? _parentAddress; private DirtyValue<string?>? _parentCity; private DirtyValue<string?>? _parentName; private DirtyValue<StringEnumValue<State>>? _parentState; private DirtyValue<string?>? _parentZip; private DirtyValue<bool?>? _partiallyExemptLoanIndicator; private DirtyValue<StringEnumValue<Preapprovals>>? _preapprovals; private DirtyValue<string?>? _prepaymentPenaltyPeriod; private DirtyValue<StringEnumValue<HmdaPropertyType>>? _propertyType; private DirtyValue<StringDecimalValue>? _propertyValue; private DirtyValue<StringEnumValue<QMStatus>>? _qMStatus; private DirtyValue<StringDecimalValue>? _rateSpread; private DirtyValue<int?>? _reportingYear; private DirtyValue<bool?>? _reportPurposeOfLoanIndicator; private DirtyValue<string?>? _repurchasedActionDate; private DirtyValue<StringEnumValue<ActionTaken>>? _repurchasedActionTaken; private DirtyValue<decimal?>? _repurchasedLoanAmount; private DirtyValue<int?>? _repurchasedReportingYear; private DirtyValue<StringEnumValue<TypeOfPurchaser>>? _repurchasedTypeOfPurchaser; private DirtyValue<string?>? _respondentID; private DirtyValue<StringEnumValue<ReverseMortgage>>? _reverseMortgage; private DirtyValue<string?>? _stateCode; private DirtyValue<StringEnumValue<SubmissionOfApplication>>? _submissionOfApplication; private DirtyValue<string?>? _totalLoanCosts; private DirtyValue<string?>? _totalPointsAndFees; private DirtyValue<StringEnumValue<TypeOfPurchaser>>? _typeOfPurchaser; private DirtyValue<string?>? _universalLoanId; /// <summary> /// Trans Details Current Loan Status [1393] /// </summary> public StringEnumValue<ActionTaken> ActionTaken { get => _actionTaken; set => SetField(ref _actionTaken, value); } /// <summary> /// Application Date [HMDA.X29] /// </summary> public string? ApplicationDate { get => _applicationDate; set => SetField(ref _applicationDate, value); } /// <summary> /// AUS #1 [HMDA.X44] /// </summary> public StringEnumValue<AUS> AUS1 { get => _aUS1; set => SetField(ref _aUS1, value); } /// <summary> /// AUS #2 [HMDA.X45] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\",\"Internal Proprietary System\"]")] public StringEnumValue<AUS> AUS2 { get => _aUS2; set => SetField(ref _aUS2, value); } /// <summary> /// AUS #3 [HMDA.X46] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\",\"Internal Proprietary System\"]")] public StringEnumValue<AUS> AUS3 { get => _aUS3; set => SetField(ref _aUS3, value); } /// <summary> /// AUS #4 [HMDA.X47] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\",\"Internal Proprietary System\"]")] public StringEnumValue<AUS> AUS4 { get => _aUS4; set => SetField(ref _aUS4, value); } /// <summary> /// AUS #5 [HMDA.X48] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\",\"Internal Proprietary System\"]")] public StringEnumValue<AUS> AUS5 { get => _aUS5; set => SetField(ref _aUS5, value); } /// <summary> /// AUS Recommendation #1 [HMDA.X50] /// </summary> public StringEnumValue<AUSRecommendation> AUSRecommendation1 { get => _aUSRecommendation1; set => SetField(ref _aUSRecommendation1, value); } /// <summary> /// AUS Recommendation #2 [HMDA.X51] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<AUSRecommendation> AUSRecommendation2 { get => _aUSRecommendation2; set => SetField(ref _aUSRecommendation2, value); } /// <summary> /// AUS Recommendation #3 [HMDA.X52] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<AUSRecommendation> AUSRecommendation3 { get => _aUSRecommendation3; set => SetField(ref _aUSRecommendation3, value); } /// <summary> /// AUS Recommendation #4 [HMDA.X53] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<AUSRecommendation> AUSRecommendation4 { get => _aUSRecommendation4; set => SetField(ref _aUSRecommendation4, value); } /// <summary> /// AUS Recommendation #5 [HMDA.X54] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<AUSRecommendation> AUSRecommendation5 { get => _aUSRecommendation5; set => SetField(ref _aUSRecommendation5, value); } /// <summary> /// Trans Details Amort Type Balloon [HMDA.X114] /// </summary> public StringEnumValue<YNOrExempt> BalloonIndicator { get => _balloonIndicator; set => SetField(ref _balloonIndicator, value); } /// <summary> /// Business or Commercial Purpose [HMDA.X58] /// </summary> public StringEnumValue<BusinessOrCommercialPurpose> BusinessOrCommercialPurpose { get => _businessOrCommercialPurpose; set => SetField(ref _businessOrCommercialPurpose, value); } /// <summary> /// CD Required [HMDA.X121] /// </summary> public bool? CDRequired { get => _cDRequired; set => SetField(ref _cDRequired, value); } /// <summary> /// Subject Property Census Tract [700] /// </summary> public string? CensusTrack { get => _censusTrack; set => SetField(ref _censusTrack, value); } /// <summary> /// CLTV [HMDA.X37] /// </summary> public StringDecimalValue CLTV { get => _cLTV; set => SetField(ref _cLTV, value); } /// <summary> /// HMDA Contact Person Email [HMDA.X62] /// </summary> public string? ContactEmailAddress { get => _contactEmailAddress; set => SetField(ref _contactEmailAddress, value); } /// <summary> /// HMDA Contact Person Fax # [HMDA.X67] /// </summary> public string? ContactFaxNumber { get => _contactFaxNumber; set => SetField(ref _contactFaxNumber, value); } /// <summary> /// HMDA Contact Person Name [HMDA.X60] /// </summary> public string? ContactName { get => _contactName; set => SetField(ref _contactName, value); } /// <summary> /// HMDA Contact Person City [HMDA.X64] /// </summary> public string? ContactOfficeCity { get => _contactOfficeCity; set => SetField(ref _contactOfficeCity, value); } /// <summary> /// HMDA Contact Person State [HMDA.X65] /// </summary> public StringEnumValue<State> ContactOfficeState { get => _contactOfficeState; set => SetField(ref _contactOfficeState, value); } /// <summary> /// HMDA Contact Person Street Address [HMDA.X63] /// </summary> public string? ContactOfficeStreetAddress { get => _contactOfficeStreetAddress; set => SetField(ref _contactOfficeStreetAddress, value); } /// <summary> /// HMDA Contact Person ZIP [HMDA.X66] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? ContactOfficeZIPCode { get => _contactOfficeZIPCode; set => SetField(ref _contactOfficeZIPCode, value); } /// <summary> /// HMDA Contact Person Phone # [HMDA.X61] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.PHONE)] public string? ContactPhoneNumber { get => _contactPhoneNumber; set => SetField(ref _contactPhoneNumber, value); } /// <summary> /// Subject Property County Code [1396] /// </summary> public string? CountyCode { get => _countyCode; set => SetField(ref _countyCode, value); } /// <summary> /// Debt to Income Ratio [HMDA.X36] /// </summary> public StringDecimalValue DebtToIncomeRatio { get => _debtToIncomeRatio; set => SetField(ref _debtToIncomeRatio, value); } /// <summary> /// Denial Reason 1 [HMDA.X21] /// </summary> public StringEnumValue<DenialReason> DenialReason1 { get => _denialReason1; set => SetField(ref _denialReason1, value); } /// <summary> /// Denial Reason 2 [HMDA.X22] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<DenialReason> DenialReason2 { get => _denialReason2; set => SetField(ref _denialReason2, value); } /// <summary> /// Denial Reason 3 [HMDA.X23] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<DenialReason> DenialReason3 { get => _denialReason3; set => SetField(ref _denialReason3, value); } /// <summary> /// Denial Reason 4 [HMDA.X33] /// </summary> [LoanFieldProperty(MissingOptionsJson = "[\"Not applicable\",\"Exempt\"]")] public StringEnumValue<DenialReason> DenialReason4 { get => _denialReason4; set => SetField(ref _denialReason4, value); } /// <summary> /// Discount Points [HMDA.X35] /// </summary> public StringDecimalValue DiscountPoints { get => _discountPoints; set => SetField(ref _discountPoints, value); } /// <summary> /// Subject Property Exclude from HMDA Report [HMDA.X24] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Exclude loan from HMDA report\"}")] public bool? ExcludeLoanFromHMDAReportIndicator { get => _excludeLoanFromHMDAReportIndicator; set => SetField(ref _excludeLoanFromHMDAReportIndicator, value); } /// <summary> /// HMDA Federal Agency [HMDA.X68] /// </summary> public StringEnumValue<FederalAgency> FederalAgency { get => _federalAgency; set => SetField(ref _federalAgency, value); } /// <summary> /// HMDA Fedral Tax ID [HMDA.X69] /// </summary> public string? FederalTaxpayerIdNumber { get => _federalTaxpayerIdNumber; set => SetField(ref _federalTaxpayerIdNumber, value); } /// <summary> /// HMDA Company Name [HMDA.X59] /// </summary> public string? FinancialInstitutionName { get => _financialInstitutionName; set => SetField(ref _financialInstitutionName, value); } /// <summary> /// Trans Details Interest Only Indicator [HMDA.X120] /// </summary> public StringEnumValue<YNOrExempt> Hmda2InterestOnlyIndicator { get => _hmda2InterestOnlyIndicator; set => SetField(ref _hmda2InterestOnlyIndicator, value); } /// <summary> /// CFPB HMDA Census Tract [HMDA.X112] /// </summary> public string? HMDACensusTrack { get => _hMDACensusTrack; set => SetField(ref _hMDACensusTrack, value); } /// <summary> /// HMDA CLTV [HMDA.X98] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA CLTV\"}")] public bool? HmdaCltvIndicator { get => _hmdaCltvIndicator; set => SetField(ref _hmdaCltvIndicator, value); } /// <summary> /// CFPB HMDA County Code [HMDA.X111] /// </summary> public string? HMDACountyCode { get => _hMDACountyCode; set => SetField(ref _hMDACountyCode, value); } /// <summary> /// HMDA DTI [HMDA.X97] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA DTI\"}")] public bool? HmdaDtiIndicator { get => _hmdaDtiIndicator; set => SetField(ref _hmdaDtiIndicator, value); } /// <summary> /// HMDA Income [HMDA.X99] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA Income\"}")] public bool? HmdaIncomeIndicator { get => _hmdaIncomeIndicator; set => SetField(ref _hmdaIncomeIndicator, value); } /// <summary> /// Trans Details Interest Only Indicator [HMDA.X109] /// </summary> public bool? HmdaInterestOnlyIndicator { get => _hmdaInterestOnlyIndicator; set => SetField(ref _hmdaInterestOnlyIndicator, value); } /// <summary> /// HMDA Loan Purpose [HMDA.X107] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Home Purchase\":\"1. Home purchase\",\"Home Improvement\":\"2. Home improvement\",\"Cash-out refinancing\":\"32. Cash-out refinancing (consumer only)\",\"Other purpose\":\"4. Other purpose (consumer only)\"}")] public StringEnumValue<HmdaLoanPurpose> HMDALoanPurpose { get => _hMDALoanPurpose; set => SetField(ref _hMDALoanPurpose, value); } /// <summary> /// HMDA Profile - Application Date value from Setting [HMDA.X104] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? HMDAProfileApplicationDateValue { get => _hMDAProfileApplicationDateValue; set => SetField(ref _hMDAProfileApplicationDateValue, value); } /// <summary> /// HMDA Profile - CLTV value from Setting [HMDA.X102] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? HMDAProfileCLTVValue { get => _hMDAProfileCLTVValue; set => SetField(ref _hMDAProfileCLTVValue, value); } /// <summary> /// HMDA Profile - DTI value from Setting [HMDA.X101] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? HMDAProfileDTIValue { get => _hMDAProfileDTIValue; set => SetField(ref _hMDAProfileDTIValue, value); } /// <summary> /// HMDA Profile ID [HMDA.X100] /// </summary> public string? HMDAProfileID { get => _hMDAProfileID; set => SetField(ref _hMDAProfileID, value); } /// <summary> /// HMDA Profile - Income value from Setting [HMDA.X103] /// </summary> [LoanFieldProperty(ReadOnly = true)] public string? HMDAProfileIncomeValue { get => _hMDAProfileIncomeValue; set => SetField(ref _hMDAProfileIncomeValue, value); } /// <summary> /// HMDA Property Address [HMDA.X88] /// </summary> public string? HmdaPropertyAddress { get => _hmdaPropertyAddress; set => SetField(ref _hmdaPropertyAddress, value); } /// <summary> /// HMDA Property City [HMDA.X89] /// </summary> public string? HmdaPropertyCity { get => _hmdaPropertyCity; set => SetField(ref _hmdaPropertyCity, value); } /// <summary> /// HMDA Property State [HMDA.X90] /// </summary> public StringEnumValue<State> HmdaPropertyState { get => _hmdaPropertyState; set => SetField(ref _hmdaPropertyState, value); } /// <summary> /// Property Value Not Relied Upon [HMDA.X108] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Property Value Not Relied Upon\"}")] public bool? HmdaPropertyValueNotReliedUponIndicator { get => _hmdaPropertyValueNotReliedUponIndicator; set => SetField(ref _hmdaPropertyValueNotReliedUponIndicator, value); } /// <summary> /// HMDA Property Zip Code [HMDA.X87] /// </summary> public string? HmdaPropertyZipCode { get => _hmdaPropertyZipCode; set => SetField(ref _hmdaPropertyZipCode, value); } /// <summary> /// HMDA Sync address fields with subject property address [HMDA.X91] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"HMDA Sync Address Indicator\"}")] public bool? HmdaSyncAddressIndicator { get => _hmdaSyncAddressIndicator; set => SetField(ref _hmdaSyncAddressIndicator, value); } /// <summary> /// Trans Details HOEPA Status [HMDA.X13] /// </summary> public StringEnumValue<HOEPAStatus> HOEPAStatus { get => _hOEPAStatus; set => SetField(ref _hOEPAStatus, value); } /// <summary> /// Hmda Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// HMDA Income [HMDA.X32] /// </summary> public NA<decimal> Income { get => _income; set => SetField(ref _income, value); } /// <summary> /// Income Excluded From HMDA [HMDA.X110] /// </summary> public decimal? IncomeExcludedFromHmda { get => _incomeExcludedFromHmda; set => SetField(ref _incomeExcludedFromHmda, value); } /// <summary> /// Initially Payable to Your Institution [HMDA.X43] /// </summary> public StringEnumValue<InitiallyPayableToYourInstitution> InitiallyPayableToYourInstitution { get => _initiallyPayableToYourInstitution; set => SetField(ref _initiallyPayableToYourInstitution, value); } /// <summary> /// Interest Rate [HMDA.X81] /// </summary> public StringDecimalValue InterestRate { get => _interestRate; set => SetField(ref _interestRate, value); } /// <summary> /// Intro Rate Period [HMDA.X84] /// </summary> public string? IntroRatePeriod { get => _introRatePeriod; set => SetField(ref _introRatePeriod, value); } /// <summary> /// HMDA LEI [HMDA.X70] /// </summary> public string? LegalEntityIdentifier { get => _legalEntityIdentifier; set => SetField(ref _legalEntityIdentifier, value); } /// <summary> /// HMDA LEI Reporting [HMDA.X106] /// </summary> public string? LegalEntityIdentifierReporting { get => _legalEntityIdentifierReporting; set => SetField(ref _legalEntityIdentifierReporting, value); } /// <summary> /// HMDA LEI Used [HMDA.X105] /// </summary> public StringEnumValue<LegalEntityIdentifierUsed> LegalEntityIdentifierUsed { get => _legalEntityIdentifierUsed; set => SetField(ref _legalEntityIdentifierUsed, value); } /// <summary> /// Lender Credits [HMDA.X80] /// </summary> public StringDecimalValue LenderCredits { get => _lenderCredits; set => SetField(ref _lenderCredits, value); } /// <summary> /// Trans Details Lien Status [HMDA.X14] /// </summary> public StringEnumValue<LienStatus> LienStatus { get => _lienStatus; set => SetField(ref _lienStatus, value); } /// <summary> /// HMDA Loan Amount [HMDA.X31] /// </summary> public decimal? LoanAmount { get => _loanAmount; set => SetField(ref _loanAmount, value); } /// <summary> /// Can Your Loan Balance Rise [HMDA.X115] /// </summary> public StringEnumValue<YNOrExempt> LoanBalanceRiseIndicator { get => _loanBalanceRiseIndicator; set => SetField(ref _loanBalanceRiseIndicator, value); } /// <summary> /// Trans Details Loan Purpose [384] /// </summary> public StringEnumValue<HmdaLoanPurpose> LoanPurpose { get => _loanPurpose; set => SetField(ref _loanPurpose, value); } /// <summary> /// Loan Term [HMDA.X83] /// </summary> public string? LoanTerm { get => _loanTerm; set => SetField(ref _loanTerm, value); } /// <summary> /// HMDA Loan Type [HMDA.X30] /// </summary> public StringEnumValue<HmdaLoanType> LoanType { get => _loanType; set => SetField(ref _loanType, value); } /// <summary> /// Manufactured Home Land Property Interest [HMDA.X40] /// </summary> public StringEnumValue<ManufacturedHomeLandPropertyInterest> ManufacturedHomeLandPropertyInterest { get => _manufacturedHomeLandPropertyInterest; set => SetField(ref _manufacturedHomeLandPropertyInterest, value); } /// <summary> /// Manufactured Secured Property Type [HMDA.X39] /// </summary> public StringEnumValue<ManufacturedSecuredProperyType> ManufacturedSecuredProperyType { get => _manufacturedSecuredProperyType; set => SetField(ref _manufacturedSecuredProperyType, value); } /// <summary> /// Subject Property MSA # [699] /// </summary> public string? MSANumber { get => _mSANumber; set => SetField(ref _mSANumber, value); } /// <summary> /// Multifamily No Units [HMDA.X41] /// </summary> public string? MultifamilyNoUnits { get => _multifamilyNoUnits; set => SetField(ref _multifamilyNoUnits, value); } /// <summary> /// NMLS Loan Originator ID [HMDA.X86] /// </summary> public string? NMLSLoanOriginatorID { get => _nMLSLoanOriginatorID; set => SetField(ref _nMLSLoanOriginatorID, value); } /// <summary> /// Open-End Line of Credit [HMDA.X57] /// </summary> public StringEnumValue<OpenEndLineOfCredit> OpenEndLineOfCredit { get => _openEndLineOfCredit; set => SetField(ref _openEndLineOfCredit, value); } /// <summary> /// Origination Charges [HMDA.X79] /// </summary> public string? OriginationCharges { get => _originationCharges; set => SetField(ref _originationCharges, value); } /// <summary> /// Other AUX(s) [HMDA.X49] /// </summary> public string? OtherAUS { get => _otherAUS; set => SetField(ref _otherAUS, value); } /// <summary> /// Other AUS Recommendation(s) [HMDA.X55] /// </summary> public string? OtherAUSRecommendations { get => _otherAUSRecommendations; set => SetField(ref _otherAUSRecommendations, value); } /// <summary> /// Other Denial Reason [HMDA.X34] /// </summary> public string? OtherDenialReason { get => _otherDenialReason; set => SetField(ref _otherDenialReason, value); } /// <summary> /// Other Non-Amortization [HMDA.X38] /// </summary> public StringEnumValue<OtherNonAmortization> OtherNonAmortization { get => _otherNonAmortization; set => SetField(ref _otherNonAmortization, value); } /// <summary> /// HMDA Parent Address [HMDA.X73] /// </summary> public string? ParentAddress { get => _parentAddress; set => SetField(ref _parentAddress, value); } /// <summary> /// HMDA Parent City [HMDA.X74] /// </summary> public string? ParentCity { get => _parentCity; set => SetField(ref _parentCity, value); } /// <summary> /// HMDA Parent Contact Name [HMDA.X72] /// </summary> public string? ParentName { get => _parentName; set => SetField(ref _parentName, value); } /// <summary> /// HMDA Parent State [HMDA.X75] /// </summary> public StringEnumValue<State> ParentState { get => _parentState; set => SetField(ref _parentState, value); } /// <summary> /// HMDA Parent Zipcode [HMDA.X76] /// </summary> [LoanFieldProperty(Format = LoanFieldFormat.ZIPCODE)] public string? ParentZip { get => _parentZip; set => SetField(ref _parentZip, value); } /// <summary> /// Report loan as Partially Exempt [HMDA.X113] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Loan is Partially Exempt\"}")] public bool? PartiallyExemptLoanIndicator { get => _partiallyExemptLoanIndicator; set => SetField(ref _partiallyExemptLoanIndicator, value); } /// <summary> /// Trans Details Preapprovals [HMDA.X12] /// </summary> public StringEnumValue<Preapprovals> Preapprovals { get => _preapprovals; set => SetField(ref _preapprovals, value); } /// <summary> /// Prepayment Penalty Period [HMDA.X82] /// </summary> public string? PrepaymentPenaltyPeriod { get => _prepaymentPenaltyPeriod; set => SetField(ref _prepaymentPenaltyPeriod, value); } /// <summary> /// Subject Property Type [HMDA.X11] /// </summary> public StringEnumValue<HmdaPropertyType> PropertyType { get => _propertyType; set => SetField(ref _propertyType, value); } /// <summary> /// Property Value [HMDA.X85] /// </summary> public StringDecimalValue PropertyValue { get => _propertyValue; set => SetField(ref _propertyValue, value); } /// <summary> /// QM Status [HMDA.X26] /// </summary> public StringEnumValue<QMStatus> QMStatus { get => _qMStatus; set => SetField(ref _qMStatus, value); } /// <summary> /// Trans Details Rate Spread [HMDA.X15] /// </summary> public StringDecimalValue RateSpread { get => _rateSpread; set => SetField(ref _rateSpread, value); } /// <summary> /// HMDA Reporting Year [HMDA.X27] /// </summary> public int? ReportingYear { get => _reportingYear; set => SetField(ref _reportingYear, value); } /// <summary> /// Loan Purpose is Home Improvement [HMDA.X25] /// </summary> [LoanFieldProperty(OptionsJson = "{\"Y\":\"Report the purpose of this loan as Home Improvement (one to four family)\"}")] public bool? ReportPurposeOfLoanIndicator { get => _reportPurposeOfLoanIndicator; set => SetField(ref _reportPurposeOfLoanIndicator, value); } /// <summary> /// Repurchased Action Date [HMDA.X96] /// </summary> public string? RepurchasedActionDate { get => _repurchasedActionDate; set => SetField(ref _repurchasedActionDate, value); } /// <summary> /// HMDA Repurchased Trans Details Current Loan Status [HMDA.X95] /// </summary> public StringEnumValue<ActionTaken> RepurchasedActionTaken { get => _repurchasedActionTaken; set => SetField(ref _repurchasedActionTaken, value); } /// <summary> /// HMDA Repurchased Loan Amount [HMDA.X93] /// </summary> public decimal? RepurchasedLoanAmount { get => _repurchasedLoanAmount; set => SetField(ref _repurchasedLoanAmount, value); } /// <summary> /// HMDA Repurchased Reporting Year [HMDA.X92] /// </summary> public int? RepurchasedReportingYear { get => _repurchasedReportingYear; set => SetField(ref _repurchasedReportingYear, value); } /// <summary> /// HMDA Repurchased Trans Details Purchaser Type [HMDA.X94] /// </summary> public StringEnumValue<TypeOfPurchaser> RepurchasedTypeOfPurchaser { get => _repurchasedTypeOfPurchaser; set => SetField(ref _repurchasedTypeOfPurchaser, value); } /// <summary> /// HMDA Respondent ID [HMDA.X71] /// </summary> public string? RespondentID { get => _respondentID; set => SetField(ref _respondentID, value); } /// <summary> /// Reverse Mortgage [HMDA.X56] /// </summary> public StringEnumValue<ReverseMortgage> ReverseMortgage { get => _reverseMortgage; set => SetField(ref _reverseMortgage, value); } /// <summary> /// Subject Property State Code [1395] /// </summary> public string? StateCode { get => _stateCode; set => SetField(ref _stateCode, value); } /// <summary> /// Submission of Application [HMDA.X42] /// </summary> public StringEnumValue<SubmissionOfApplication> SubmissionOfApplication { get => _submissionOfApplication; set => SetField(ref _submissionOfApplication, value); } /// <summary> /// Total Loan Costs [HMDA.X77] /// </summary> public string? TotalLoanCosts { get => _totalLoanCosts; set => SetField(ref _totalLoanCosts, value); } /// <summary> /// Total Points and Fees [HMDA.X78] /// </summary> public string? TotalPointsAndFees { get => _totalPointsAndFees; set => SetField(ref _totalPointsAndFees, value); } /// <summary> /// Trans Details Purchaser Type [1397] /// </summary> public StringEnumValue<TypeOfPurchaser> TypeOfPurchaser { get => _typeOfPurchaser; set => SetField(ref _typeOfPurchaser, value); } /// <summary> /// Universal Loan Id [HMDA.X28] /// </summary> public string? UniversalLoanId { get => _universalLoanId; set => SetField(ref _universalLoanId, 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. /*============================================================ ** ** ** ** ** ** Purpose: Culture-specific collection of resources. ** ** ===========================================================*/ using System; using System.Collections; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Diagnostics.Contracts; using System.Collections.Generic; namespace System.Resources { // A ResourceSet stores all the resources defined in one particular CultureInfo. // // The method used to load resources is straightforward - this class // enumerates over an IResourceReader, loading every name and value, and // stores them in a hash table. Custom IResourceReaders can be used. // public class ResourceSet : IDisposable, IEnumerable { [NonSerialized] protected IResourceReader Reader; internal Hashtable Table; private Hashtable _caseInsensitiveTable; // For case-insensitive lookups. protected ResourceSet() { // To not inconvenience people subclassing us, we should allocate a new // hashtable here just so that Table is set to something. CommonInit(); } // For RuntimeResourceSet, ignore the Table parameter - it's a wasted // allocation. internal ResourceSet(bool junk) { } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to open & read from a file // on disk. // public ResourceSet(String fileName) { Reader = new ResourceReader(fileName); CommonInit(); ReadResources(); } // Creates a ResourceSet using the system default ResourceReader // implementation. Use this constructor to read from an open stream // of data. // public ResourceSet(Stream stream) { Reader = new ResourceReader(stream); CommonInit(); ReadResources(); } public ResourceSet(IResourceReader reader) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Contract.EndContractBlock(); Reader = reader; CommonInit(); ReadResources(); } private void CommonInit() { Table = new Hashtable(); } // Closes and releases any resources used by this ResourceSet, if any. // All calls to methods on the ResourceSet after a call to close may // fail. Close is guaranteed to be safely callable multiple times on a // particular ResourceSet, and all subclasses must support these semantics. public virtual void Close() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { // Close the Reader in a thread-safe way. IResourceReader copyOfReader = Reader; Reader = null; if (copyOfReader != null) copyOfReader.Close(); } Reader = null; _caseInsensitiveTable = null; Table = null; } public void Dispose() { Dispose(true); } // Returns the preferred IResourceReader class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultReader() { return typeof(ResourceReader); } // Returns the preferred IResourceWriter class for this kind of ResourceSet. // Subclasses of ResourceSet using their own Readers &; should override // GetDefaultReader and GetDefaultWriter. public virtual Type GetDefaultWriter() { Assembly resourceWriterAssembly = Assembly.Load("System.Resources.Writer, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"); return resourceWriterAssembly.GetType("System.Resources.ResourceWriter", true); } public virtual IDictionaryEnumerator GetEnumerator() { return GetEnumeratorHelper(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumeratorHelper(); } private IDictionaryEnumerator GetEnumeratorHelper() { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable.GetEnumerator(); } // Look up a string value for a resource given its name. // public virtual String GetString(String name) { Object obj = GetObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } public virtual String GetString(String name, bool ignoreCase) { Object obj; String s; // Case-sensitive lookup obj = GetObjectInternal(name); try { s = (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } // case-sensitive lookup succeeded if (s != null || !ignoreCase) { return s; } // Try doing a case-insensitive lookup obj = GetCaseInsensitiveObjectInternal(name); try { return (String)obj; } catch (InvalidCastException) { throw new InvalidOperationException(SR.Format(SR.InvalidOperation_ResourceNotString_Name, name)); } } // Look up an object value for a resource given its name. // public virtual Object GetObject(String name) { return GetObjectInternal(name); } public virtual Object GetObject(String name, bool ignoreCase) { Object obj = GetObjectInternal(name); if (obj != null || !ignoreCase) return obj; return GetCaseInsensitiveObjectInternal(name); } protected virtual void ReadResources() { IDictionaryEnumerator en = Reader.GetEnumerator(); while (en.MoveNext()) { Object value = en.Value; Table.Add(en.Key, value); } // While technically possible to close the Reader here, don't close it // to help with some WinRes lifetime issues. } private Object GetObjectInternal(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); return copyOfTable[name]; } private Object GetCaseInsensitiveObjectInternal(String name) { Hashtable copyOfTable = Table; // Avoid a race with Dispose if (copyOfTable == null) throw new ObjectDisposedException(null, SR.ObjectDisposed_ResourceSet); Hashtable caseTable = _caseInsensitiveTable; // Avoid a race condition with Close if (caseTable == null) { caseTable = new Hashtable(StringComparer.OrdinalIgnoreCase); IDictionaryEnumerator en = copyOfTable.GetEnumerator(); while (en.MoveNext()) { caseTable.Add(en.Key, en.Value); } _caseInsensitiveTable = caseTable; } return caseTable[name]; } } }
using System; using System.IO; using System.Collections.Generic; using System.Linq; using RestSharp; using DocuSign.eSign.Client; using DocuSign.eSign.Model; namespace DocuSign.eSign.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IAuthenticationApi { /// <summary> /// Gets login information for a specified user. /// </summary> /// <remarks> /// Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </remarks> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>1LoginInformation</returns> LoginInformation Login (AuthenticationApi.LoginOptions options = null); /// <summary> /// Gets login information for a specified user. /// </summary> /// <remarks> /// Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </remarks> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>2ApiResponse of LoginInformation</returns> ApiResponse<LoginInformation> LoginWithHttpInfo (AuthenticationApi.LoginOptions options = null); /// <summary> /// Gets login information for a specified user. /// </summary> /// <remarks> /// Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </remarks> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>3Task of LoginInformation</returns> System.Threading.Tasks.Task<LoginInformation> LoginAsync (AuthenticationApi.LoginOptions options = null); /// <summary> /// Gets login information for a specified user. /// </summary> /// <remarks> /// Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </remarks> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>4Task of ApiResponse (LoginInformation)</returns> System.Threading.Tasks.Task<ApiResponse<LoginInformation>> LoginAsyncWithHttpInfo (AuthenticationApi.LoginOptions options = null); } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public class AuthenticationApi : IAuthenticationApi { /// <summary> /// Initializes a new instance of the <see cref="AuthenticationApi"/> class. /// </summary> /// <returns></returns> public AuthenticationApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); } /// <summary> /// Initializes a new instance of the <see cref="AuthenticationApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public AuthenticationApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuraiton.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Gets login information for a specified user. Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </summary> public class LoginOptions { /// Determines whether login settings are returned in the response.\n\nValid Values:\n\n* all - All the login settings are returned. \n* none - no login settings are returned. public string loginSettings {get; set;} /// When set to **true**, shows the account API password in the response. public string apiPassword {get; set;} /// When set to **true**, shows the account ID GUID in the response. public string includeAccountIdGuid {get; set;} } /// <summary> /// Gets login information for a specified user. Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </summary> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>5LoginInformation</returns> public LoginInformation Login (AuthenticationApi.LoginOptions options = null) { ApiResponse<LoginInformation> response = LoginWithHttpInfo(options); return response.Data; } /// <summary> /// Gets login information for a specified user. Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </summary> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>6ApiResponse of LoginInformation</returns> public ApiResponse< LoginInformation > LoginWithHttpInfo (AuthenticationApi.LoginOptions options = null) { var path_ = "/v2/login_information"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "application/json" }; String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (options != null) { if (options.loginSettings != null) queryParams.Add("login_settings", Configuration.ApiClient.ParameterToString(options.loginSettings)); // query parameter if (options.apiPassword != null) queryParams.Add("api_password", Configuration.ApiClient.ParameterToString(options.apiPassword)); // query parameter if (options.includeAccountIdGuid != null) queryParams.Add("include_account_id_guid", Configuration.ApiClient.ParameterToString(options.includeAccountIdGuid)); // query parameter } // make the HTTP request IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); int statusCode = (int) response.StatusCode; if (statusCode >= 400) throw new ApiException (statusCode, "Error calling Login: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException (statusCode, "Error calling Login: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<LoginInformation>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (LoginInformation) Configuration.ApiClient.Deserialize(response, typeof(LoginInformation))); } /// <summary> /// Gets login information for a specified user. Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </summary> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>7Task of LoginInformation</returns> public async System.Threading.Tasks.Task<LoginInformation> LoginAsync (AuthenticationApi.LoginOptions options = null) { ApiResponse<LoginInformation> response = await LoginAsyncWithHttpInfo(options); return response.Data; } /// <summary> /// Gets login information for a specified user. Retrieves login information for a specified user. Each account that is associated with the login credentials is listed. You can use the returned information to determine whether a user is authenticated and select an account to use in future operations. \n\nThe `baseUrl` property, returned in the response, is used in all future API calls as the base of the request URL. The `baseUrl` property contains the DocuSign server, the API version, and the `accountId` property that is used for the login. This request uses your DocuSign credentials to retrieve the account information. /// </summary> /// <param name="options">Options for modifying the behavior of the function.</param> /// <returns>8Task of ApiResponse (LoginInformation)</returns> public async System.Threading.Tasks.Task<ApiResponse<LoginInformation>> LoginAsyncWithHttpInfo (AuthenticationApi.LoginOptions options = null) { var path_ = "/v2/login_information"; var pathParams = new Dictionary<String, String>(); var queryParams = new Dictionary<String, String>(); var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader); var formParams = new Dictionary<String, String>(); var fileParams = new Dictionary<String, FileParameter>(); String postBody = null; // to determine the Accept header String[] http_header_accepts = new String[] { "application/json" }; String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); if (http_header_accept != null) headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (options != null) { if (options.loginSettings != null) queryParams.Add("login_settings", Configuration.ApiClient.ParameterToString(options.loginSettings)); // query parameter if (options.apiPassword != null) queryParams.Add("api_password", Configuration.ApiClient.ParameterToString(options.apiPassword)); // query parameter if (options.includeAccountIdGuid != null) queryParams.Add("include_account_id_guid", Configuration.ApiClient.ParameterToString(options.includeAccountIdGuid)); // query parameter } // make the HTTP request IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); int statusCode = (int) response.StatusCode; if (statusCode >= 400) throw new ApiException (statusCode, "Error calling Login: " + response.Content, response.Content); else if (statusCode == 0) throw new ApiException (statusCode, "Error calling Login: " + response.ErrorMessage, response.ErrorMessage); return new ApiResponse<LoginInformation>(statusCode, response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (LoginInformation) Configuration.ApiClient.Deserialize(response, typeof(LoginInformation))); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Net; using System.Reflection; using System.Text; using System.Xml; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Serialization; using OpenSim.Framework.Serialization.External; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.CoreModules.World.Terrain; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Archiver { /// <summary> /// Handles an individual archive read request /// </summary> public class ArchiveReadRequest { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static ASCIIEncoding m_asciiEncoding = new ASCIIEncoding(); private static UTF8Encoding m_utf8Encoding = new UTF8Encoding(); private Scene m_scene; private Stream m_loadStream; private Guid m_requestId; private string m_errorMessage; /// <value> /// Should the archive being loaded be merged with what is already on the region? /// </value> private bool m_merge; /// <summary> /// Used to cache lookups for valid uuids. /// </summary> private IDictionary<UUID, bool> m_validUserUuids = new Dictionary<UUID, bool>(); public ArchiveReadRequest(Scene scene, string loadPath, bool merge, Guid requestId) { m_scene = scene; m_loadStream = new GZipStream(GetStream(loadPath), CompressionMode.Decompress); m_errorMessage = String.Empty; m_merge = merge; m_requestId = requestId; } public ArchiveReadRequest(Scene scene, Stream loadStream, bool merge, Guid requestId) { m_scene = scene; m_loadStream = loadStream; m_merge = merge; m_requestId = requestId; } /// <summary> /// Dearchive the region embodied in this request. /// </summary> public void DearchiveRegion() { // The same code can handle dearchiving 0.1 and 0.2 OpenSim Archive versions DearchiveRegion0DotStar(); } private void DearchiveRegion0DotStar() { int successfulAssetRestores = 0; int failedAssetRestores = 0; List<string> serialisedSceneObjects = new List<string>(); List<string> serialisedParcels = new List<string>(); string filePath = "NONE"; try { TarArchiveReader archive = new TarArchiveReader(m_loadStream); byte[] data; TarArchiveReader.TarEntryType entryType; while ((data = archive.ReadEntry(out filePath, out entryType)) != null) { //m_log.DebugFormat( // "[ARCHIVER]: Successfully read {0} ({1} bytes)", filePath, data.Length); if (TarArchiveReader.TarEntryType.TYPE_DIRECTORY == entryType) continue; if (filePath.StartsWith(ArchiveConstants.OBJECTS_PATH)) { serialisedSceneObjects.Add(m_utf8Encoding.GetString(data)); } else if (filePath.StartsWith(ArchiveConstants.ASSETS_PATH)) { if (LoadAsset(filePath, data)) successfulAssetRestores++; else failedAssetRestores++; if ((successfulAssetRestores + failedAssetRestores) % 250 == 0) m_log.Debug("[ARCHIVER]: Loaded " + successfulAssetRestores + " assets and failed to load " + failedAssetRestores + " assets..."); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.TERRAINS_PATH)) { LoadTerrain(filePath, data); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.SETTINGS_PATH)) { LoadRegionSettings(filePath, data); } else if (!m_merge && filePath.StartsWith(ArchiveConstants.LANDDATA_PATH)) { serialisedParcels.Add(m_utf8Encoding.GetString(data)); } else if (filePath == ArchiveConstants.CONTROL_FILE_PATH) { LoadControlFile(filePath, data); } } //m_log.Debug("[ARCHIVER]: Reached end of archive"); archive.Close(); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Aborting load with error in archive file {0}. {1}", filePath, e); m_errorMessage += e.ToString(); m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage); return; } m_log.InfoFormat("[ARCHIVER]: Restored {0} assets", successfulAssetRestores); if (failedAssetRestores > 0) { m_log.ErrorFormat("[ARCHIVER]: Failed to load {0} assets", failedAssetRestores); m_errorMessage += String.Format("Failed to load {0} assets", failedAssetRestores); } if (!m_merge) { m_log.Info("[ARCHIVER]: Clearing all existing scene objects"); m_scene.DeleteAllSceneObjects(); } // Try to retain the original creator/owner/lastowner if their uuid is present on this grid // otherwise, use the master avatar uuid instead UUID masterAvatarId = m_scene.RegionInfo.MasterAvatarAssignedUUID; if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero) masterAvatarId = m_scene.RegionInfo.EstateSettings.EstateOwner; // Reload serialized parcels m_log.InfoFormat("[ARCHIVER]: Loading {0} parcels. Please wait.", serialisedParcels.Count); List<LandData> landData = new List<LandData>(); foreach (string serialisedParcel in serialisedParcels) { LandData parcel = LandDataSerializer.Deserialize(serialisedParcel); if (!ResolveUserUuid(parcel.OwnerID)) parcel.OwnerID = masterAvatarId; landData.Add(parcel); } m_scene.EventManager.TriggerIncomingLandDataFromStorage(landData); m_log.InfoFormat("[ARCHIVER]: Restored {0} parcels.", landData.Count); // Reload serialized prims m_log.InfoFormat("[ARCHIVER]: Loading {0} scene objects. Please wait.", serialisedSceneObjects.Count); IRegionSerialiserModule serialiser = m_scene.RequestModuleInterface<IRegionSerialiserModule>(); int sceneObjectsLoadedCount = 0; foreach (string serialisedSceneObject in serialisedSceneObjects) { /* m_log.DebugFormat("[ARCHIVER]: Loading xml with raw size {0}", serialisedSceneObject.Length); // Really large xml files (multi megabyte) appear to cause // memory problems // when loading the xml. But don't enable this check yet if (serialisedSceneObject.Length > 5000000) { m_log.Error("[ARCHIVER]: Ignoring xml since size > 5000000);"); continue; } */ SceneObjectGroup sceneObject = serialiser.DeserializeGroupFromXml2(serialisedSceneObject); // For now, give all incoming scene objects new uuids. This will allow scenes to be cloned // on the same region server and multiple examples a single object archive to be imported // to the same scene (when this is possible). sceneObject.ResetIDs(); foreach (SceneObjectPart part in sceneObject.Children.Values) { if (!ResolveUserUuid(part.CreatorID)) part.CreatorID = masterAvatarId; if (!ResolveUserUuid(part.OwnerID)) part.OwnerID = masterAvatarId; if (!ResolveUserUuid(part.LastOwnerID)) part.LastOwnerID = masterAvatarId; // And zap any troublesome sit target information part.SitTargetOrientation = new Quaternion(0, 0, 0, 1); part.SitTargetPosition = new Vector3(0, 0, 0); // Fix ownership/creator of inventory items // Not doing so results in inventory items // being no copy/no mod for everyone lock (part.TaskInventory) { TaskInventoryDictionary inv = part.TaskInventory; foreach (KeyValuePair<UUID, TaskInventoryItem> kvp in inv) { if (!ResolveUserUuid(kvp.Value.OwnerID)) { kvp.Value.OwnerID = masterAvatarId; } if (!ResolveUserUuid(kvp.Value.CreatorID)) { kvp.Value.CreatorID = masterAvatarId; } } } } if (m_scene.AddRestoredSceneObject(sceneObject, true, false)) { sceneObjectsLoadedCount++; sceneObject.CreateScriptInstances(0, false, m_scene.DefaultScriptEngine, 0); } } m_log.InfoFormat("[ARCHIVER]: Restored {0} scene objects to the scene", sceneObjectsLoadedCount); int ignoredObjects = serialisedSceneObjects.Count - sceneObjectsLoadedCount; if (ignoredObjects > 0) m_log.WarnFormat("[ARCHIVER]: Ignored {0} scene objects that already existed in the scene", ignoredObjects); m_log.InfoFormat("[ARCHIVER]: Successfully loaded archive"); m_scene.EventManager.TriggerOarFileLoaded(m_requestId, m_errorMessage); } /// <summary> /// Look up the given user id to check whether it's one that is valid for this grid. /// </summary> /// <param name="uuid"></param> /// <returns></returns> private bool ResolveUserUuid(UUID uuid) { if (!m_validUserUuids.ContainsKey(uuid)) { CachedUserInfo profile = m_scene.CommsManager.UserProfileCacheService.GetUserDetails(uuid); if (profile != null && profile.UserProfile != null) m_validUserUuids.Add(uuid, true); else m_validUserUuids.Add(uuid, false); } if (m_validUserUuids[uuid]) return true; else return false; } /// <summary> /// Load an asset /// </summary> /// <param name="assetFilename"></param> /// <param name="data"></param> /// <returns>true if asset was successfully loaded, false otherwise</returns> private bool LoadAsset(string assetPath, byte[] data) { // Right now we're nastily obtaining the UUID from the filename string filename = assetPath.Remove(0, ArchiveConstants.ASSETS_PATH.Length); int i = filename.LastIndexOf(ArchiveConstants.ASSET_EXTENSION_SEPARATOR); if (i == -1) { m_log.ErrorFormat( "[ARCHIVER]: Could not find extension information in asset path {0} since it's missing the separator {1}. Skipping", assetPath, ArchiveConstants.ASSET_EXTENSION_SEPARATOR); return false; } string extension = filename.Substring(i); string uuid = filename.Remove(filename.Length - extension.Length); if (ArchiveConstants.EXTENSION_TO_ASSET_TYPE.ContainsKey(extension)) { sbyte assetType = ArchiveConstants.EXTENSION_TO_ASSET_TYPE[extension]; //m_log.DebugFormat("[ARCHIVER]: Importing asset {0}, type {1}", uuid, assetType); AssetBase asset = new AssetBase(new UUID(uuid), String.Empty); asset.Type = assetType; asset.Data = data; // We're relying on the asset service to do the sensible thing and not store the asset if it already // exists. m_scene.AssetService.Store(asset); /** * Create layers on decode for image assets. This is likely to significantly increase the time to load archives so * it might be best done when dearchive takes place on a separate thread if (asset.Type=AssetType.Texture) { IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) cacheLayerDecode.syncdecode(asset.FullID, asset.Data); } */ return true; } else { m_log.ErrorFormat( "[ARCHIVER]: Tried to dearchive data with path {0} with an unknown type extension {1}", assetPath, extension); return false; } } /// <summary> /// Load region settings data /// </summary> /// <param name="settingsPath"></param> /// <param name="data"></param> /// <returns> /// true if settings were loaded successfully, false otherwise /// </returns> private bool LoadRegionSettings(string settingsPath, byte[] data) { RegionSettings loadedRegionSettings; try { loadedRegionSettings = RegionSettingsSerializer.Deserialize(data); } catch (Exception e) { m_log.ErrorFormat( "[ARCHIVER]: Could not parse region settings file {0}. Ignoring. Exception was {1}", settingsPath, e); return false; } RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings; currentRegionSettings.AgentLimit = loadedRegionSettings.AgentLimit; currentRegionSettings.AllowDamage = loadedRegionSettings.AllowDamage; currentRegionSettings.AllowLandJoinDivide = loadedRegionSettings.AllowLandJoinDivide; currentRegionSettings.AllowLandResell = loadedRegionSettings.AllowLandResell; currentRegionSettings.BlockFly = loadedRegionSettings.BlockFly; currentRegionSettings.BlockShowInSearch = loadedRegionSettings.BlockShowInSearch; currentRegionSettings.BlockTerraform = loadedRegionSettings.BlockTerraform; currentRegionSettings.DisableCollisions = loadedRegionSettings.DisableCollisions; currentRegionSettings.DisablePhysics = loadedRegionSettings.DisablePhysics; currentRegionSettings.DisableScripts = loadedRegionSettings.DisableScripts; currentRegionSettings.Elevation1NE = loadedRegionSettings.Elevation1NE; currentRegionSettings.Elevation1NW = loadedRegionSettings.Elevation1NW; currentRegionSettings.Elevation1SE = loadedRegionSettings.Elevation1SE; currentRegionSettings.Elevation1SW = loadedRegionSettings.Elevation1SW; currentRegionSettings.Elevation2NE = loadedRegionSettings.Elevation2NE; currentRegionSettings.Elevation2NW = loadedRegionSettings.Elevation2NW; currentRegionSettings.Elevation2SE = loadedRegionSettings.Elevation2SE; currentRegionSettings.Elevation2SW = loadedRegionSettings.Elevation2SW; currentRegionSettings.FixedSun = loadedRegionSettings.FixedSun; currentRegionSettings.ObjectBonus = loadedRegionSettings.ObjectBonus; currentRegionSettings.RestrictPushing = loadedRegionSettings.RestrictPushing; currentRegionSettings.TerrainLowerLimit = loadedRegionSettings.TerrainLowerLimit; currentRegionSettings.TerrainRaiseLimit = loadedRegionSettings.TerrainRaiseLimit; currentRegionSettings.TerrainTexture1 = loadedRegionSettings.TerrainTexture1; currentRegionSettings.TerrainTexture2 = loadedRegionSettings.TerrainTexture2; currentRegionSettings.TerrainTexture3 = loadedRegionSettings.TerrainTexture3; currentRegionSettings.TerrainTexture4 = loadedRegionSettings.TerrainTexture4; currentRegionSettings.UseEstateSun = loadedRegionSettings.UseEstateSun; currentRegionSettings.WaterHeight = loadedRegionSettings.WaterHeight; IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>(); estateModule.sendRegionHandshakeToAll(); return true; } /// <summary> /// Load terrain data /// </summary> /// <param name="terrainPath"></param> /// <param name="data"></param> /// <returns> /// true if terrain was resolved successfully, false otherwise. /// </returns> private bool LoadTerrain(string terrainPath, byte[] data) { ITerrainModule terrainModule = m_scene.RequestModuleInterface<ITerrainModule>(); MemoryStream ms = new MemoryStream(data); terrainModule.LoadFromStream(terrainPath, ms); ms.Close(); m_log.DebugFormat("[ARCHIVER]: Restored terrain {0}", terrainPath); return true; } /// <summary> /// Resolve path to a working FileStream /// </summary> private Stream GetStream(string path) { if (File.Exists(path)) { return new FileStream(path, FileMode.Open, FileAccess.Read); } else { try { Uri uri = new Uri(path); if (uri.Scheme == "file") { return new FileStream(uri.AbsolutePath, FileMode.Open, FileAccess.Read); } else { if (uri.Scheme != "http") throw new Exception(String.Format("Unsupported URI scheme ({0})", path)); // OK, now we know we have an HTTP URI to work with return URIFetch(uri); } } catch (UriFormatException) { // In many cases the user will put in a plain old filename that cannot be found so assume that // this is the problem rather than confusing the issue with a UriFormatException throw new Exception(String.Format("Cannot find file {0}", path)); } } } private static Stream URIFetch(Uri uri) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); // request.Credentials = credentials; request.ContentLength = 0; request.KeepAlive = false; WebResponse response = request.GetResponse(); Stream file = response.GetResponseStream(); if (response.ContentType != "application/x-oar") throw new Exception(String.Format("{0} does not identify an OAR file", uri.ToString())); if (response.ContentLength == 0) throw new Exception(String.Format("{0} returned an empty file", uri.ToString())); // return new BufferedStream(file, (int) response.ContentLength); return new BufferedStream(file, 1000000); } /// <summary> /// Load oar control file /// </summary> /// <param name="path"></param> /// <param name="data"></param> private void LoadControlFile(string path, byte[] data) { //Create the XmlNamespaceManager. NameTable nt = new NameTable(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(nt); // Create the XmlParserContext. XmlParserContext context = new XmlParserContext(null, nsmgr, null, XmlSpace.None); XmlTextReader xtr = new XmlTextReader(m_asciiEncoding.GetString(data), XmlNodeType.Document, context); RegionSettings currentRegionSettings = m_scene.RegionInfo.RegionSettings; // Loaded metadata will empty if no information exists in the archive currentRegionSettings.LoadedCreationDateTime = 0; currentRegionSettings.LoadedCreationID = ""; while (xtr.Read()) { if (xtr.NodeType == XmlNodeType.Element) { if (xtr.Name.ToString() == "datetime") { int value; if (Int32.TryParse(xtr.ReadElementContentAsString(), out value)) currentRegionSettings.LoadedCreationDateTime = value; } else if (xtr.Name.ToString() == "id") { currentRegionSettings.LoadedCreationID = xtr.ReadElementContentAsString(); } } } currentRegionSettings.Save(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Windows.Data; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// This is the view model for CodeStyle options page. /// </summary> /// <remarks> /// The codestyle options page is defined in <see cref="CodeStylePage"/> /// </remarks> internal class StyleViewModel : AbstractOptionPreviewViewModel { #region "Preview Text" private static readonly string s_fieldDeclarationPreviewTrue = @" class C{ int capacity; void Method() { //[ this.capacity = 0; //] } }"; private static readonly string s_fieldDeclarationPreviewFalse = @" class C{ int capacity; void Method() { //[ capacity = 0; //] } }"; private static readonly string s_propertyDeclarationPreviewTrue = @" class C{ public int Id { get; set; } void Method() { //[ this.Id = 0; //] } }"; private static readonly string s_propertyDeclarationPreviewFalse = @" class C{ public int Id { get; set; } void Method() { //[ Id = 0; //] } }"; private static readonly string s_eventDeclarationPreviewTrue = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ this.Elapsed += Handler; //] } }"; private static readonly string s_eventDeclarationPreviewFalse = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ Elapsed += Handler; //] } }"; private static readonly string s_methodDeclarationPreviewTrue = @" using System; class C{ void Display() { //[ this.Display(); //] } }"; private static readonly string s_methodDeclarationPreviewFalse = @" using System; class C{ void Display() { //[ Display(); //] } }"; private static readonly string s_intrinsicPreviewDeclarationTrue = @" class Program { //[ private int _member; static void M(int argument) { int local; } //] }"; private static readonly string s_intrinsicPreviewDeclarationFalse = @" using System; class Program { //[ private Int32 _member; static void M(Int32 argument) { Int32 local; } //] }"; private static readonly string s_intrinsicPreviewMemberAccessTrue = @" class Program { //[ static void M() { var local = int.MaxValue; } //] }"; private static readonly string s_intrinsicPreviewMemberAccessFalse = @" using System; class Program { //[ static void M() { var local = Int32.MaxValue; } //] }"; private static readonly string s_varForIntrinsicsPreviewFalse = @" using System; class C{ void Method() { //[ int x = 5; // built-in types //] } }"; private static readonly string s_varForIntrinsicsPreviewTrue = @" using System; class C{ void Method() { //[ var x = 5; // built-in types //] } }"; private static readonly string s_varWhereApparentPreviewFalse = @" using System; class C{ void Method() { //[ C cobj = new C(); // type is apparent from assignment expression //] } }"; private static readonly string s_varWhereApparentPreviewTrue = @" using System; class C{ void Method() { //[ var cobj = new C(); // type is apparent from assignment expression //] } }"; private static readonly string s_varWherePossiblePreviewFalse = @" using System; class C{ void Init() { //[ Action f = this.Init(); // everywhere else. //] } }"; private static readonly string s_varWherePossiblePreviewTrue = @" using System; class C{ void Init() { //[ var f = this.Init(); // everywhere else. //] } }"; #endregion internal StyleViewModel(OptionSet optionSet, IServiceProvider serviceProvider) : base(optionSet, serviceProvider, LanguageNames.CSharp) { var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems); collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName))); var qualifyGroupTitle = CSharpVSResources.this_preferences_colon; var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon; var varGroupTitle = CSharpVSResources.var_preferences_colon; var qualifyMemberAccessPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true), new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false), }; var predefinedTypesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true), new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false), }; var typeStylePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true), new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false), }; CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionSet, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CodeStyleOptions.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionSet, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeForIntrinsicTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWhereApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new SimpleCodeStyleOptionViewModel(CSharpCodeStyleOptions.UseImplicitTypeWherePossible, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionSet, varGroupTitle, typeStylePreferences)); } } }
using System; using System.ComponentModel; using System.Data; using System.Web; using System.Web.UI.WebControls; using Rainbow.Framework; using Rainbow.Framework.Settings; namespace Rainbow.Framework.Web.UI.WebControls { /// <summary> /// Binds tabular XML data to a datagrid, and allows add, editing, and deleting /// items from the XML file. /// Modified from Susan Warren's XmlEditGrid available on http://asp.net /// Rainbow version by Jes1111 - 15-June-2005 /// </summary> [ DefaultProperty("XmlFile") ] public class XmlEditGrid : DataGrid { // // Fields // private bool shouldRebind = false; private DataTable dt = null; private DataSet ds = null; // // Properties // /// <summary> /// Gets or sets the XML file. /// </summary> /// <value>The XML file.</value> [ Bindable(true), Category("Data"), Description("Xml file to edit.") ] public string XmlFile { get { string s = (string)ViewState["XmlFile"]; if (s == null) return String.Empty; return s; } set { ViewState["XmlFile"] = value; } } /// <summary> /// Gets or sets the edit text box CSS class. /// </summary> /// <value>The edit text box CSS class.</value> [ Bindable(true), Browsable(true), Category("Appearance"), Description("Name of CSS class to apply to textboxes in edit mode.") ] public string EditTextBoxCssClass { get { string s = (string)ViewState["EditTextBoxCssClass"]; if (s == null) return String.Empty; return s; } set { ViewState["EditTextBoxCssClass"] = value; } } #region Overridden DataGrid Methods /// <summary> /// OnInit() method -- Add the Edit and Delete columns to the grid /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnInit(EventArgs e) { // Test for Page to ensure this doesn't run at design time if (Page != null) { string imagePath = GetClientScriptPath(); EditCommandColumn c0 = new EditCommandColumn(); c0.EditText = "<img src='" + imagePath + "edit.gif' border=0 alt='" +General.GetString("XMLEDITGRID_EDITITEM", "edit this item") + "'>"; c0.CancelText = "<img src='" + imagePath + "cancel.gif' border=0 alt='" +General.GetString("XMLEDITGRID_CANCEL", "cancel") + "'>"; c0.UpdateText = "<img src='" + imagePath + "update.gif' border=0 alt='" +General.GetString("XMLEDITGRID_SAVE", "save changes") + "'>"; c0.ItemStyle.HorizontalAlign = HorizontalAlign.Center; c0.HeaderStyle.Width = new Unit("35px"); this.Columns.Add(c0); ButtonColumn c1 = new ButtonColumn(); c1.CommandName = "Delete"; c1.Text = "<img src='" + imagePath + "delete.gif' border=0 alt='" +General.GetString("XMLEDITGRID_DELETE", "delete this item") + "'>"; c1.ItemStyle.HorizontalAlign = HorizontalAlign.Center; c1.HeaderStyle.Width = new Unit("35px"); this.Columns.Add(c1); this.ShowFooter = true; this.ItemStyle.VerticalAlign = VerticalAlign.Top; } } /// <summary> /// OnLoad() method -- We read the XML file on each /// page request at runtime. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnLoad(EventArgs e) { // Test for Page to ensure this doesn't run at design time if (Page != null) { // get the data from the XML file ds = new DataSet(); ds.ReadXml(HttpContext.Current.Server.MapPath(XmlFile)); // set the datatable if (DataMember.Length != 0) dt = ds.Tables[DataMember]; else dt = ds.Tables[0]; } // should bind data on first page load if (!Page.IsPostBack) { shouldRebind = true; } } /// <summary> /// OnPageIndexChanged() method -- handles datagrid /// paging /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridPageChangedEventArgs"></see> that contains event data.</param> protected override void OnPageIndexChanged(DataGridPageChangedEventArgs e) { this.CurrentPageIndex = e.NewPageIndex; shouldRebind = true; } /// <summary> /// OnEditCommand() method -- puts the grid in edit mode /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"></see> that contains event data.</param> protected override void OnEditCommand(DataGridCommandEventArgs e) { this.EditItemIndex = e.Item.ItemIndex; shouldRebind = true; } /// <summary> /// OnCancelCommand() method -- cancels edit mode /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"></see> that contains event data.</param> protected override void OnCancelCommand(DataGridCommandEventArgs e) { this.EditItemIndex = -1; shouldRebind = true; } /// <summary> /// OnDeleteCommand() method -- cancels edit mode /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"></see> that contains event data.</param> protected override void OnDeleteCommand(DataGridCommandEventArgs e) { // remove the row that fired the command if (e.Item.DataSetIndex != 0) // don't allow first row to be deleted { dt.Rows.RemoveAt(e.Item.DataSetIndex); // save the updated data as the XML file SaveData(); this.EditItemIndex = -1; shouldRebind = true; } } /// <summary> /// OnUpdateCommand() method -- cancels edit mode /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridCommandEventArgs"></see> that contains event data.</param> protected override void OnUpdateCommand(DataGridCommandEventArgs e) { // get a reference to this row of data, using the DataSetIndex DataRow row = dt.Rows[e.Item.DataSetIndex]; // get the values and update the datarow for (int i = 0; i < dt.Columns.Count; i++) { // skip first two columns (Edit and delete columns) int j = i + 2; // get the value from the textbox and push it into the dataset TextBox t = (TextBox)e.Item.Cells[j].Controls[0]; row[dt.Columns[i].Caption] = HttpUtility.HtmlEncode(t.Text); } // save the updated data as the XML file SaveData(); // clear the edit item and rebind the grid this.EditItemIndex = -1; shouldRebind = true; } /// <summary> /// OnItemDataBound() method -- For the edit item, makes /// the textboxes multiline for long values /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridItemEventArgs"></see> that contains event data.</param> protected override void OnItemDataBound(DataGridItemEventArgs e) { // Buff up the appearance of textboxes in the Edit Item // Text for the edit item if ((ListItemType)e.Item.ItemType == ListItemType.EditItem) { foreach (TableCell c in e.Item.Controls) { if (c.Controls[0].GetType() == typeof(TextBox)) { TextBox t = (TextBox)c.Controls[0]; t.Text = HttpUtility.HtmlDecode(t.Text); // set style properties if (this.EditTextBoxCssClass.Length != 0) t.CssClass = this.EditTextBoxCssClass; else t.Style["width"] = "100%"; // if the data is really long, make this a textarea int rows = (t.Text.Length / 50) + 1; if (rows > 1) { // set the textbox to render as a textarea t.TextMode = TextBoxMode.MultiLine; t.Rows = rows + 3; } } } } } /// <summary> /// OnItemCreated() method --Add the "Add new item" link to /// the footer row /// </summary> /// <param name="e">A <see cref="T:System.Web.UI.WebControls.DataGridItemEventArgs"></see> that contains event data.</param> protected override void OnItemCreated(DataGridItemEventArgs e) { if ((ListItemType)e.Item.ItemType == ListItemType.Footer) { // The Footer row item (e.Item) is a TableRow that contains // one cell for each column in the grid. // Delete all of the current cells and insert a single one // that spans the entire row. // get the cell count, then clear the Cells collection int colcount = e.Item.Cells.Count; e.Item.Cells.Clear(); // create the new cell, and set it to span all of the columns TableCell c = new TableCell(); c.ColumnSpan = colcount; // create a LinkButton for adding a new item LinkButton l = new LinkButton(); l.Click += new EventHandler(AddItem); l.Text =General.GetString("XMLEDITGRID_ADD", "add new item"); l.CssClass = "CommandButton"; // Add the LinkButton to the cell, and the cell to the pager row c.Controls.Add(l); e.Item.Cells.AddAt(0, c); } } /// <summary> /// OnPreRender() method -- We bind in this method since /// it's called only at runtime /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnPreRender(EventArgs e) { if (shouldRebind) { this.DataSource = dt; this.DataBind(); } } /// <summary> /// Hide some properties on the base DataGrid /// </summary> /// <value></value> /// <returns>The name of the key field in the data source specified by <see cref="P:System.Web.UI.WebControls.BaseDataList.DataSource"></see>.</returns> [ Bindable(false), Browsable(false) ] public override string DataKeyField { get { return String.Empty; } set { } } /// <summary> /// Hide some properties on the base DataGrid /// </summary> /// <value></value> /// <returns>An <see cref="T:System.Collections.IEnumerable"></see> or <see cref="T:System.ComponentModel.IListSource"></see> that contains a collection of values used to supply data to this control. The default value is null.</returns> /// <exception cref="T:System.Web.HttpException">The data source cannot be resolved because a value is specified for both the <see cref="P:System.Web.UI.WebControls.BaseDataList.DataSource"></see> property and the <see cref="P:System.Web.UI.WebControls.BaseDataList.DataSourceID"></see> property. </exception> [ Bindable(false), Browsable(false) ] public override object DataSource { get { return base.DataSource; } set { base.DataSource = value; } } #endregion #region Helper methods /// <summary> /// SaveData() method -- writes the data back to the XML file /// </summary> public void SaveData() { // save the XML data to a file ds.WriteXml(HttpContext.Current.Server.MapPath(XmlFile)); } /// <summary> /// AddItem() method -- adds a new item to the end of the file /// </summary> /// <param name="Src">The SRC.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void AddItem(Object Src, EventArgs e) { // Create a new row DataRow r = dt.NewRow(); // initialize it for (int i = 0; i < dt.Columns.Count; i++) { r[dt.Columns[i].Caption] = ""; } // add it to the table dt.Rows.Add(r); // save the updated data as the XML file SaveData(); // set the edit index to the new row, and bind this.EditItemIndex = dt.Rows.Count - 1; shouldRebind = true; } /// <summary> /// GetClientScriptPath() method -- works out the /// location of the shared image files. /// </summary> /// <returns></returns> string GetClientScriptPath() { return Path.ApplicationRootPath("/DesktopModules/MagicUrls/"); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class Knight_Core_IndexedDictExpand_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { MethodBase method; Type[] args; Type type = typeof(Knight.Core.IndexedDictExpand); Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>(); List<MethodInfo> lst = null; foreach(var m in type.GetMethods()) { if(m.IsGenericMethodDefinition) { if (!genericMethods.TryGetValue(m.Name, out lst)) { lst = new List<MethodInfo>(); genericMethods[m.Name] = lst; } lst.Add(m); } } args = new Type[]{typeof(System.String), typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance)}; if (genericMethods.TryGetValue("TryGetValue", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(System.Boolean), typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(System.String), typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).MakeByRefType())) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, TryGetValue_0); break; } } } args = new Type[]{typeof(System.String), typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance)}; if (genericMethods.TryGetValue("Last", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(Knight.Core.CKeyValuePair<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, Last_1); break; } } } args = new Type[]{typeof(System.String), typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance)}; if (genericMethods.TryGetValue("Remove", out lst)) { foreach(var m in lst) { if(m.MatchGenericParameters(args, typeof(System.Boolean), typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>), typeof(System.String))) { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, Remove_2); break; } } } } static StackObject* TryGetValue_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 3); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ILRuntime.Runtime.Intepreter.ILTypeInstance @rValue = (ILRuntime.Runtime.Intepreter.ILTypeInstance)typeof(ILRuntime.Runtime.Intepreter.ILTypeInstance).CheckCLRTypes(__intp.RetriveObject(ptr_of_this_method, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); System.String @rKey = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance> @rIndexedDict = (Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); var result_of_this_method = Knight.Core.IndexedDictExpand.TryGetValue<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>(@rIndexedDict, @rKey, out @rValue); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = ILIntepreter.ResolveReference(ptr_of_this_method); object ___obj = @rValue; if (___dst->ObjectType >= ObjectTypes.Object) { if (___obj is CrossBindingAdaptorType) ___obj = ((CrossBindingAdaptorType)___obj).ILInstance; __mStack[___dst->Value] = ___obj; } else { ILIntepreter.UnboxObject(___dst, ___obj, __mStack, __domain); } } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = @rValue; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, @rValue); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = @rValue; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, @rValue); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as ILRuntime.Runtime.Intepreter.ILTypeInstance[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = @rValue; } break; } __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 3); __intp.Free(ptr_of_this_method); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } static StackObject* Last_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance> @rIndexedDict = (Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = Knight.Core.IndexedDictExpand.Last<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>(@rIndexedDict); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* Remove_2(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 2); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); System.String @key = (System.String)typeof(System.String).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); ptr_of_this_method = ILIntepreter.Minus(__esp, 2); Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance> @rIndexedDict = (Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>)typeof(Knight.Core.IndexedDict<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack)); __intp.Free(ptr_of_this_method); var result_of_this_method = Knight.Core.IndexedDictExpand.Remove<System.String, ILRuntime.Runtime.Intepreter.ILTypeInstance>(@rIndexedDict, @key); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdv = Google.Cloud.Dialogflow.V2; using sys = System; namespace Google.Cloud.Dialogflow.V2 { /// <summary>Resource name for the <c>Context</c> resource.</summary> public sealed partial class ContextName : gax::IResourceName, sys::IEquatable<ContextName> { /// <summary>The possible contents of <see cref="ContextName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> ProjectSessionContext = 1, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> ProjectEnvironmentUserSessionContext = 2, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> ProjectLocationSessionContext = 3, /// <summary> /// A resource name with pattern /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> ProjectLocationEnvironmentUserSessionContext = 4, } private static gax::PathTemplate s_projectSessionContext = new gax::PathTemplate("projects/{project}/agent/sessions/{session}/contexts/{context}"); private static gax::PathTemplate s_projectEnvironmentUserSessionContext = new gax::PathTemplate("projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}"); private static gax::PathTemplate s_projectLocationSessionContext = new gax::PathTemplate("projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}"); private static gax::PathTemplate s_projectLocationEnvironmentUserSessionContext = new gax::PathTemplate("projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}"); /// <summary>Creates a <see cref="ContextName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ContextName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ContextName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ContextName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ContextName"/> with the pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ContextName"/> constructed from the provided ids.</returns> public static ContextName FromProjectSessionContext(string projectId, string sessionId, string contextId) => new ContextName(ResourceNameType.ProjectSessionContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Creates a <see cref="ContextName"/> with the pattern /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ContextName"/> constructed from the provided ids.</returns> public static ContextName FromProjectEnvironmentUserSessionContext(string projectId, string environmentId, string userId, string sessionId, string contextId) => new ContextName(ResourceNameType.ProjectEnvironmentUserSessionContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Creates a <see cref="ContextName"/> with the pattern /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ContextName"/> constructed from the provided ids.</returns> public static ContextName FromProjectLocationSessionContext(string projectId, string locationId, string sessionId, string contextId) => new ContextName(ResourceNameType.ProjectLocationSessionContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Creates a <see cref="ContextName"/> with the pattern /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ContextName"/> constructed from the provided ids.</returns> public static ContextName FromProjectLocationEnvironmentUserSessionContext(string projectId, string locationId, string environmentId, string userId, string sessionId, string contextId) => new ContextName(ResourceNameType.ProjectLocationEnvironmentUserSessionContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), userId: gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </returns> public static string Format(string projectId, string sessionId, string contextId) => FormatProjectSessionContext(projectId, sessionId, contextId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c>. /// </returns> public static string FormatProjectSessionContext(string projectId, string sessionId, string contextId) => s_projectSessionContext.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </returns> public static string FormatProjectEnvironmentUserSessionContext(string projectId, string environmentId, string userId, string sessionId, string contextId) => s_projectEnvironmentUserSessionContext.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContextName"/> with pattern /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c>. /// </returns> public static string FormatProjectLocationSessionContext(string projectId, string locationId, string sessionId, string contextId) => s_projectLocationSessionContext.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContextName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="userId">The <c>User</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContextName"/> with pattern /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// . /// </returns> public static string FormatProjectLocationEnvironmentUserSessionContext(string projectId, string locationId, string environmentId, string userId, string sessionId, string contextId) => s_projectLocationEnvironmentUserSessionContext.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(userId, nameof(userId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))); /// <summary>Parses the given resource name string into a new <see cref="ContextName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/agent/sessions/{session}/contexts/{context}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ContextName"/> if successful.</returns> public static ContextName Parse(string contextName) => Parse(contextName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ContextName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/agent/sessions/{session}/contexts/{context}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ContextName"/> if successful.</returns> public static ContextName Parse(string contextName, bool allowUnparsed) => TryParse(contextName, allowUnparsed, out ContextName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ContextName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/agent/sessions/{session}/contexts/{context}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ContextName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string contextName, out ContextName result) => TryParse(contextName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ContextName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/agent/sessions/{session}/contexts/{context}</c></description> /// </item> /// <item> /// <description> /// <c>projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/agent/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// <item> /// <description> /// <c> /// projects/{project}/locations/{location}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="contextName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ContextName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string contextName, bool allowUnparsed, out ContextName result) { gax::GaxPreconditions.CheckNotNull(contextName, nameof(contextName)); gax::TemplatedResourceName resourceName; if (s_projectSessionContext.TryParseName(contextName, out resourceName)) { result = FromProjectSessionContext(resourceName[0], resourceName[1], resourceName[2]); return true; } if (s_projectEnvironmentUserSessionContext.TryParseName(contextName, out resourceName)) { result = FromProjectEnvironmentUserSessionContext(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (s_projectLocationSessionContext.TryParseName(contextName, out resourceName)) { result = FromProjectLocationSessionContext(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (s_projectLocationEnvironmentUserSessionContext.TryParseName(contextName, out resourceName)) { result = FromProjectLocationEnvironmentUserSessionContext(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4], resourceName[5]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(contextName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ContextName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string contextId = null, string environmentId = null, string locationId = null, string projectId = null, string sessionId = null, string userId = null) { Type = type; UnparsedResource = unparsedResourceName; ContextId = contextId; EnvironmentId = environmentId; LocationId = locationId; ProjectId = projectId; SessionId = sessionId; UserId = userId; } /// <summary> /// Constructs a new instance of a <see cref="ContextName"/> class from the component parts of pattern /// <c>projects/{project}/agent/sessions/{session}/contexts/{context}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contextId">The <c>Context</c> ID. Must not be <c>null</c> or empty.</param> public ContextName(string projectId, string sessionId, string contextId) : this(ResourceNameType.ProjectSessionContext, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId)), contextId: gax::GaxPreconditions.CheckNotNullOrEmpty(contextId, nameof(contextId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Context</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ContextId { get; } /// <summary> /// The <c>Environment</c> ID. May be <c>null</c>, depending on which resource name is contained by this /// instance. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>Location</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Session</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string SessionId { get; } /// <summary> /// The <c>User</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance. /// </summary> public string UserId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectSessionContext: return s_projectSessionContext.Expand(ProjectId, SessionId, ContextId); case ResourceNameType.ProjectEnvironmentUserSessionContext: return s_projectEnvironmentUserSessionContext.Expand(ProjectId, EnvironmentId, UserId, SessionId, ContextId); case ResourceNameType.ProjectLocationSessionContext: return s_projectLocationSessionContext.Expand(ProjectId, LocationId, SessionId, ContextId); case ResourceNameType.ProjectLocationEnvironmentUserSessionContext: return s_projectLocationEnvironmentUserSessionContext.Expand(ProjectId, LocationId, EnvironmentId, UserId, SessionId, ContextId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ContextName); /// <inheritdoc/> public bool Equals(ContextName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ContextName a, ContextName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ContextName a, ContextName b) => !(a == b); } public partial class Context { /// <summary> /// <see cref="gcdv::ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ContextName ContextName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ContextName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListContextsRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public SessionName ParentAsSessionName { get => string.IsNullOrEmpty(Parent) ? null : SessionName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetContextRequest { /// <summary> /// <see cref="gcdv::ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ContextName ContextName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ContextName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreateContextRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public SessionName ParentAsSessionName { get => string.IsNullOrEmpty(Parent) ? null : SessionName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteContextRequest { /// <summary> /// <see cref="gcdv::ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ContextName ContextName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ContextName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class DeleteAllContextsRequest { /// <summary> /// <see cref="SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public SessionName ParentAsSessionName { get => string.IsNullOrEmpty(Parent) ? null : SessionName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Services.Interfaces; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class AssetServicesConnector : BaseServiceConnector, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; private IImprovedAssetCache m_Cache = null; private int m_maxAssetRequestConcurrency = 30; private delegate void AssetRetrievedEx(AssetBase asset); // Keeps track of concurrent requests for the same asset, so that it's only loaded once. // Maps: Asset ID -> Handlers which will be called when the asset has been loaded private Dictionary<string, AssetRetrievedEx> m_AssetHandlers = new Dictionary<string, AssetRetrievedEx>(); public int MaxAssetRequestConcurrency { get { return m_maxAssetRequestConcurrency; } set { m_maxAssetRequestConcurrency = value; } } public AssetServicesConnector() { } public AssetServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public AssetServicesConnector(IConfigSource source) : base(source, "AssetService") { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig netconfig = source.Configs["Network"]; if (netconfig != null) m_maxAssetRequestConcurrency = netconfig.GetInt("MaxRequestConcurrency",m_maxAssetRequestConcurrency); IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[ASSET CONNECTOR]: AssetService missing from OpenSim.ini"); throw new Exception("Asset connector init error"); } string serviceURI = assetConfig.GetString("AssetServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[ASSET CONNECTOR]: No Server URI named in section AssetService"); throw new Exception("Asset connector init error"); } m_ServerURI = serviceURI; } protected void SetCache(IImprovedAssetCache cache) { m_Cache = cache; } public AssetBase Get(string id) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Synchronous get request for {0}", id); string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { // XXX: Commented out for now since this has either never been properly operational or not for some time // as m_maxAssetRequestConcurrency was being passed as the timeout, not a concurrency limiting option. // Wasn't noticed before because timeout wasn't actually used. // Not attempting concurrency setting for now as this omission was discovered in release candidate // phase for OpenSimulator 0.8. Need to revisit afterwards. // asset // = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>( // "GET", uri, 0, m_maxAssetRequestConcurrency); asset = SynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, m_Auth); if (m_Cache != null) m_Cache.Cache(asset); } return asset; } public AssetBase GetCached(string id) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Cache request for {0}", id); if (m_Cache != null) return m_Cache.Get(id); return null; } public AssetMetadata GetMetadata(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Metadata; } string uri = m_ServerURI + "/assets/" + id + "/metadata"; AssetMetadata asset = SynchronousRestObjectRequester.MakeRequest<int, AssetMetadata>("GET", uri, 0, m_Auth); return asset; } public byte[] GetData(string id) { if (m_Cache != null) { AssetBase fullAsset = m_Cache.Get(id); if (fullAsset != null) return fullAsset.Data; } using (RestClient rc = new RestClient(m_ServerURI)) { rc.AddResourcePath("assets"); rc.AddResourcePath(id); rc.AddResourcePath("data"); rc.RequestMethod = "GET"; Stream s = rc.Request(m_Auth); if (s == null) return null; if (s.Length > 0) { byte[] ret = new byte[s.Length]; s.Read(ret, 0, (int)s.Length); return ret; } return null; } } public bool Get(string id, Object sender, AssetRetrieved handler) { // m_log.DebugFormat("[ASSET SERVICE CONNECTOR]: Potentially asynchronous get request for {0}", id); string uri = m_ServerURI + "/assets/" + id; AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { lock (m_AssetHandlers) { AssetRetrievedEx handlerEx = new AssetRetrievedEx(delegate(AssetBase _asset) { handler(id, sender, _asset); }); AssetRetrievedEx handlers; if (m_AssetHandlers.TryGetValue(id, out handlers)) { // Someone else is already loading this asset. It will notify our handler when done. handlers += handlerEx; return true; } // Load the asset ourselves handlers += handlerEx; m_AssetHandlers.Add(id, handlers); } bool success = false; try { AsynchronousRestObjectRequester.MakeRequest<int, AssetBase>("GET", uri, 0, delegate(AssetBase a) { if (a != null && m_Cache != null) m_Cache.Cache(a); AssetRetrievedEx handlers; lock (m_AssetHandlers) { handlers = m_AssetHandlers[id]; m_AssetHandlers.Remove(id); } handlers.Invoke(a); }, m_maxAssetRequestConcurrency, m_Auth); success = true; } finally { if (!success) { lock (m_AssetHandlers) { m_AssetHandlers.Remove(id); } } } } else { handler(id, sender, asset); } return true; } public virtual bool[] AssetsExist(string[] ids) { string uri = m_ServerURI + "/get_assets_exist"; bool[] exist = null; try { exist = SynchronousRestObjectRequester.MakeRequest<string[], bool[]>("POST", uri, ids, m_Auth); } catch (Exception) { // This is most likely to happen because the server doesn't support this function, // so just silently return "doesn't exist" for all the assets. } if (exist == null) exist = new bool[ids.Length]; return exist; } public string Store(AssetBase asset) { if (asset.Local) { if (m_Cache != null) m_Cache.Cache(asset); return asset.ID; } string uri = m_ServerURI + "/assets/"; string newID; try { newID = SynchronousRestObjectRequester.MakeRequest<AssetBase, string>("POST", uri, asset, m_Auth); } catch (Exception e) { m_log.Warn(string.Format("[ASSET CONNECTOR]: Unable to send asset {0} to asset server. Reason: {1} ", asset.ID, e.Message), e); return string.Empty; } // TEMPORARY: SRAS returns 'null' when it's asked to store existing assets if (newID == null) { m_log.DebugFormat("[ASSET CONNECTOR]: Storing of asset {0} returned null; assuming the asset already exists", asset.ID); return asset.ID; } if (string.IsNullOrEmpty(newID)) return string.Empty; asset.ID = newID; if (m_Cache != null) m_Cache.Cache(asset); return newID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = null; if (m_Cache != null) asset = m_Cache.Get(id); if (asset == null) { AssetMetadata metadata = GetMetadata(id); if (metadata == null) return false; asset = new AssetBase(metadata.FullID, metadata.Name, metadata.Type, UUID.Zero.ToString()); asset.Metadata = metadata; } asset.Data = data; string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester.MakeRequest<AssetBase, bool>("POST", uri, asset, m_Auth)) { if (m_Cache != null) m_Cache.Cache(asset); return true; } return false; } public bool Delete(string id) { string uri = m_ServerURI + "/assets/" + id; if (SynchronousRestObjectRequester.MakeRequest<int, bool>("DELETE", uri, 0, m_Auth)) { if (m_Cache != null) m_Cache.Expire(id); return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using Xunit.Abstractions; using System.IO; using System.Xml.Schema; using System.Xml.XPath; namespace System.Xml.Tests { //[TestCase(Name = "TC_SchemaSet_Misc", Desc = "")] public class TC_SchemaSet_Misc : TC_SchemaSetBase { private ITestOutputHelper _output; public TC_SchemaSet_Misc(ITestOutputHelper output) { _output = output; } public bool bWarningCallback; public bool bErrorCallback; public int errorCount; public int warningCount; public bool WarningInnerExceptionSet = false; public bool ErrorInnerExceptionSet = false; private void Initialize() { bWarningCallback = bErrorCallback = false; errorCount = warningCount = 0; WarningInnerExceptionSet = ErrorInnerExceptionSet = false; } //hook up validaton callback private void ValidationCallback(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING: "); bWarningCallback = true; warningCount++; WarningInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + WarningInnerExceptionSet + "\n"); } else if (args.Severity == XmlSeverityType.Error) { _output.WriteLine("ERROR: "); bErrorCallback = true; errorCount++; ErrorInnerExceptionSet = (args.Exception.InnerException != null); _output.WriteLine("\nInnerExceptionSet : " + ErrorInnerExceptionSet + "\n"); } _output.WriteLine(args.Message); // Print the error to the screen. } //----------------------------------------------------------------------------------- //[Variation(Desc = "v1 - Bug110823 - SchemaSet.Add is holding onto some of the schema files after adding", Priority = 1)] [Fact] public void v1() { XmlSchemaSet xss = new XmlSchemaSet(); xss.XmlResolver = new XmlUrlResolver(); using (XmlTextReader xtr = new XmlTextReader(Path.Combine(TestData._Root, "bug110823.xsd"))) { xss.Add(XmlSchema.Read(xtr, null)); } } //[Variation(Desc = "v2 - Bug115049 - XSD: content model validation for an invalid root element should be abandoned", Priority = 2)] [Fact] public void v2() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, "bug115049.xsd")); ss.Compile(); //create reader XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.Schemas.Add(ss); XmlReader vr = XmlReader.Create(Path.Combine(TestData._Root, "bug115049.xml"), settings); while (vr.Read()) ; CError.Compare(errorCount, 1, "Error Count mismatch!"); return; } //[Variation(Desc = "v4 - 243300 - We are not correctly handling xs:anyType as xsi:type in the instance", Priority = 2)] [Fact] public void v4() { string xml = @"<a xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xsi:type='xsd:anyType'>1242<b/></a>"; Initialize(); XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = new XmlUrlResolver(); settings.ValidationType = ValidationType.Schema; settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation | XmlSchemaValidationFlags.ProcessInlineSchema; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReader vr = XmlReader.Create(new StringReader(xml), settings, (string)null); while (vr.Read()) ; CError.Compare(errorCount, 0, "Error Count mismatch!"); CError.Compare(warningCount, 1, "Warning Count mismatch!"); return; } /* Parameters = file name , is custom xml namespace System.Xml.Tests */ //[Variation(Desc = "v20 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v10.xsd", 2, false })] [InlineData("bug264908_v10.xsd", 2, false)] //[Variation(Desc = "v19 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v9.xsd", 5, true })] [InlineData("bug264908_v9.xsd", 5, true)] //[Variation(Desc = "v18 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v8.xsd", 5, false })] [InlineData("bug264908_v8.xsd", 5, false)] //[Variation(Desc = "v17 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v7.xsd", 4, false })] [InlineData("bug264908_v7.xsd", 4, false)] //[Variation(Desc = "v16 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v6.xsd", 4, true })] [InlineData("bug264908_v6.xsd", 4, true)] //[Variation(Desc = "v15 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v5.xsd", 4, false })] [InlineData("bug264908_v5.xsd", 4, false)] //[Variation(Desc = "v14 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v4.xsd", 4, true })] [InlineData("bug264908_v4.xsd", 4, true)] //[Variation(Desc = "v13 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v3.xsd", 1, true })] [InlineData("bug264908_v3.xsd", 1, true)] //[Variation(Desc = "v12 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v2.xsd", 1, true })] [InlineData("bug264908_v2.xsd", 1, true)] //[Variation(Desc = "v11 - DCR 264908 - XSD: Support user specified schema for http://www.w3.org/XML/1998/namespace System.Xml.Tests", Priority = 1, Params = new object[] { "bug264908_v1.xsd", 3, true })] [InlineData("bug264908_v1.xsd", 3, true)] [Theory] public void v10(object param0, object param1, object param2) { string xmlFile = param0.ToString(); int count = (int)param1; bool custom = (bool)param2; string attName = "blah"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, xmlFile)); ss.Compile(); //test the count CError.Compare(ss.Count, count, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set if (custom) { foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } return; } //[Variation(Desc = "v21 - Bug 319346 - Chameleon add of a schema into the xml namespace", Priority = 1)] [Fact] public void v20() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; string attName = "blah"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(xmlns, Path.Combine(TestData._Root, "bug264908_v11.xsd")); ss.Compile(); //test the count CError.Compare(ss.Count, 3, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } //[Variation(Desc = "v22 - Bug 338038 - Component should be additive into the Xml namespace", Priority = 1)] [Fact] public void v21() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; string attName = "blah1"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v1.xsd")); ss.Compile(); //test the count CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); //make sure the correct schema is in the set foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) return; } Assert.True(false); } //[Variation(Desc = "v23 - Bug 338038 - Conflicting components in custome xml namespace System.Xml.Tests be caught", Priority = 1)] [Fact] public void v22() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(xmlns, Path.Combine(TestData._Root, "bug338038_v2.xsd")); try { ss.Compile(); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); return; } Assert.True(false); } //[Variation(Desc = "v24 - Bug 338038 - Change type of xml:lang to decimal in custome xml namespace System.Xml.Tests", Priority = 1)] [Fact] public void v24() { string attName = "lang"; string newtype = "decimal"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd")); ss.Compile(); CError.Compare(ss.Count, 4, "Count of SchemaSet not matched!"); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == attName) { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, newtype, "Incorrect type for xml:lang"); return; } } Assert.True(false); } //[Variation(Desc = "v25 - Bug 338038 - Conflicting definitions for xml attributes in two schemas", Priority = 1)] [Fact] public void v25() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3a.xsd")); ss.Compile(); try { ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3b.xsd")); ss.Compile(); } catch (XmlSchemaException e) { _output.WriteLine(e.Message); CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } Assert.True(false); } //[Variation(Desc = "v26 - Bug 338038 - Change type of xml:lang to decimal and xml:base to short in two steps", Priority = 1)] [Fact] public void v26() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4b.xsd")); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "lang") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "decimal", "Incorrect type for xml:lang"); } if (a.QualifiedName.Name == "base") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "short", "Incorrect type for xml:base"); } } CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } //[Variation(Desc = "v27 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests", Priority = 1)] [Fact] public void v27() { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd")); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "blah") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang"); } } CError.Compare(ss.Count, 6, "Count of SchemaSet not matched!"); return; } //[Variation(Desc = "v28 - Bug 338038 - Add new attributes to the already present xml namespace System.Xml.Tests, remove default ns schema", Priority = 1)] [Fact] public void v28() { string xmlns = @"http://www.w3.org/XML/1998/namespace"; XmlSchema schema = null; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v3.xsd")); ss.Compile(); foreach (XmlSchema s in ss.Schemas(xmlns)) { schema = s; } ss.Add(null, Path.Combine(TestData._Root, "bug338038_v4a.xsd")); ss.Compile(); ss.Add(null, Path.Combine(TestData._Root, "bug338038_v5b.xsd")); ss.Compile(); ss.Remove(schema); ss.Compile(); foreach (XmlSchemaAttribute a in ss.GlobalAttributes.Values) { if (a.QualifiedName.Name == "blah") { CError.Compare(a.AttributeSchemaType.QualifiedName.Name, "int", "Incorrect type for xml:lang"); } } CError.Compare(ss.Count, 5, "Count of SchemaSet not matched!"); return; } //Regressions - Bug Fixes private void Callback1(object sender, ValidationEventArgs args) { if (args.Severity == XmlSeverityType.Warning) { _output.WriteLine("WARNING Recieved"); bWarningCallback = true; warningCount++; CError.Compare(args.Exception.InnerException == null, false, "Inner Exception not set"); } } //[Variation(Desc = "v100 - Bug 320502 - XmlSchemaSet: while throwing a warning for invalid externals we do not set the inner exception", Priority = 1)] [Fact] public void v100() { string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:include schemaLocation='bogus'/></xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(Callback1); ss.Add(null, new XmlTextReader(new StringReader(xsd))); ss.Compile(); CError.Compare(warningCount, 1, "Warning Count mismatch!"); return; } //[Variation(Desc = "v101 - Bug 339706 - XmlSchemaSet: Compile on the set fails when a compiled schema containing notation is already present", Priority = 1)] [Fact] public void v101() { string xsd1 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:notation name='a' public='a'/></xs:schema>"; string xsd2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='root'/></xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(Callback1); ss.Add(null, new XmlTextReader(new StringReader(xsd1))); ss.Compile(); ss.Add(null, new XmlTextReader(new StringReader(xsd2))); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v102 - Bug 337850 - XmlSchemaSet: Type already declared error when redefined schema is added to the set before the redefining schema.", Priority = 1)] [Fact] public void v102() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(null, Path.Combine(TestData._Root, "schZ013c.xsd")); ss.Add(null, Path.Combine(TestData._Root, "schZ013a.xsd")); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v104 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled SOM.", Priority = 1, Params = new object[] { false })] [InlineData(false)] //[Variation(Desc = "v103 - CodeCoverage- XmlSchemaSet: add precompiled subs groups, global elements, attributes and types to another compiled set.", Priority = 1, Params = new object[] { true })] [InlineData(true)] [Theory] public void v103(object param0) { bool addset = (bool)param0; Initialize(); XmlSchemaSet ss1 = new XmlSchemaSet(); ss1.XmlResolver = new XmlUrlResolver(); ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss1.Add(null, Path.Combine(TestData._Root, "Misc103_x.xsd")); ss1.Compile(); CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!"); XmlSchemaSet ss2 = new XmlSchemaSet(); ss2.XmlResolver = new XmlUrlResolver(); ss2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s = ss2.Add(null, Path.Combine(TestData._Root, "Misc103_a.xsd")); ss2.Compile(); CError.Compare(ss1.Count, 1, "Schema Set 1 Count mismatch!"); if (addset) { ss1.Add(ss2); CError.Compare(ss1.GlobalElements.Count, 7, "Schema Set 1 GlobalElements Count mismatch!"); CError.Compare(ss1.GlobalAttributes.Count, 2, "Schema Set 1 GlobalAttributes Count mismatch!"); CError.Compare(ss1.GlobalTypes.Count, 6, "Schema Set 1 GlobalTypes Count mismatch!"); } else { ss1.Add(s); CError.Compare(ss1.GlobalElements.Count, 2, "Schema Set 1 GlobalElements Count mismatch!"); CError.Compare(ss1.GlobalAttributes.Count, 0, "Schema Set 1 GlobalAttributes Count mismatch!"); CError.Compare(ss1.GlobalTypes.Count, 2, "Schema Set 1 GlobalTypes Count mismatch!"); } /***********************************************/ XmlSchemaSet ss3 = new XmlSchemaSet(); ss3.XmlResolver = new XmlUrlResolver(); ss3.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss3.Add(null, Path.Combine(TestData._Root, "Misc103_c.xsd")); ss3.Compile(); ss1.Add(ss3); CError.Compare(ss1.GlobalElements.Count, 8, "Schema Set 1 GlobalElements Count mismatch!"); return; } //[Variation(Desc = "v103 - Reference to a component from no namespace System.Xml.Tests an explicit import of no namespace System.Xml.Tests throw a validation warning", Priority = 1)] [Fact] public void v105() { Initialize(); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add(null, Path.Combine(TestData._Root, "Misc105.xsd")); CError.Compare(warningCount, 1, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v106 - Adding a compiled SoS(schema for schema) to a set causes type collision error", Priority = 1)] [Fact] public void v106() { Initialize(); XmlSchemaSet ss1 = new XmlSchemaSet(); ss1.XmlResolver = new XmlUrlResolver(); ss1.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlReaderSettings settings = new XmlReaderSettings(); #pragma warning disable 0618 settings.ProhibitDtd = false; #pragma warning restore 0618 XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "XMLSchema.xsd"), settings); ss1.Add(null, r); ss1.Compile(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); foreach (XmlSchema s in ss1.Schemas()) { ss.Add(s); } ss.Add(null, Path.Combine(TestData._Root, "xsdauthor.xsd")); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v107 - XsdValidatingReader: InnerException not set on validation warning of a schemaLocation not loaded.", Priority = 1)] [Fact] public void v107() { string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='a bug356711_a.xsd' xmlns:a='a'></root>"; Initialize(); XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); schemaSet.Add(null, Path.Combine(TestData._Root, "bug356711_root.xsd")); XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = new XmlUrlResolver(); settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation; settings.Schemas.Add(schemaSet); settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.ValidationType = ValidationType.Schema; XmlReader vr = XmlReader.Create(new StringReader(strXml), settings); while (vr.Read()) ; CError.Compare(warningCount, 1, "Warning Count mismatch!"); CError.Compare(WarningInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v108 - XmlSchemaSet.Add() should not trust compiled state of the schema being added", Priority = 1)] [Fact] public void v108() { string strSchema1 = @" <xs:schema targetNamespace='http://bar' xmlns='http://bar' xmlns:x='http://foo' elementFormDefault='qualified' attributeFormDefault='unqualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:import namespace='http://foo'/> <xs:element name='bar'> <xs:complexType> <xs:sequence> <xs:element ref='x:foo'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> "; string strSchema2 = @"<xs:schema targetNamespace='http://foo' xmlns='http://foo' xmlns:x='http://bar' elementFormDefault='qualified' attributeFormDefault='unqualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:import namespace='http://bar'/> <xs:element name='foo'> <xs:complexType> <xs:sequence> <xs:element ref='x:bar'/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; Initialize(); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); ValidationEventHandler handler = new ValidationEventHandler(ValidationCallback); set.ValidationEventHandler += handler; XmlSchema s1 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema1))) { s1 = XmlSchema.Read(r, handler); set.Add(s1); } set.Compile(); // Now load set 2 set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s2 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema2))) { s2 = XmlSchema.Read(r, handler); } XmlSchemaImport import = (XmlSchemaImport)s2.Includes[0]; import.Schema = s1; import = (XmlSchemaImport)s1.Includes[0]; import.Schema = s2; set.Add(s1); set.Reprocess(s1); set.Add(s2); set.Reprocess(s2); set.Compile(); s2 = null; using (XmlReader r = XmlReader.Create(new StringReader(strSchema2))) { s2 = XmlSchema.Read(r, handler); } set = new XmlSchemaSet(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); import = (XmlSchemaImport)s2.Includes[0]; import.Schema = s1; import = (XmlSchemaImport)s1.Includes[0]; import.Schema = s2; set.Add(s1); set.Reprocess(s1); set.Add(s2); set.Reprocess(s2); set.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch"); return; } //[Variation(Desc = "v109 - 386243, Adding a chameleon schema against to no namespace throws unexpected warnings", Priority = 1)] [Fact] public void v109() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); ss.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd")); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v110 - 386246, ArgumentException 'item arleady added' error on a chameleon add done twice", Priority = 1)] [Fact] public void v110() { Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema s1 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); XmlSchema s2 = ss.Add("http://EmployeeTest.org", Path.Combine(TestData._Root, "EmployeeTypes.xsd")); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v111 - 380805, Chameleon include compiled in one set added to another", Priority = 1)] [Fact] public void v111() { Initialize(); XmlSchemaSet newSet = new XmlSchemaSet(); newSet.XmlResolver = new XmlUrlResolver(); newSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema chameleon = newSet.Add(null, Path.Combine(TestData._Root, "EmployeeTypes.xsd")); newSet.Compile(); CError.Compare(newSet.GlobalTypes.Count, 10, "GlobalTypes count mismatch!"); XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); sc.Add(chameleon); sc.Add(null, Path.Combine(TestData._Root, "baseEmployee.xsd")); sc.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v112 - 382035, schema set tables not cleared as expected on reprocess", Priority = 1)] [Fact] public void v112() { Initialize(); XmlSchemaSet set2 = new XmlSchemaSet(); set2.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema includedSchema = set2.Add(null, Path.Combine(TestData._Root, "bug382035a1.xsd")); set2.Compile(); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); XmlSchema mainSchema = set.Add(null, Path.Combine(TestData._Root, "bug382035a.xsd")); set.Compile(); XmlReader r = XmlReader.Create(Path.Combine(TestData._Root, "bug382035a1.xsd")); XmlSchema reParsedInclude = XmlSchema.Read(r, new ValidationEventHandler(ValidationCallback)); ((XmlSchemaExternal)mainSchema.Includes[0]).Schema = reParsedInclude; set.Reprocess(mainSchema); set.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "v113 - Set InnerException on XmlSchemaValidationException while parsing typed values", Priority = 1)] [Fact] public void v113() { string strXml = @"<root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema' xsi:type='xs:int'>a</root>"; Initialize(); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessSchemaLocation; settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); settings.ValidationType = ValidationType.Schema; XmlReader vr = XmlReader.Create(new StringReader(strXml), settings); while (vr.Read()) ; CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v114 - XmlSchemaSet: InnerException not set on parse errors during schema compilation", Priority = 1)] [Fact] public void v114() { string strXsd = @"<xs:schema elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='date' type='date'/> <xs:simpleType name='date'> <xs:restriction base='xs:int'> <xs:enumeration value='a'/> </xs:restriction> </xs:simpleType> </xs:schema>"; Initialize(); XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(XmlSchema.Read(new StringReader(strXsd), new ValidationEventHandler(ValidationCallback))); ss.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); CError.Compare(ErrorInnerExceptionSet, true, "Inner Exception not set!"); return; } //[Variation(Desc = "v116 - 405327 NullReferenceExceptions while accessing obsolete properties in the SOM", Priority = 1)] [Fact] public void v116() { #pragma warning disable 0618 XmlSchemaAttribute attribute = new XmlSchemaAttribute(); object attributeType = attribute.AttributeType; XmlSchemaElement element = new XmlSchemaElement(); object elementType = element.ElementType; XmlSchemaType schemaType = new XmlSchemaType(); object BaseSchemaType = schemaType.BaseSchemaType; #pragma warning restore 0618 } //[Variation(Desc = "v117 - 398474 InnerException not set on XmlSchemaException, when xs:pattern has an invalid regular expression", Priority = 1)] [Fact] public void v117() { string strXsdv117 = @"<?xml version='1.0' encoding='utf-8' ?> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='doc'> <xs:complexType> <xs:sequence> <xs:element name='value' maxOccurs='unbounded'> <xs:simpleType> <xs:restriction base='xs:string'> <xs:pattern value='(?r:foo)'/> </xs:restriction> </xs:simpleType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; Initialize(); using (StringReader reader = new StringReader(strXsdv117)) { XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); ss.Add(XmlSchema.Read(reader, ValidationCallback)); ss.Compile(); CError.Compare(ErrorInnerExceptionSet, true, "\nInner Exception not set\n"); } return; } //[Variation(Desc = "v118 - 424904 Not getting unhandled attributes on particle", Priority = 1)] [Fact] public void v118() { using (XmlReader r = new XmlTextReader(Path.Combine(TestData._Root, "Bug424904.xsd"))) { XmlSchema s = XmlSchema.Read(r, null); XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.Add(s); set.Compile(); XmlQualifiedName name = new XmlQualifiedName("test2", "http://foo"); XmlSchemaComplexType test2type = s.SchemaTypes[name] as XmlSchemaComplexType; XmlSchemaParticle p = test2type.ContentTypeParticle; XmlAttribute[] att = p.UnhandledAttributes; Assert.False(att == null || att.Length < 1); } } //[Variation(Desc = "v120 - 397633 line number and position not set on the validation error for an invalid xsi:type value", Priority = 1)] [Fact] public void v120() { using (XmlReader schemaReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xsd"))) { XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.Add("", schemaReader); sc.Compile(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = sc; using (XmlReader docValidatingReader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings)) { XmlDocument doc = new XmlDocument(); try { doc.Load(docValidatingReader); doc.Validate(null); } catch (XmlSchemaValidationException ex) { if (ex.LineNumber == 1 && ex.LinePosition == 2 && !string.IsNullOrEmpty(ex.SourceUri)) { return; } } } } Assert.True(false); } //[Variation(Desc = "v120a.XmlDocument.Load non-validating reader.Expect IOE.")] [Fact] public void v120a() { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; using (XmlReader reader = XmlReader.Create(Path.Combine(TestData._Root, "Bug397633.xml"), readerSettings)) { XmlDocument doc = new XmlDocument(); try { doc.Load(reader); doc.Validate(null); } catch (XmlSchemaValidationException ex) { _output.WriteLine(ex.Message); return; } } Assert.True(false); } //[Variation(Desc = "444196: XmlReader.MoveToNextAttribute returns incorrect results")] [Fact] public void v124() { Initialize(); string XamlPresentationNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; string XamlToParse = "<pfx0:DrawingBrush TileMode=\"Tile\" Viewbox=\"foobar\" />"; string xml = " <xs:schema " + " xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" + " xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"" + " targetNamespace=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " + " elementFormDefault=\"qualified\" " + " attributeFormDefault=\"unqualified\"" + " >" + "" + " <xs:element name=\"DrawingBrush\" type=\"DrawingBrushType\" />" + "" + " <xs:complexType name=\"DrawingBrushType\">" + " <xs:attribute name=\"Viewbox\" type=\"xs:string\" />" + " <xs:attribute name=\"TileMode\" type=\"xs:string\" />" + " </xs:complexType>" + " </xs:schema>"; XmlSchema schema = XmlSchema.Read(new StringReader(xml), null); schema.TargetNamespace = XamlPresentationNamespace; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.Add(schema); schemaSet.Compile(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ConformanceLevel = ConformanceLevel.Fragment; readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; NameTable nameTable = new NameTable(); XmlNamespaceManager namespaces = new XmlNamespaceManager(nameTable); namespaces.AddNamespace("pfx0", XamlPresentationNamespace); namespaces.AddNamespace(string.Empty, XamlPresentationNamespace); XmlParserContext parserContext = new XmlParserContext(nameTable, namespaces, null, null, null, null, null, null, XmlSpace.None); using (XmlReader xmlReader = XmlReader.Create(new StringReader(XamlToParse), readerSettings, parserContext)) { xmlReader.Read(); xmlReader.MoveToAttribute(0); xmlReader.MoveToNextAttribute(); xmlReader.MoveToNextAttribute(); xmlReader.MoveToNextAttribute(); xmlReader.MoveToAttribute(0); if (xmlReader.MoveToNextAttribute()) return; } Assert.True(false); } //[Variation(Desc = "615444 XmlSchema.Write ((XmlWriter)null) throws InvalidOperationException instead of ArgumentNullException")] [Fact] public void v125() { XmlSchema xs = new XmlSchema(); try { xs.Write((XmlWriter)null); } catch (InvalidOperationException) { return; } Assert.True(false); } //[Variation(Desc = "Dev10_40561 Redefine Chameleon: Unexpected qualified name on local particle")] [Fact] public void Dev10_40561() { Initialize(); string xml = @"<?xml version='1.0' encoding='utf-8'?><e1 xmlns='ns-a'> <c23 xmlns='ns-b'/></e1>"; XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); string path = Path.Combine(TestData.StandardPath, "xsd10", "SCHEMA", "schN11_a.xsd"); set.Add(null, path); set.Compile(); XmlReaderSettings settings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Schema; settings.Schemas = set; using (XmlReader reader = XmlReader.Create(new StringReader(xml), settings)) { try { while (reader.Read()) ; _output.WriteLine("XmlSchemaValidationException was not thrown"); Assert.True(false); } catch (XmlSchemaValidationException e) { _output.WriteLine(e.Message); } } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } // Test failure on ILC: Test depends on Xml Serialization and requires reflection on a LOT of types under System.Xml.Schema namespace. // Rd.xml with "<Namespace Name="System.Xml.Schema" Dynamic="Required Public" />" lets this test pass but we should probably be // fixing up XmlSerializer's own rd.xml rather than the test here. [Fact] public void GetBuiltinSimpleTypeWorksAsEcpected() { Initialize(); string xml = "<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine + " <xs:simpleType>" + Environment.NewLine + " <xs:restriction base=\"xs:anySimpleType\" />" + Environment.NewLine + " </xs:simpleType>" + Environment.NewLine + "</xs:schema>"; XmlSchema schema = new XmlSchema(); XmlSchemaSimpleType stringType = XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String); schema.Items.Add(stringType); StringWriter sw = new StringWriter(); schema.Write(sw); CError.Compare(sw.ToString(), xml, "Mismatch"); return; } //[Variation(Desc = "Dev10_40509 Assert and NRE when validate the XML against the XSD")] [Fact] public void Dev10_40509() { Initialize(); string xml = Path.Combine(TestData._Root, "bug511217.xml"); string xsd = Path.Combine(TestData._Root, "bug511217.xsd"); XmlSchemaSet s = new XmlSchemaSet(); s.XmlResolver = new XmlUrlResolver(); XmlReader r = XmlReader.Create(xsd); s.Add(null, r); s.Compile(); XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; using (XmlReader docValidatingReader = XmlReader.Create(xml, rs)) { XmlDocument doc = new XmlDocument(); doc.Load(docValidatingReader); doc.Schemas = s; doc.Validate(null); } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_40511 XmlSchemaSet::Compile throws XmlSchemaException for valid schema")] [Fact] public void Dev10_40511() { Initialize(); string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:simpleType name='textType'> <xs:restriction base='xs:string'> <xs:minLength value='1' /> </xs:restriction> </xs:simpleType> <xs:simpleType name='statusCodeType'> <xs:restriction base='textType'> <xs:length value='6' /> </xs:restriction> </xs:simpleType> </xs:schema>"; XmlSchemaSet sc = new XmlSchemaSet(); sc.XmlResolver = new XmlUrlResolver(); sc.Add("xs", XmlReader.Create(new StringReader(xsd))); sc.Compile(); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_40495 Undefined ComplexType error when loading schemas from in memory strings")] [Fact] public void Dev10_40495() { Initialize(); const string schema1Str = @"<xs:schema xmlns:tns=""http://BizTalk_Server_Project2.Schema1"" xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" targetNamespace=""http://BizTalk_Server_Project2.Schema1"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:include schemaLocation=""S3"" /> <xs:include schemaLocation=""S2"" /> <xs:element name=""Root""> <xs:complexType> <xs:sequence> <xs:element name=""FxTypeElement""> <xs:complexType> <xs:complexContent mixed=""false""> <xs:extension base=""tns:FxType""> <xs:attribute name=""Field"" type=""xs:string"" /> </xs:extension> </xs:complexContent> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; const string schema2Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:complexType name=""FxType""> <xs:attribute name=""Fx2"" type=""xs:string"" /> </xs:complexType> </xs:schema>"; const string schema3Str = @"<xs:schema xmlns:b=""http://schemas.microsoft.com/BizTalk/2003"" attributeFormDefault=""unqualified"" elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:complexType name=""TestType""> <xs:attribute name=""Fx2"" type=""xs:string"" /> </xs:complexType> </xs:schema>"; XmlSchema schema1 = XmlSchema.Read(new StringReader(schema1Str), null); XmlSchema schema2 = XmlSchema.Read(new StringReader(schema2Str), null); XmlSchema schema3 = XmlSchema.Read(new StringReader(schema3Str), null); //schema1 has some xs:includes in it. Since all schemas are string based, XmlSchema on its own cannot load automatically //load these included schemas. We will resolve these schema locations schema1 and make them point to the correct //in memory XmlSchema objects ((XmlSchemaExternal)schema1.Includes[0]).Schema = schema3; ((XmlSchemaExternal)schema1.Includes[1]).Schema = schema2; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallback); if (schemaSet.Add(schema1) != null) { //This compile will complain about Undefined complex Type tns:FxType and schemaSet_ValidationEventHandler will be //called with this error. schemaSet.Compile(); schemaSet.Reprocess(schema1); } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "Dev10_64765 XmlSchemaValidationException.SourceObject is always null when using XPathNavigator.CheckValidity method")] [Fact] public void Dev10_64765() { Initialize(); string xsd = "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + "<xsd:element name='some'>" + "</xsd:element>" + "</xsd:schema>"; string xml = "<root/>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); ValidateXPathNavigator(xml, CompileSchemaSet(xsd)); return; } private void ValidateXPathNavigator(string xml, XmlSchemaSet schemaSet) { XPathDocument doc = new XPathDocument(new StringReader(xml)); XPathNavigator nav = doc.CreateNavigator(); ValidateXPathNavigator(nav, schemaSet); } private void ValidateXPathNavigator(XPathNavigator nav, XmlSchemaSet schemaSet) { _output.WriteLine(nav.CheckValidity(schemaSet, OnValidationEvent) ? "Validation succeeded." : "Validation failed."); } private XmlSchemaSet CompileSchemaSet(string xsd) { XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.XmlResolver = new XmlUrlResolver(); schemaSet.Add(XmlSchema.Read(new StringReader(xsd), OnValidationEvent)); schemaSet.ValidationEventHandler += OnValidationEvent; schemaSet.Compile(); return schemaSet; } private void OnValidationEvent(object sender, ValidationEventArgs e) { XmlSchemaValidationException exception = e.Exception as XmlSchemaValidationException; if (exception == null || exception.SourceObject == null) { CError.Compare(exception != null, "exception == null"); CError.Compare(exception.SourceObject != null, "SourceObject == null"); return; } CError.Compare(exception.SourceObject.GetType().ToString(), "MS.Internal.Xml.Cache.XPathDocumentNavigator", "SourceObject.GetType"); _output.WriteLine("Exc: " + exception); } //[Variation(Desc = "Dev10_40563 XmlSchemaSet: Assert Failure with Chk Build.")] [Fact] public void Dev10_40563() { Initialize(); string xsd = "<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" + "<xsd:element name='some'>" + "</xsd:element>" + "</xsd:schema>"; XmlSchemaSet ss = new XmlSchemaSet(); ss.XmlResolver = new XmlUrlResolver(); ss.Add("http://www.w3.org/2001/XMLSchema", XmlReader.Create(new StringReader(xsd))); XmlReaderSettings rs = new XmlReaderSettings(); rs.ValidationType = ValidationType.Schema; rs.Schemas = ss; string input = "<root xml:space='default'/>"; using (XmlReader r1 = XmlReader.Create(new StringReader(input), rs)) { using (XmlReader r2 = XmlReader.Create(new StringReader(input), rs)) { while (r1.Read()) ; while (r2.Read()) ; } } CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 0, "Error Count mismatch!"); return; } //[Variation(Desc = "TFS_470020 Schema with substitution groups does not throw when content model is ambiguous")] [Fact] public void TFS_470020() { Initialize(); string xml = @"<?xml version='1.0' encoding='utf-8' ?> <e3> <e2>1</e2> <e2>1</e2> </e3>"; string xsd = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' elementFormDefault='qualified'> <xs:element name='e1' type='xs:int'/> <xs:element name='e2' type='xs:int' substitutionGroup='e1'/> <xs:complexType name='t3'> <xs:sequence> <xs:element ref='e1' minOccurs='0' maxOccurs='1'/> <xs:element name='e2' type='xs:int' minOccurs='0' maxOccurs='1'/> </xs:sequence> </xs:complexType> <xs:element name='e3' type='t3'/> </xs:schema>"; XmlSchemaSet set = new XmlSchemaSet(); set.XmlResolver = new XmlUrlResolver(); set.Add(null, XmlReader.Create(new StringReader(xsd))); XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); doc.Schemas = set; doc.Validate(ValidationCallback); CError.Compare(warningCount, 0, "Warning Count mismatch!"); CError.Compare(errorCount, 1, "Error Count mismatch!"); return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTLib2.Bioinfo { public partial class Universe { public class ConjugateGradientOption { //int iterInitial = 0; // * index of initial iteration //double k = 0.0001; // * step step //double max_atom_movement = 0.1; // * maximum atom movement //double threshold = 0.001; // * threshold for forces.NormInf //int randomPurturb = 0; // * add random purturbation when (iter % randomPurturb == 0) // // no random purturbation if (randomPurturb == 0) //bool[] atomsMovable = null; // * selection of movable atoms // move all atoms if (atomsMovable == null) or (atomsMovable[all] == true) // move only atom whose (atomsMovable[id] == true) IMinimizeLogger logger = new MinimizeLogger_PrintEnergyForceMag(); // * write log } public int Minimize_ConjugateGradient_v1(int iterInitial, List<ForceField.IForceField> frcflds, double? k, double max_atom_movement, int? max_iteration, double threshold, int randomPurturb, bool[] atomsMovable, IMinimizeLogger logger, InfoPack extra, bool? doSteepDeescent // null or true for default ) { if(doSteepDeescent == null) doSteepDeescent = true; if(k == null) { k = double.MaxValue; foreach(ForceField.IForceField frcfld in frcflds) { double? kk = frcfld.GetDefaultMinimizeStep(); if(kk.HasValue) k = Math.Min(k.Value, kk.Value); } } // double k = 0.0001; int iter = iterInitial; // 0. Initial configuration of atoms Vectors coords = GetCoords(); if(atomsMovable == null) { atomsMovable = new bool[size]; for(int i=0; i<size; i++) atomsMovable[i] = true; } Vectors h = GetVectorsZero(); Vectors forces = null; Dictionary<string,object> cache = new Dictionary<string, object>(); double energy = GetPotential(frcflds, coords, out forces, cache); double forces_NormInf = NormInf(forces, atomsMovable); double forces_Norm1 = Norm(1, forces, atomsMovable); double forces_Norm2 = Norm(2, forces, atomsMovable); Vectors forces0 = forces; double energy0 = energy; while(true) { if(forces.IsComputable == false) { System.Console.Error.WriteLine("non-computable components while doing steepest-descent"); HEnvironment.Exit(0); } if(logger != null) { logger.log(iter, coords, energy, forces, atomsMovable); logger.logTrajectory(this, iter, coords); //if(iter %10 == 0) //{ // System.IO.Directory.CreateDirectory("output"); // string pdbname = string.Format("mini.conju.{0:D5}.pdb", iter); // pdb.ToFile("output\\"+pdbname, coords.ToArray()); // System.IO.File.AppendAllLines("output\\mini.conju.[animation].pml", new string[] { "load "+pdbname+", 1A6G" }); //} } // 1. Save the position of atoms // 2. Calculate the potential energy of system and the net forces on atoms // 3. Check if every force reaches to zero, // , and END if yes bool stopIteration = false; if(forces_NormInf < threshold) stopIteration = true; if((max_iteration != null) && (iter>=max_iteration.Value)) stopIteration = true; if(stopIteration) { // double check cache = new Dictionary<string, object>(); // reset cache energy = GetPotential(frcflds, coords, out forces, cache); forces_NormInf = NormInf(forces, atomsMovable); forces_Norm1 = Norm(1, forces, atomsMovable); forces_Norm2 = Norm(2, forces, atomsMovable); // This is already checked by "if(forces_NormInf < threshold) stopIteration = true;" //if(forces_NormInf < threshold) ///////////////////////////////////////////////////// { if(iter != 1) { SetCoords((Vector[])coords); } //{ // string pdbname = string.Format("mini.conju.{0:D5}.pdb", iter); // pdb.ToFile("output\\"+pdbname, coords.ToArray()); // System.IO.File.AppendAllLines("output\\mini.conju.[animation].pml", new string[] { "load "+pdbname+", 1A6G" }); //} if(extra != null) { extra.SetValue("energy", energy); extra.SetValue("forces", forces); extra.SetValue("forces norm-1", forces_Norm1); extra.SetValue("forces norm-2", forces_Norm2); extra.SetValue("forces norm-inf", forces_NormInf); extra.SetValue("iter", iter); } return iter; } } // 4. Move atoms with conjugated gradient Vectors coords_prd; { if((iter > 0) && (iter % 100 == 0)) { cache = new Dictionary<string, object>(); // reset cache } if((randomPurturb > 0) && (iter % randomPurturb == 0)) { Vectors dcoords = GetVectorsRandom(); dcoords *= max_atom_movement; coords = AddConditional(coords, dcoords, atomsMovable); } if(iter > 1) { HDebug.Assert(forces0 != null); double r = Vectors.VtV(forces, forces).Sum() / Vectors.VtV(forces0, forces0).Sum(); h = forces + r * h; double kk = k.Value; double hNormInf = NormInf(h, atomsMovable); if(kk*hNormInf > max_atom_movement) // make the maximum movement as atomsMovable kk = max_atom_movement/(hNormInf); //double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf()); //double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h,atomsMovable)); coords_prd = AddConditional(coords, kk * h, atomsMovable); } else { // same to the steepest descent for the first iteration h = forces; double kk = k.Value; double hNormInf = NormInf(h, atomsMovable); if(kk*hNormInf > max_atom_movement) // make the maximum movement as atomsMovable kk = max_atom_movement/(hNormInf); //double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf()); //double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h, atomsMovable)); coords_prd = AddConditional(coords, kk * h, atomsMovable); } } // 5. Predict energy or forces on atoms Vectors forces_prd; double energy_prd = GetPotential(frcflds, coords_prd, out forces_prd, cache); iter++; double forces_prd_NormInf = NormInf(forces_prd, atomsMovable); double forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable); double forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable); // 6. Check if the predicted forces or energy will exceed over the limit // , and goto 1 if no doSteepDeescent = true; //if((doSteepDeescent == false) || ((energy_prd <= energy) && (forces_prd_NormInf < forces_NormInf+1.0)) if((energy_prd < energy+0.1) && (forces_prd_NormInf < forces_NormInf+0.0001)) { energy0 = energy; forces0 = forces; coords = coords_prd; forces = forces_prd; energy = energy_prd; forces_NormInf = forces_prd_NormInf; forces_Norm1 = forces_prd_Norm1; forces_Norm2 = forces_prd_Norm2; continue; } if(logger != null) logger.log(iter, coords_prd, energy_prd, forces_prd, atomsMovable, "will do steepest"); // 7. Back to saved configuration // 8. Move atoms with simple gradient { // same to the steepest descent h = forces; double kk = k.Value; double hNormInf = NormInf(h, atomsMovable); if(kk*hNormInf > max_atom_movement) // make the maximum movement as atomsMovable kk = max_atom_movement/(hNormInf); //double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf()); //double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h, atomsMovable)); coords_prd = AddConditional(coords, kk * h, atomsMovable); //if(randomPurturb) //{ // Vectors dcoords = GetForcesRandom(); // dcoords *= (0.1*max_atom_movement); // coords += dcoords; //} } energy_prd = GetPotential(frcflds, coords_prd, out forces_prd, cache); forces_prd_NormInf = NormInf(forces_prd, atomsMovable); forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable); forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable); energy0 = energy; forces0 = forces; coords = coords_prd; forces = forces_prd; energy = energy_prd; forces_NormInf = forces_prd_NormInf; forces_Norm1 = forces_prd_Norm1; forces_Norm2 = forces_prd_Norm2; // 9. goto 1 } } } }