context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Threading.Tasks; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Internal methods internal async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException(nameof(ReadContentAsBase64)); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Fail($"Unexpected state {_state}"); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException(nameof(ReadContentAsBinHex)); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Fail($"Unexpected state {_state}"); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBase64)); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Fail($"Unexpected state {_state}"); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException(nameof(count)); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException(nameof(ReadElementContentAsBinHex)); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Fail($"Unexpected state {_state}"); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task FinishAsync() { if (_state != State.None) { while (await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) ; if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); } } Reset(); } // Private methods private async Task<bool> InitAsync() { // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private async Task<bool> InitOnElementAsync() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element await _reader.ReadAsync().ConfigureAwait(false); if (isEmpty) { return false; } // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element await _reader.ReadAsync().ConfigureAwait(false); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private async Task<int> ReadContentAsBinaryAsync(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); while (true) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { while (true) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = await _reader.GetValueAsync().ConfigureAwait(false); int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) { _isEnd = true; return _decoder.DecodedCount; } } } private async Task<int> ReadElementContentAsBinaryAsync(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); _state = State.None; return 0; } private async Task<bool> MoveToNextContentNodeAsync(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (await _reader.ReadAsync().ConfigureAwait(false)); return false; } } }
// 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.Immutable; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.Completion; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Moq; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Completion { public abstract class AbstractCompletionProviderTests<TWorkspaceFixture> : TestBase, IClassFixture<TWorkspaceFixture> where TWorkspaceFixture : TestWorkspaceFixture, new() { protected readonly Mock<ICompletionSession> MockCompletionSession; protected TWorkspaceFixture WorkspaceFixture; protected AbstractCompletionProviderTests(TWorkspaceFixture workspaceFixture) { MockCompletionSession = new Mock<ICompletionSession>(MockBehavior.Strict); this.WorkspaceFixture = workspaceFixture; } public override void Dispose() { this.WorkspaceFixture.CloseTextViewAsync().Wait(); base.Dispose(); } protected static async Task<bool> CanUseSpeculativeSemanticModelAsync(Document document, int position) { var service = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var node = (await document.GetSyntaxRootAsync()).FindToken(position).Parent; return !service.GetMemberBodySpanForSpeculativeBinding(node).IsEmpty; } internal CompletionServiceWithProviders GetCompletionService(Workspace workspace) { return CreateCompletionService(workspace, ImmutableArray.Create(CreateCompletionProvider())); } internal abstract CompletionServiceWithProviders CreateCompletionService( Workspace workspace, ImmutableArray<CompletionProvider> exclusiveProviders); protected abstract string ItemPartiallyWritten(string expectedItemOrNull); protected abstract Task<TestWorkspace> CreateWorkspaceAsync(string fileContents); protected abstract Task BaseVerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority); internal static CompletionHelper GetCompletionHelper(Document document) { return CompletionHelper.GetHelper(document); } internal Task<CompletionList> GetCompletionListAsync( CompletionService service, Document document, int position, CompletionTrigger triggerInfo, OptionSet options = null) { return service.GetCompletionsAsync(document, position, triggerInfo, options: options); } protected async Task CheckResultsAsync( Document document, int position, string expectedItemOrNull, string expectedDescriptionOrNull, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { var code = (await document.GetTextAsync()).ToString(); CompletionTrigger trigger = CompletionTrigger.Default; if (usePreviousCharAsTrigger) { trigger = CompletionTrigger.CreateInsertionTrigger(insertedCharacter: code.ElementAt(position - 1)); } var completionService = GetCompletionService(document.Project.Solution.Workspace); var completionList = await GetCompletionListAsync(completionService, document, position, trigger); var items = completionList == null ? ImmutableArray<CompletionItem>.Empty : completionList.Items; if (checkForAbsence) { if (items == null) { return; } if (expectedItemOrNull == null) { Assert.Empty(items); } else { AssertEx.None( items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true)); } } else { if (expectedItemOrNull == null) { Assert.NotEmpty(items); } else { AssertEx.Any(items, c => CompareItems(c.DisplayText, expectedItemOrNull) && (expectedDescriptionOrNull != null ? completionService.GetDescriptionAsync(document, c).Result.Text == expectedDescriptionOrNull : true) && (glyph.HasValue ? c.Tags.SequenceEqual(GlyphTags.GetTags((Glyph)glyph.Value)) : true) && (matchPriority.HasValue ? (int)c.Rules.MatchPriority == matchPriority.Value : true )); } } } private Task VerifyAsync( string markup, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { MarkupTestFile.GetPosition(markup.NormalizeLineEndings(), out var code, out int position); return VerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected async Task VerifyCustomCommitProviderAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind? sourceCodeKind = null, char? commitChar = null) { MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out var code, out int position); if (sourceCodeKind.HasValue) { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, sourceCodeKind.Value, commitChar); } else { await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Regular, commitChar); await VerifyCustomCommitProviderWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, SourceCodeKind.Script, commitChar); } } protected async Task VerifyProviderCommitAsync(string markupBeforeCommit, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind? sourceCodeKind = null) { MarkupTestFile.GetPosition(markupBeforeCommit.NormalizeLineEndings(), out var code, out int position); expectedCodeAfterCommit = expectedCodeAfterCommit.NormalizeLineEndings(); if (sourceCodeKind.HasValue) { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, sourceCodeKind.Value); } else { await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Regular); await VerifyProviderCommitWorkerAsync(code, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar, SourceCodeKind.Script); } } protected virtual bool CompareItems(string actualItem, string expectedItem) { return actualItem.Equals(expectedItem); } protected async Task VerifyItemExistsAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false, int? glyph = null, int? matchPriority = null) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); } else { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: false, glyph: glyph, matchPriority: matchPriority); } } protected async Task VerifyItemIsAbsentAsync( string markup, string expectedItem, string expectedDescriptionOrNull = null, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, sourceCodeKind.Value, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Regular, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItem, expectedDescriptionOrNull, SourceCodeKind.Script, usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } } protected async Task VerifyAnyItemExistsAsync( string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: false, glyph: null, matchPriority: null); } } protected async Task VerifyNoItemsExistAsync(string markup, SourceCodeKind? sourceCodeKind = null, bool usePreviousCharAsTrigger = false) { if (sourceCodeKind.HasValue) { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind.Value, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } else { await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); await VerifyAsync(markup, expectedItemOrNull: null, expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: usePreviousCharAsTrigger, checkForAbsence: true, glyph: null, matchPriority: null); } } internal abstract CompletionProvider CreateCompletionProvider(); /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="code">The source code (not markup).</param> /// <param name="expectedItemOrNull">The expected item. If this is null, verifies that *any* item shows up for this CompletionProvider (or no items show up if checkForAbsence is true).</param> /// <param name="expectedDescriptionOrNull">If this is null, the Description for the item is ignored.</param> /// <param name="usePreviousCharAsTrigger">Whether or not the previous character in markup should be used to trigger IntelliSense for this provider. If false, invokes it through the invoke IntelliSense command.</param> /// <param name="checkForAbsence">If true, checks for absence of a specific item (or that no items are returned from this CompletionProvider)</param> protected virtual async Task VerifyWorkerAsync( string code, int position, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool usePreviousCharAsTrigger, bool checkForAbsence, int? glyph, int? matchPriority) { Glyph? expectedGlyph = null; if (glyph.HasValue) { expectedGlyph = (Glyph)glyph.Value; } var document1 = await WorkspaceFixture.UpdateDocumentAsync(code, sourceCodeKind); await CheckResultsAsync(document1, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = await WorkspaceFixture.UpdateDocumentAsync(code, sourceCodeKind, cleanBeforeUpdate: false); await CheckResultsAsync(document2, position, expectedItemOrNull, expectedDescriptionOrNull, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyCustomCommitProviderWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, SourceCodeKind sourceCodeKind, char? commitChar = null) { var document1 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind); await VerifyCustomCommitProviderCheckResultsAsync(document1, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyCustomCommitProviderCheckResultsAsync(document2, codeBeforeCommit, position, itemToCommit, expectedCodeAfterCommit, commitChar); } } private async Task VerifyCustomCommitProviderCheckResultsAsync(Document document, string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar) { var workspace = await WorkspaceFixture.GetWorkspaceAsync(); SetWorkspaceOptions(workspace); var textBuffer = workspace.Documents.Single().TextBuffer; var service = GetCompletionService(workspace); var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Default)).Items; var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); var customCommitCompletionProvider = service.ExclusiveProviders?[0] as ICustomCommitCompletionProvider; if (customCommitCompletionProvider != null) { var completionRules = GetCompletionHelper(document); var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView(); VerifyCustomCommitWorker(service, customCommitCompletionProvider, firstItem, completionRules, textView, textBuffer, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } else { await VerifyCustomCommitWorkerAsync(service, document, firstItem, codeBeforeCommit, expectedCodeAfterCommit, commitChar); } } protected virtual void SetWorkspaceOptions(TestWorkspace workspace) { } internal async Task VerifyCustomCommitWorkerAsync( CompletionServiceWithProviders service, Document document, CompletionItem completionItem, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } var commit = await service.GetChangeAsync(document, completionItem, commitChar, CancellationToken.None); var text = await document.GetTextAsync(); var newText = text.WithChanges(commit.TextChange); var newDoc = document.WithText(newText); document.Project.Solution.Workspace.TryApplyChanges(newDoc.Project.Solution); var textBuffer = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().TextBuffer; var textView = (await WorkspaceFixture.GetWorkspaceAsync()).Documents.Single().GetTextView(); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = commit.NewPosition != null ? commit.NewPosition.Value : textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } internal virtual void VerifyCustomCommitWorker( CompletionService service, ICustomCommitCompletionProvider customCommitCompletionProvider, CompletionItem completionItem, CompletionHelper completionRules, ITextView textView, ITextBuffer textBuffer, string codeBeforeCommit, string expectedCodeAfterCommit, char? commitChar = null) { MarkupTestFile.GetPosition(expectedCodeAfterCommit, out var actualExpectedCode, out int expectedCaretPosition); if (commitChar.HasValue && !Controller.IsCommitCharacter(service.GetRules(), completionItem, commitChar.Value, commitChar.Value.ToString())) { Assert.Equal(codeBeforeCommit, actualExpectedCode); return; } customCommitCompletionProvider.Commit(completionItem, textView, textBuffer, textView.TextSnapshot, commitChar); string actualCodeAfterCommit = textBuffer.CurrentSnapshot.AsText().ToString(); var caretPosition = textView.Caret.Position.BufferPosition.Position; Assert.Equal(actualExpectedCode, actualCodeAfterCommit); Assert.Equal(expectedCaretPosition, caretPosition); } /// <summary> /// Override this to change parameters or return without verifying anything, e.g. for script sources. Or to test in other code contexts. /// </summary> /// <param name="codeBeforeCommit">The source code (not markup).</param> /// <param name="position">Position where intellisense is invoked.</param> /// <param name="itemToCommit">The item to commit from the completion provider.</param> /// <param name="expectedCodeAfterCommit">The expected code after commit.</param> protected virtual async Task VerifyProviderCommitWorkerAsync(string codeBeforeCommit, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitChar, string textTypedSoFar, SourceCodeKind sourceCodeKind) { var document1 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind); await VerifyProviderCommitCheckResultsAsync(document1, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); if (await CanUseSpeculativeSemanticModelAsync(document1, position)) { var document2 = await WorkspaceFixture.UpdateDocumentAsync(codeBeforeCommit, sourceCodeKind, cleanBeforeUpdate: false); await VerifyProviderCommitCheckResultsAsync(document2, position, itemToCommit, expectedCodeAfterCommit, commitChar, textTypedSoFar); } } private async Task VerifyProviderCommitCheckResultsAsync( Document document, int position, string itemToCommit, string expectedCodeAfterCommit, char? commitCharOpt, string textTypedSoFar) { var workspace = await WorkspaceFixture.GetWorkspaceAsync(); var textBuffer = workspace.Documents.Single().TextBuffer; var textSnapshot = textBuffer.CurrentSnapshot.AsText(); var service = GetCompletionService(workspace); var items = (await GetCompletionListAsync(service, document, position, CompletionTrigger.Default)).Items; var firstItem = items.First(i => CompareItems(i.DisplayText, itemToCommit)); var completionRules = GetCompletionHelper(document); var commitChar = commitCharOpt ?? '\t'; var text = await document.GetTextAsync(); if (commitChar == '\t' || Controller.IsCommitCharacter(service.GetRules(), firstItem, commitChar, textTypedSoFar + commitChar)) { var textChange = (await service.GetChangeAsync(document, firstItem, commitChar, CancellationToken.None)).TextChange; // Adjust TextChange to include commit character, so long as it isn't TAB. if (commitChar != '\t') { textChange = new TextChange(textChange.Span, textChange.NewText.TrimEnd(commitChar) + commitChar); } text = text.WithChanges(textChange); } else { // nothing was committed, but we should insert the commit character. var textChange = new TextChange(new TextSpan(firstItem.Span.End, 0), commitChar.ToString()); text = text.WithChanges(textChange); } Assert.Equal(expectedCodeAfterCommit, text.ToString()); } protected async Task VerifyItemInEditorBrowsableContextsAsync( string markup, string referencedCode, string item, int expectedSymbolsSameSolution, int expectedSymbolsMetadataReference, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers = false) { await VerifyItemWithMetadataReferenceAsync(markup, referencedCode, item, expectedSymbolsMetadataReference, sourceLanguage, referencedLanguage, hideAdvancedMembers); await VerifyItemWithProjectReferenceAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, referencedLanguage, hideAdvancedMembers); // If the source and referenced languages are different, then they cannot be in the same project if (sourceLanguage == referencedLanguage) { await VerifyItemInSameProjectAsync(markup, referencedCode, item, expectedSymbolsSameSolution, sourceLanguage, hideAdvancedMembers); } } private Task VerifyItemWithMetadataReferenceAsync(string markup, string metadataReferenceCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataReferenceCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected Task VerifyItemWithAliasedMetadataReferencesAsync(string markup, string metadataAlias, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" Aliases=""{3}, global"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> </Document> </MetadataReferenceFromSource> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(metadataAlias)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } protected Task VerifyItemWithProjectReferenceAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, string referencedLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <ProjectReference>ReferencedProject</ProjectReference> <Document FilePath=""SourceDocument""> {1} </Document> </Project> <Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"" IncludeXmlDocComments=""true"" DocumentationMode=""Diagnose""> <Document FilePath=""ReferencedDocument""> {3} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), referencedLanguage, SecurityElement.Escape(referencedCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private Task VerifyItemInSameProjectAsync(string markup, string referencedCode, string expectedItem, int expectedSymbols, string sourceLanguage, bool hideAdvancedMembers) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferences=""true""> <Document FilePath=""SourceDocument""> {1} </Document> <Document FilePath=""ReferencedDocument""> {2} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup), SecurityElement.Escape(referencedCode)); return VerifyItemWithReferenceWorkerAsync(xmlString, expectedItem, expectedSymbols, hideAdvancedMembers); } private async Task VerifyItemWithReferenceWorkerAsync( string xmlString, string expectedItem, int expectedSymbols, bool hideAdvancedMembers) { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); testWorkspace.Options = testWorkspace.Options.WithChangedOption(CompletionOptions.HideAdvancedMembers, document.Project.Language, hideAdvancedMembers); var triggerInfo = CompletionTrigger.Default; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); if (expectedSymbols >= 1) { AssertEx.Any(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); var item = completionList.Items.First(c => CompareItems(c.DisplayText, expectedItem)); var description = await completionService.GetDescriptionAsync(document, item); if (expectedSymbols == 1) { Assert.DoesNotContain("+", description.Text, StringComparison.Ordinal); } else { Assert.Contains(GetExpectedOverloadSubstring(expectedSymbols), description.Text, StringComparison.Ordinal); } } else { if (completionList != null) { AssertEx.None(completionList.Items, c => CompareItems(c.DisplayText, expectedItem)); } } } } protected Task VerifyItemWithMscorlib45Async(string markup, string expectedItem, string expectedDescription, string sourceLanguage) { var xmlString = string.Format(@" <Workspace> <Project Language=""{0}"" CommonReferencesNet45=""true""> <Document FilePath=""SourceDocument""> {1} </Document> </Project> </Workspace>", sourceLanguage, SecurityElement.Escape(markup)); return VerifyItemWithMscorlib45WorkerAsync(xmlString, expectedItem, expectedDescription); } private async Task VerifyItemWithMscorlib45WorkerAsync( string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { var position = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var documentId = testWorkspace.Documents.Single(d => d.Name == "SourceDocument").Id; var document = solution.GetDocument(documentId); var triggerInfo = CompletionTrigger.Default; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.FirstOrDefault(i => i.DisplayText == expectedItem); Assert.Equal(expectedDescription, (await completionService.GetDescriptionAsync(document, item)).Text); } } private const char NonBreakingSpace = (char)0x00A0; private string GetExpectedOverloadSubstring(int expectedSymbols) { if (expectedSymbols <= 1) { throw new ArgumentOutOfRangeException(nameof(expectedSymbols)); } return "+" + NonBreakingSpace + (expectedSymbols - 1) + NonBreakingSpace + FeaturesResources.overload; } protected async Task VerifyItemInLinkedFilesAsync(string xmlString, string expectedItem, string expectedDescription) { using (var testWorkspace = await TestWorkspace.CreateAsync(xmlString)) { var position = testWorkspace.Documents.First().CursorPosition.Value; var solution = testWorkspace.CurrentSolution; var textContainer = testWorkspace.Documents.First().TextBuffer.AsTextContainer(); var currentContextDocumentId = testWorkspace.GetDocumentIdInCurrentContext(textContainer); var document = solution.GetDocument(currentContextDocumentId); var triggerInfo = CompletionTrigger.Default; var completionService = GetCompletionService(testWorkspace); var completionList = await GetCompletionListAsync(completionService, document, position, triggerInfo); var item = completionList.Items.Single(c => c.DisplayText == expectedItem); Assert.NotNull(item); if (expectedDescription != null) { var actualDescription = (await completionService.GetDescriptionAsync(document, item)).Text; Assert.Equal(expectedDescription, actualDescription); } } } protected Task VerifyAtPositionAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { code = code.Substring(0, position) + insertText + code.Substring(position); position += insertText.Length; return BaseVerifyWorkerAsync(code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtPositionAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtPositionAsync( code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected async Task VerifyAtEndOfFileAsync( string code, int position, string insertText, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { // only do this if the placeholder was at the end of the text. if (code.Length != position) { return; } code = code.Substring(startIndex: 0, length: position) + insertText; position += insertText.Length; await BaseVerifyWorkerAsync( code, position, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, usePreviousCharAsTrigger, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtPosition_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtPositionAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtEndOfFileAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtEndOfFileAsync(code, position, string.Empty, usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected Task VerifyAtEndOfFile_ItemPartiallyWrittenAsync( string code, int position, bool usePreviousCharAsTrigger, string expectedItemOrNull, string expectedDescriptionOrNull, SourceCodeKind sourceCodeKind, bool checkForAbsence, int? glyph, int? matchPriority) { return VerifyAtEndOfFileAsync( code, position, ItemPartiallyWritten(expectedItemOrNull), usePreviousCharAsTrigger, expectedItemOrNull, expectedDescriptionOrNull, sourceCodeKind, checkForAbsence, glyph, matchPriority); } protected async Task VerifyTextualTriggerCharacterAsync( string markup, bool shouldTriggerWithTriggerOnLettersEnabled, bool shouldTriggerWithTriggerOnLettersDisabled) { await VerifyTextualTriggerCharacterWorkerAsync(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersEnabled, triggerOnLetter: true); await VerifyTextualTriggerCharacterWorkerAsync(markup, expectedTriggerCharacter: shouldTriggerWithTriggerOnLettersDisabled, triggerOnLetter: false); } private async Task VerifyTextualTriggerCharacterWorkerAsync( string markup, bool expectedTriggerCharacter, bool triggerOnLetter) { using (var workspace = await CreateWorkspaceAsync(markup)) { var document = workspace.Documents.Single(); var position = document.CursorPosition.Value; var text = document.TextBuffer.CurrentSnapshot.AsText(); var options = workspace.Options.WithChangedOption( CompletionOptions.TriggerOnTypingLetters, document.Project.Language, triggerOnLetter); var trigger = CompletionTrigger.CreateInsertionTrigger(text[position]); var service = GetCompletionService(workspace); var isTextualTriggerCharacterResult = service.ShouldTriggerCompletion(text, position + 1, trigger, options: options); if (expectedTriggerCharacter) { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to be textual trigger character"; Assert.True(isTextualTriggerCharacterResult, assertText); } else { var assertText = "'" + text.ToString(new TextSpan(position, 1)) + "' expected to NOT be textual trigger character"; Assert.False(isTextualTriggerCharacterResult, assertText); } } } protected async Task VerifyCommonCommitCharactersAsync(string initialMarkup, string textTypedSoFar) { var commitCharacters = new[] { ' ', '{', '}', '[', ']', '(', ')', '.', ',', ':', ';', '+', '-', '*', '/', '%', '&', '|', '^', '!', '~', '=', '<', '>', '?', '@', '#', '\'', '\"', '\\' }; await VerifyCommitCharactersAsync(initialMarkup, textTypedSoFar, commitCharacters); } protected async Task VerifyCommitCharactersAsync(string initialMarkup, string textTypedSoFar, char[] validChars, char[] invalidChars = null) { Assert.NotNull(validChars); invalidChars = invalidChars ?? new[] { 'x' }; using (var workspace = await CreateWorkspaceAsync(initialMarkup)) { var hostDocument = workspace.DocumentWithCursor; var documentId = workspace.GetDocumentId(hostDocument); var document = workspace.CurrentSolution.GetDocument(documentId); var position = hostDocument.CursorPosition.Value; var service = GetCompletionService(workspace); var completionList = await GetCompletionListAsync(service, document, position, CompletionTrigger.Default); var item = completionList.Items.First(i => i.DisplayText.StartsWith(textTypedSoFar)); foreach (var ch in validChars) { Assert.True(Controller.IsCommitCharacter( service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' to be a commit character"); } foreach (var ch in invalidChars) { Assert.False(Controller.IsCommitCharacter( service.GetRules(), item, ch, textTypedSoFar + ch), $"Expected '{ch}' NOT to be a commit character"); } } } } }
//------------------------------------------------------------------------------ // <copyright file="SoapReflector.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Protocols { using System; using System.Reflection; using System.Xml.Serialization; using System.Collections; using System.Web.Services.Configuration; using System.Web.Services.Description; using System.Globalization; using System.Xml; using System.Threading; internal class SoapReflectedHeader { internal Type headerType; internal MemberInfo memberInfo; internal SoapHeaderDirection direction; internal bool repeats; internal bool custom; } internal class SoapReflectedExtension : IComparable { Type type; SoapExtensionAttribute attribute; int priority; internal SoapReflectedExtension(Type type, SoapExtensionAttribute attribute) : this(type, attribute, attribute.Priority) { } internal SoapReflectedExtension(Type type, SoapExtensionAttribute attribute, int priority) { if (priority < 0) throw new ArgumentException(Res.GetString(Res.WebConfigInvalidExtensionPriority, priority), "priority"); this.type = type; this.attribute = attribute; this.priority = priority; } internal SoapExtension CreateInstance(object initializer) { SoapExtension extension = (SoapExtension)Activator.CreateInstance(type); extension.Initialize(initializer); return extension; } internal object GetInitializer(LogicalMethodInfo methodInfo) { SoapExtension extension = (SoapExtension)Activator.CreateInstance(type); return extension.GetInitializer(methodInfo, attribute); } internal object GetInitializer(Type serviceType) { SoapExtension extension = (SoapExtension) Activator.CreateInstance(type); return extension.GetInitializer(serviceType); } internal static object[] GetInitializers(LogicalMethodInfo methodInfo, SoapReflectedExtension[] extensions) { object[] initializers = new object[extensions.Length]; for (int i = 0; i < initializers.Length; i++) initializers[i] = extensions[i].GetInitializer(methodInfo); return initializers; } internal static object[] GetInitializers(Type serviceType, SoapReflectedExtension[] extensions) { object[] initializers = new object[extensions.Length]; for (int i = 0; i < initializers.Length; i++) initializers[i] = extensions[i].GetInitializer(serviceType); return initializers; } public int CompareTo(object o) { // higher priorities (lower numbers) go at the front of the list return priority - ((SoapReflectedExtension)o).priority; } } internal class SoapReflectedMethod { internal LogicalMethodInfo methodInfo; internal string action; internal string name; internal XmlMembersMapping requestMappings; internal XmlMembersMapping responseMappings; internal XmlMembersMapping inHeaderMappings; internal XmlMembersMapping outHeaderMappings; internal SoapReflectedHeader[] headers; internal SoapReflectedExtension[] extensions; internal bool oneWay; internal bool rpc; internal SoapBindingUse use; internal SoapParameterStyle paramStyle; internal WebServiceBindingAttribute binding; internal XmlQualifiedName requestElementName; internal XmlQualifiedName portType; internal bool IsClaimsConformance { get { return binding != null && binding.ConformsTo == WsiProfiles.BasicProfile1_1; } } } // custom attributes are not returned in a "stable" order, so we sort them by name internal class SoapHeaderAttributeComparer : IComparer { public int Compare(object x, object y) { return string.Compare(((SoapHeaderAttribute)x).MemberName, ((SoapHeaderAttribute)y).MemberName, StringComparison.Ordinal); } } internal static class SoapReflector { class SoapParameterInfo { internal ParameterInfo parameterInfo; internal XmlAttributes xmlAttributes; internal SoapAttributes soapAttributes; } class MethodAttribute { internal string action; internal string binding; internal string requestName; internal string requestNs; internal string responseName; internal string responseNs; } internal static bool ServiceDefaultIsEncoded(Type type) { return ServiceDefaultIsEncoded(GetSoapServiceAttribute(type)); } internal static bool ServiceDefaultIsEncoded(object soapServiceAttribute) { if (soapServiceAttribute == null) return false; if (soapServiceAttribute is SoapDocumentServiceAttribute) { return ((SoapDocumentServiceAttribute)soapServiceAttribute).Use == SoapBindingUse.Encoded; } if (soapServiceAttribute is SoapRpcServiceAttribute) { return ((SoapRpcServiceAttribute)soapServiceAttribute).Use == SoapBindingUse.Encoded; } return false; } internal static string GetEncodedNamespace(string ns, bool serviceDefaultIsEncoded) { if (serviceDefaultIsEncoded) return ns; if (ns.EndsWith("/", StringComparison.Ordinal)) return ns + "encodedTypes"; return ns + "/encodedTypes"; } internal static string GetLiteralNamespace(string ns, bool serviceDefaultIsEncoded) { if (!serviceDefaultIsEncoded) return ns; if (ns.EndsWith("/", StringComparison.Ordinal)) return ns + "literalTypes"; return ns + "/literalTypes"; } internal static SoapReflectionImporter CreateSoapImporter(string defaultNs, bool serviceDefaultIsEncoded) { return new SoapReflectionImporter(GetEncodedNamespace(defaultNs, serviceDefaultIsEncoded)); } internal static XmlReflectionImporter CreateXmlImporter(string defaultNs, bool serviceDefaultIsEncoded) { return new XmlReflectionImporter(GetLiteralNamespace(defaultNs, serviceDefaultIsEncoded)); } internal static void IncludeTypes(LogicalMethodInfo[] methods, SoapReflectionImporter importer) { for (int i = 0; i < methods.Length; i++) { LogicalMethodInfo method = methods[i]; IncludeTypes(method, importer); } } internal static void IncludeTypes(LogicalMethodInfo method, SoapReflectionImporter importer) { if (method.Declaration != null) { importer.IncludeTypes(method.Declaration.DeclaringType); importer.IncludeTypes(method.Declaration); } importer.IncludeTypes(method.DeclaringType); importer.IncludeTypes(method.CustomAttributeProvider); } internal static object GetSoapMethodAttribute(LogicalMethodInfo methodInfo) { object[] rpcMethodAttributes = methodInfo.GetCustomAttributes(typeof(SoapRpcMethodAttribute)); object[] docMethodAttributes = methodInfo.GetCustomAttributes(typeof(SoapDocumentMethodAttribute)); if (rpcMethodAttributes.Length > 0) { if (docMethodAttributes.Length > 0) throw new ArgumentException(Res.GetString(Res.WebBothMethodAttrs), "methodInfo"); return rpcMethodAttributes[0]; } else if (docMethodAttributes.Length > 0) return docMethodAttributes[0]; else return null; } internal static object GetSoapServiceAttribute(Type type) { object[] rpcServiceAttributes = type.GetCustomAttributes(typeof(SoapRpcServiceAttribute), false); object[] docServiceAttributes = type.GetCustomAttributes(typeof(SoapDocumentServiceAttribute), false); if (rpcServiceAttributes.Length > 0) { if (docServiceAttributes.Length > 0) throw new ArgumentException(Res.GetString(Res.WebBothServiceAttrs), "methodInfo"); return rpcServiceAttributes[0]; } else if (docServiceAttributes.Length > 0) return docServiceAttributes[0]; else return null; } internal static SoapServiceRoutingStyle GetSoapServiceRoutingStyle(object soapServiceAttribute) { if (soapServiceAttribute is SoapRpcServiceAttribute) return ((SoapRpcServiceAttribute)soapServiceAttribute).RoutingStyle; else if (soapServiceAttribute is SoapDocumentServiceAttribute) return ((SoapDocumentServiceAttribute)soapServiceAttribute).RoutingStyle; else return SoapServiceRoutingStyle.SoapAction; } internal static string GetSoapMethodBinding(LogicalMethodInfo method) { string binding; object[] attrs = method.GetCustomAttributes(typeof(SoapDocumentMethodAttribute)); if (attrs.Length == 0) { attrs = method.GetCustomAttributes(typeof(SoapRpcMethodAttribute)); if (attrs.Length == 0) binding = string.Empty; else binding = ((SoapRpcMethodAttribute)attrs[0]).Binding; } else binding = ((SoapDocumentMethodAttribute)attrs[0]).Binding; if (method.Binding != null) { if (binding.Length > 0 && binding != method.Binding.Name) { throw new InvalidOperationException(Res.GetString(Res.WebInvalidBindingName, binding, method.Binding.Name)); } return method.Binding.Name; } return binding; } internal static SoapReflectedMethod ReflectMethod(LogicalMethodInfo methodInfo, bool client, XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, string defaultNs) { try { string methodId = methodInfo.GetKey(); SoapReflectedMethod soapMethod = new SoapReflectedMethod(); MethodAttribute methodAttribute = new MethodAttribute(); object serviceAttr = GetSoapServiceAttribute(methodInfo.DeclaringType); bool serviceDefaultIsEncoded = ServiceDefaultIsEncoded(serviceAttr); object methodAttr = GetSoapMethodAttribute(methodInfo); if (methodAttr == null) { if (client) return null; // method attribute required on the client if (serviceAttr is SoapRpcServiceAttribute) { SoapRpcMethodAttribute method = new SoapRpcMethodAttribute(); method.Use = ((SoapRpcServiceAttribute)serviceAttr).Use; methodAttr = method; } else if (serviceAttr is SoapDocumentServiceAttribute) { SoapDocumentMethodAttribute method = new SoapDocumentMethodAttribute(); method.Use = ((SoapDocumentServiceAttribute)serviceAttr).Use; methodAttr = method; } else { methodAttr = new SoapDocumentMethodAttribute(); } } if (methodAttr is SoapRpcMethodAttribute) { SoapRpcMethodAttribute attr = (SoapRpcMethodAttribute)methodAttr; soapMethod.rpc = true; soapMethod.use = attr.Use; soapMethod.oneWay = attr.OneWay; methodAttribute.action = attr.Action; methodAttribute.binding = attr.Binding; methodAttribute.requestName = attr.RequestElementName; methodAttribute.requestNs = attr.RequestNamespace; methodAttribute.responseName = attr.ResponseElementName; methodAttribute.responseNs = attr.ResponseNamespace; } else { SoapDocumentMethodAttribute attr = (SoapDocumentMethodAttribute)methodAttr; soapMethod.rpc = false; soapMethod.use = attr.Use; soapMethod.paramStyle = attr.ParameterStyle; soapMethod.oneWay = attr.OneWay; methodAttribute.action = attr.Action; methodAttribute.binding = attr.Binding; methodAttribute.requestName = attr.RequestElementName; methodAttribute.requestNs = attr.RequestNamespace; methodAttribute.responseName = attr.ResponseElementName; methodAttribute.responseNs = attr.ResponseNamespace; if (soapMethod.use == SoapBindingUse.Default) { if (serviceAttr is SoapDocumentServiceAttribute) soapMethod.use = ((SoapDocumentServiceAttribute)serviceAttr).Use; if (soapMethod.use == SoapBindingUse.Default) soapMethod.use = SoapBindingUse.Literal; } if (soapMethod.paramStyle == SoapParameterStyle.Default) { if (serviceAttr is SoapDocumentServiceAttribute) soapMethod.paramStyle = ((SoapDocumentServiceAttribute)serviceAttr).ParameterStyle; if (soapMethod.paramStyle == SoapParameterStyle.Default) soapMethod.paramStyle = SoapParameterStyle.Wrapped; } } if (methodAttribute.binding.Length > 0) { if (client) throw new InvalidOperationException(Res.GetString(Res.WebInvalidBindingPlacement, methodAttr.GetType().Name)); soapMethod.binding = WebServiceBindingReflector.GetAttribute(methodInfo, methodAttribute.binding); } WebMethodAttribute webMethodAttribute = methodInfo.MethodAttribute; // soapMethod.name = webMethodAttribute.MessageName; if (soapMethod.name.Length == 0) soapMethod.name = methodInfo.Name; string requestElementName; if (soapMethod.rpc) { // in the case when we interop with non .net we might need to chnage the method name. requestElementName = methodAttribute.requestName.Length == 0 || !client ? methodInfo.Name : methodAttribute.requestName; } else { requestElementName = methodAttribute.requestName.Length == 0 ? soapMethod.name : methodAttribute.requestName; } string requestNamespace = methodAttribute.requestNs; if (requestNamespace == null) { if (soapMethod.binding != null && soapMethod.binding.Namespace != null && soapMethod.binding.Namespace.Length != 0) requestNamespace = soapMethod.binding.Namespace; else requestNamespace = defaultNs; } string responseElementName; if (soapMethod.rpc && soapMethod.use != SoapBindingUse.Encoded) { // NOTE: this rule should apply equally to rpc/lit and rpc/enc, but to reduce risk, i'm only applying it to rpc/lit responseElementName = methodInfo.Name + "Response"; } else { responseElementName = methodAttribute.responseName.Length == 0 ? soapMethod.name + "Response" : methodAttribute.responseName; } string responseNamespace = methodAttribute.responseNs; if (responseNamespace == null) { if (soapMethod.binding != null && soapMethod.binding.Namespace != null && soapMethod.binding.Namespace.Length != 0) responseNamespace = soapMethod.binding.Namespace; else responseNamespace = defaultNs; } SoapParameterInfo[] inParameters = ReflectParameters(methodInfo.InParameters, requestNamespace); SoapParameterInfo[] outParameters = ReflectParameters(methodInfo.OutParameters, responseNamespace); soapMethod.action = methodAttribute.action; if (soapMethod.action == null) soapMethod.action = GetDefaultAction(defaultNs, methodInfo); soapMethod.methodInfo = methodInfo; if (soapMethod.oneWay) { if (outParameters.Length > 0) throw new ArgumentException(Res.GetString(Res.WebOneWayOutParameters), "methodInfo"); if (methodInfo.ReturnType != typeof(void)) throw new ArgumentException(Res.GetString(Res.WebOneWayReturnValue), "methodInfo"); } XmlReflectionMember[] members = new XmlReflectionMember[inParameters.Length]; for (int i = 0; i < members.Length; i++) { SoapParameterInfo soapParamInfo = inParameters[i]; XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapParamInfo.parameterInfo.Name; member.MemberType = soapParamInfo.parameterInfo.ParameterType; if (member.MemberType.IsByRef) member.MemberType = member.MemberType.GetElementType(); member.XmlAttributes = soapParamInfo.xmlAttributes; member.SoapAttributes = soapParamInfo.soapAttributes; members[i] = member; } soapMethod.requestMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, requestElementName, requestNamespace, methodAttribute.requestNs == null, members, true, false, methodId, client); if (GetSoapServiceRoutingStyle(serviceAttr) == SoapServiceRoutingStyle.RequestElement && soapMethod.paramStyle == SoapParameterStyle.Bare && soapMethod.requestMappings.Count != 1) throw new ArgumentException(Res.GetString(Res.WhenUsingAMessageStyleOfParametersAsDocument0), "methodInfo"); string elementName = ""; string elementNamespace = ""; if (soapMethod.paramStyle == SoapParameterStyle.Bare) { if (soapMethod.requestMappings.Count == 1) { elementName = soapMethod.requestMappings[0].XsdElementName; elementNamespace = soapMethod.requestMappings[0].Namespace; } // else: can't route on request element -- we match on an empty qname, // normal rules apply for duplicates } else { elementName = soapMethod.requestMappings.XsdElementName; elementNamespace = soapMethod.requestMappings.Namespace; } soapMethod.requestElementName = new XmlQualifiedName(elementName, elementNamespace); if (!soapMethod.oneWay) { int numOutParams = outParameters.Length; int count = 0; CodeIdentifiers identifiers = null; if (methodInfo.ReturnType != typeof(void)) { numOutParams++; count = 1; identifiers = new CodeIdentifiers(); } members = new XmlReflectionMember[numOutParams]; for (int i = 0; i < outParameters.Length; i++) { SoapParameterInfo soapParamInfo = outParameters[i]; XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapParamInfo.parameterInfo.Name; member.MemberType = soapParamInfo.parameterInfo.ParameterType; if (member.MemberType.IsByRef) member.MemberType = member.MemberType.GetElementType(); member.XmlAttributes = soapParamInfo.xmlAttributes; member.SoapAttributes = soapParamInfo.soapAttributes; members[count++] = member; if (identifiers != null) identifiers.Add(member.MemberName, null); } if (methodInfo.ReturnType != typeof(void)) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = identifiers.MakeUnique(soapMethod.name + "Result"); member.MemberType = methodInfo.ReturnType; member.IsReturnValue = true; member.XmlAttributes = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider); member.XmlAttributes.XmlRoot = null; // Ignore XmlRoot attribute used by get/post member.SoapAttributes = new SoapAttributes(methodInfo.ReturnTypeCustomAttributeProvider); members[0] = member; } soapMethod.responseMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, soapMethod.rpc, soapMethod.use, soapMethod.paramStyle, responseElementName, responseNamespace, methodAttribute.responseNs == null, members, false, false, methodId + ":Response", !client); } SoapExtensionAttribute[] extensionAttributes = (SoapExtensionAttribute[])methodInfo.GetCustomAttributes(typeof(SoapExtensionAttribute)); soapMethod.extensions = new SoapReflectedExtension[extensionAttributes.Length]; for (int i = 0; i < extensionAttributes.Length; i++) soapMethod.extensions[i] = new SoapReflectedExtension(extensionAttributes[i].ExtensionType, extensionAttributes[i]); Array.Sort(soapMethod.extensions); SoapHeaderAttribute[] headerAttributes = (SoapHeaderAttribute[])methodInfo.GetCustomAttributes(typeof(SoapHeaderAttribute)); Array.Sort(headerAttributes, new SoapHeaderAttributeComparer()); Hashtable headerTypes = new Hashtable(); soapMethod.headers = new SoapReflectedHeader[headerAttributes.Length]; int front = 0; int back = soapMethod.headers.Length; ArrayList inHeaders = new ArrayList(); ArrayList outHeaders = new ArrayList(); for (int i = 0; i < soapMethod.headers.Length; i++) { SoapHeaderAttribute headerAttribute = headerAttributes[i]; SoapReflectedHeader soapHeader = new SoapReflectedHeader(); Type declaringType = methodInfo.DeclaringType; if ((soapHeader.memberInfo = declaringType.GetField(headerAttribute.MemberName)) != null) { soapHeader.headerType = ((FieldInfo)soapHeader.memberInfo).FieldType; } else if ((soapHeader.memberInfo = declaringType.GetProperty(headerAttribute.MemberName)) != null) { soapHeader.headerType = ((PropertyInfo)soapHeader.memberInfo).PropertyType; } else { throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderMissing); } if (soapHeader.headerType.IsArray) { soapHeader.headerType = soapHeader.headerType.GetElementType(); soapHeader.repeats = true; if (soapHeader.headerType != typeof(SoapUnknownHeader) && soapHeader.headerType != typeof(SoapHeader)) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderType); } if (MemberHelper.IsStatic(soapHeader.memberInfo)) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderStatic); if (!MemberHelper.CanRead(soapHeader.memberInfo)) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderRead); if (!MemberHelper.CanWrite(soapHeader.memberInfo)) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderWrite); if (!typeof(SoapHeader).IsAssignableFrom(soapHeader.headerType)) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderType); SoapHeaderDirection direction = headerAttribute.Direction; if (soapMethod.oneWay && (direction & (SoapHeaderDirection.Out | SoapHeaderDirection.Fault)) != 0) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebHeaderOneWayOut); if (headerTypes.Contains(soapHeader.headerType)) { SoapHeaderDirection prevDirection = (SoapHeaderDirection) headerTypes[soapHeader.headerType]; if ((prevDirection & direction) != 0) throw HeaderException(headerAttribute.MemberName, methodInfo.DeclaringType, Res.WebMultiplyDeclaredHeaderTypes); headerTypes[soapHeader.headerType] = direction | prevDirection; } else headerTypes[soapHeader.headerType] = direction; if (soapHeader.headerType != typeof(SoapHeader) && soapHeader.headerType != typeof(SoapUnknownHeader)) { XmlReflectionMember member = new XmlReflectionMember(); member.MemberName = soapHeader.headerType.Name; member.MemberType = soapHeader.headerType; XmlAttributes a = new XmlAttributes(soapHeader.headerType); if (a.XmlRoot != null) { member.XmlAttributes = new XmlAttributes(); XmlElementAttribute attr = new XmlElementAttribute(); attr.ElementName = a.XmlRoot.ElementName; attr.Namespace = a.XmlRoot.Namespace; member.XmlAttributes.XmlElements.Add(attr); } member.OverrideIsNullable = true; if ((direction & SoapHeaderDirection.In) != 0) inHeaders.Add(member); if ((direction & (SoapHeaderDirection.Out | SoapHeaderDirection.Fault)) != 0) outHeaders.Add(member); soapHeader.custom = true; } soapHeader.direction = direction; // Put generic header mappings at the end of the list so they are found last during header processing if (!soapHeader.custom) { soapMethod.headers[--back] = soapHeader; } else { soapMethod.headers[front++] = soapHeader; } } soapMethod.inHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, soapMethod.use, SoapParameterStyle.Bare, requestElementName + "InHeaders", defaultNs, true, (XmlReflectionMember[]) inHeaders.ToArray(typeof(XmlReflectionMember)), false, true, methodId + ":InHeaders", client); if (!soapMethod.oneWay) soapMethod.outHeaderMappings = ImportMembersMapping(xmlImporter, soapImporter, serviceDefaultIsEncoded, false, soapMethod.use, SoapParameterStyle.Bare, responseElementName + "OutHeaders", defaultNs, true, (XmlReflectionMember[]) outHeaders.ToArray(typeof(XmlReflectionMember)), false, true, methodId + ":OutHeaders", !client); return soapMethod; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } throw new InvalidOperationException(Res.GetString(Res.WebReflectionErrorMethod, methodInfo.DeclaringType.Name, methodInfo.Name), e); } } static XmlMembersMapping ImportMembersMapping(XmlReflectionImporter xmlImporter, SoapReflectionImporter soapImporter, bool serviceDefaultIsEncoded, bool rpc, SoapBindingUse use, SoapParameterStyle paramStyle, string elementName, string elementNamespace, bool nsIsDefault, XmlReflectionMember[] members, bool validate, bool openModel, string key, bool writeAccess) { XmlMembersMapping mapping = null; if (use == SoapBindingUse.Encoded) { string ns = (!rpc && paramStyle != SoapParameterStyle.Bare && nsIsDefault) ? GetEncodedNamespace(elementNamespace, serviceDefaultIsEncoded) : elementNamespace; mapping = soapImporter.ImportMembersMapping(elementName, ns, members, rpc || paramStyle != SoapParameterStyle.Bare, rpc, validate, writeAccess ? XmlMappingAccess.Write : XmlMappingAccess.Read); } else { string ns = nsIsDefault ? GetLiteralNamespace(elementNamespace, serviceDefaultIsEncoded) : elementNamespace; mapping = xmlImporter.ImportMembersMapping(elementName, ns, members, paramStyle != SoapParameterStyle.Bare, rpc, openModel, writeAccess ? XmlMappingAccess.Write : XmlMappingAccess.Read); } if (mapping != null) { mapping.SetKey(key); } return mapping; } static Exception HeaderException(string memberName, Type declaringType, string description) { return new Exception(Res.GetString(description, declaringType.Name, memberName)); } static SoapParameterInfo[] ReflectParameters(ParameterInfo[] paramInfos, string ns) { SoapParameterInfo[] soapParamInfos = new SoapParameterInfo[paramInfos.Length]; for (int i = 0; i < paramInfos.Length; i++) { SoapParameterInfo soapParamInfo = new SoapParameterInfo(); ParameterInfo paramInfo = paramInfos[i]; if (paramInfo.ParameterType.IsArray && paramInfo.ParameterType.GetArrayRank() > 1) throw new InvalidOperationException(Res.GetString(Res.WebMultiDimArray)); soapParamInfo.xmlAttributes = new XmlAttributes(paramInfo); soapParamInfo.soapAttributes = new SoapAttributes(paramInfo); soapParamInfo.parameterInfo = paramInfo; soapParamInfos[i] = soapParamInfo; } return soapParamInfos; } static string GetDefaultAction(string defaultNs, LogicalMethodInfo methodInfo) { WebMethodAttribute methodAttribute = methodInfo.MethodAttribute; string messageName = methodAttribute.MessageName; if (messageName.Length == 0) messageName = methodInfo.Name; if (defaultNs.EndsWith("/", StringComparison.Ordinal)) return defaultNs + messageName; return defaultNs + "/" + messageName; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; public sealed class CustomAttributeRepresentation { public static readonly CustomAttributeRepresentation[] SharedEmptyArray = new CustomAttributeRepresentation[0]; // // State // private MethodRepresentation m_constructor; private object[] m_fixedArgsValues; private string[] m_namedArgs; private object[] m_namedArgsValues; // // Constructor Methods // public CustomAttributeRepresentation( MethodRepresentation constructor , object[] fixedArgsValues , string[] namedArgs , object[] namedArgsValues ) { CHECKS.ASSERT( constructor != null, "Cannot create CustomAttributeRepresentation without supporting metadata" ); m_constructor = constructor; m_fixedArgsValues = fixedArgsValues; m_namedArgs = namedArgs; m_namedArgsValues = namedArgsValues; } // // MetaDataEquality Methods // public override bool Equals( object obj ) { if(obj is CustomAttributeRepresentation) { CustomAttributeRepresentation other = (CustomAttributeRepresentation)obj; if(m_constructor == other.m_constructor) { if(ArrayUtility.ArrayEquals( m_fixedArgsValues, other.m_fixedArgsValues ) && ArrayUtility.ArrayEquals( m_namedArgs , other.m_namedArgs ) && ArrayUtility.ArrayEquals( m_namedArgsValues, other.m_namedArgsValues ) ) { return true; } } } return false; } public override int GetHashCode() { return m_constructor.GetHashCode(); } //--// // // Helper Methods // public void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_constructor ); context.Transform( ref m_fixedArgsValues ); context.Transform( ref m_namedArgs ); context.Transform( ref m_namedArgsValues ); context.Pop(); } //--// public bool HasNamedArg( string name ) { return GetNamedArgIndex( name ) >= 0; } public object GetNamedArg( string name ) { int i = GetNamedArgIndex( name ); if(i >= 0) { return m_namedArgsValues[i]; } return null; } public bool TryToGetNamedArg< T >( string name , out T val ) { return TryToGetNamedArg( name, out val, default(T) ); } public bool TryToGetNamedArg< T >( string name , out T val , T defaultVal ) { int i = GetNamedArgIndex( name ); if(i >= 0) { val = (T)m_namedArgsValues[i]; return true; } else { val = defaultVal; return false; } } public T GetNamedArg< T >( string name ) { object val = GetNamedArg( name ); if(val != null) { return (T)val; } else { return default(T); } } public T GetNamedArg< T >( string name , T defaultVal ) { object val = GetNamedArg( name ); if(val != null) { return (T)val; } else { return defaultVal; } } private int GetNamedArgIndex( string name ) { for(int i = 0; i < m_namedArgs.Length; i++) { if(m_namedArgs[i] == name) { return i; } } return -1; } //--// // // Access Methods // public MethodRepresentation Constructor { get { return m_constructor; } } public object[] FixedArgsValues { get { return m_fixedArgsValues; } } public string[] NamedArgs { get { return m_namedArgs; } } public object[] NamedArgsValues { get { return m_namedArgsValues; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Linq; using Xunit; namespace System.Text.Tests { public partial class EncodingTest : IClassFixture<CultureSetup> { public EncodingTest(CultureSetup setup) { // Setting up the culture happens externally, and only once, which is what we want. // xUnit will keep track of it, do nothing. } public static IEnumerable<object[]> CodePageInfo() { // The layout is code page, IANA(web) name, and query string. // Query strings may be undocumented, and IANA names will be returned from Encoding objects. // Entries are sorted by code page. yield return new object[] { 37, "ibm037", "ibm037" }; yield return new object[] { 37, "ibm037", "cp037" }; yield return new object[] { 37, "ibm037", "csibm037" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-ca" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-nl" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-us" }; yield return new object[] { 37, "ibm037", "ebcdic-cp-wt" }; yield return new object[] { 437, "ibm437", "ibm437" }; yield return new object[] { 437, "ibm437", "437" }; yield return new object[] { 437, "ibm437", "cp437" }; yield return new object[] { 437, "ibm437", "cspc8codepage437" }; yield return new object[] { 500, "ibm500", "ibm500" }; yield return new object[] { 500, "ibm500", "cp500" }; yield return new object[] { 500, "ibm500", "csibm500" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-be" }; yield return new object[] { 500, "ibm500", "ebcdic-cp-ch" }; yield return new object[] { 708, "asmo-708", "asmo-708" }; yield return new object[] { 720, "dos-720", "dos-720" }; yield return new object[] { 737, "ibm737", "ibm737" }; yield return new object[] { 775, "ibm775", "ibm775" }; yield return new object[] { 850, "ibm850", "ibm850" }; yield return new object[] { 850, "ibm850", "cp850" }; yield return new object[] { 852, "ibm852", "ibm852" }; yield return new object[] { 852, "ibm852", "cp852" }; yield return new object[] { 855, "ibm855", "ibm855" }; yield return new object[] { 855, "ibm855", "cp855" }; yield return new object[] { 857, "ibm857", "ibm857" }; yield return new object[] { 857, "ibm857", "cp857" }; yield return new object[] { 858, "ibm00858", "ibm00858" }; yield return new object[] { 858, "ibm00858", "ccsid00858" }; yield return new object[] { 858, "ibm00858", "cp00858" }; yield return new object[] { 858, "ibm00858", "cp858" }; yield return new object[] { 858, "ibm00858", "pc-multilingual-850+euro" }; yield return new object[] { 860, "ibm860", "ibm860" }; yield return new object[] { 860, "ibm860", "cp860" }; yield return new object[] { 861, "ibm861", "ibm861" }; yield return new object[] { 861, "ibm861", "cp861" }; yield return new object[] { 862, "dos-862", "dos-862" }; yield return new object[] { 862, "dos-862", "cp862" }; yield return new object[] { 862, "dos-862", "ibm862" }; yield return new object[] { 863, "ibm863", "ibm863" }; yield return new object[] { 863, "ibm863", "cp863" }; yield return new object[] { 864, "ibm864", "ibm864" }; yield return new object[] { 864, "ibm864", "cp864" }; yield return new object[] { 865, "ibm865", "ibm865" }; yield return new object[] { 865, "ibm865", "cp865" }; yield return new object[] { 866, "cp866", "cp866" }; yield return new object[] { 866, "cp866", "ibm866" }; yield return new object[] { 869, "ibm869", "ibm869" }; yield return new object[] { 869, "ibm869", "cp869" }; yield return new object[] { 870, "ibm870", "ibm870" }; yield return new object[] { 870, "ibm870", "cp870" }; yield return new object[] { 870, "ibm870", "csibm870" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-roece" }; yield return new object[] { 870, "ibm870", "ebcdic-cp-yu" }; yield return new object[] { 874, "windows-874", "windows-874" }; yield return new object[] { 874, "windows-874", "dos-874" }; yield return new object[] { 874, "windows-874", "iso-8859-11" }; yield return new object[] { 874, "windows-874", "tis-620" }; yield return new object[] { 875, "cp875", "cp875" }; yield return new object[] { 932, "shift_jis", "shift_jis" }; yield return new object[] { 932, "shift_jis", "csshiftjis" }; yield return new object[] { 932, "shift_jis", "cswindows31j" }; yield return new object[] { 932, "shift_jis", "ms_kanji" }; yield return new object[] { 932, "shift_jis", "shift-jis" }; yield return new object[] { 932, "shift_jis", "sjis" }; yield return new object[] { 932, "shift_jis", "x-ms-cp932" }; yield return new object[] { 932, "shift_jis", "x-sjis" }; yield return new object[] { 936, "gb2312", "gb2312" }; yield return new object[] { 936, "gb2312", "chinese" }; yield return new object[] { 936, "gb2312", "cn-gb" }; yield return new object[] { 936, "gb2312", "csgb2312" }; yield return new object[] { 936, "gb2312", "csgb231280" }; yield return new object[] { 936, "gb2312", "csiso58gb231280" }; yield return new object[] { 936, "gb2312", "gb_2312-80" }; yield return new object[] { 936, "gb2312", "gb231280" }; yield return new object[] { 936, "gb2312", "gb2312-80" }; yield return new object[] { 936, "gb2312", "gbk" }; yield return new object[] { 936, "gb2312", "iso-ir-58" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1987" }; yield return new object[] { 949, "ks_c_5601-1987", "csksc56011987" }; yield return new object[] { 949, "ks_c_5601-1987", "iso-ir-149" }; yield return new object[] { 949, "ks_c_5601-1987", "korean" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601_1987" }; yield return new object[] { 949, "ks_c_5601-1987", "ks_c_5601-1989" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc_5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ksc5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c5601" }; yield return new object[] { 949, "ks_c_5601-1987", "ks-c-5601" }; yield return new object[] { 950, "big5", "big5" }; yield return new object[] { 950, "big5", "big5-hkscs" }; yield return new object[] { 950, "big5", "cn-big5" }; yield return new object[] { 950, "big5", "csbig5" }; yield return new object[] { 950, "big5", "x-x-big5" }; yield return new object[] { 1026, "ibm1026", "ibm1026" }; yield return new object[] { 1026, "ibm1026", "cp1026" }; yield return new object[] { 1026, "ibm1026", "csibm1026" }; yield return new object[] { 1047, "ibm01047", "ibm01047" }; yield return new object[] { 1140, "ibm01140", "ibm01140" }; yield return new object[] { 1140, "ibm01140", "ccsid01140" }; yield return new object[] { 1140, "ibm01140", "cp01140" }; yield return new object[] { 1140, "ibm01140", "ebcdic-us-37+euro" }; yield return new object[] { 1141, "ibm01141", "ibm01141" }; yield return new object[] { 1141, "ibm01141", "ccsid01141" }; yield return new object[] { 1141, "ibm01141", "cp01141" }; yield return new object[] { 1141, "ibm01141", "ebcdic-de-273+euro" }; yield return new object[] { 1142, "ibm01142", "ibm01142" }; yield return new object[] { 1142, "ibm01142", "ccsid01142" }; yield return new object[] { 1142, "ibm01142", "cp01142" }; yield return new object[] { 1142, "ibm01142", "ebcdic-dk-277+euro" }; yield return new object[] { 1142, "ibm01142", "ebcdic-no-277+euro" }; yield return new object[] { 1143, "ibm01143", "ibm01143" }; yield return new object[] { 1143, "ibm01143", "ccsid01143" }; yield return new object[] { 1143, "ibm01143", "cp01143" }; yield return new object[] { 1143, "ibm01143", "ebcdic-fi-278+euro" }; yield return new object[] { 1143, "ibm01143", "ebcdic-se-278+euro" }; yield return new object[] { 1144, "ibm01144", "ibm01144" }; yield return new object[] { 1144, "ibm01144", "ccsid01144" }; yield return new object[] { 1144, "ibm01144", "cp01144" }; yield return new object[] { 1144, "ibm01144", "ebcdic-it-280+euro" }; yield return new object[] { 1145, "ibm01145", "ibm01145" }; yield return new object[] { 1145, "ibm01145", "ccsid01145" }; yield return new object[] { 1145, "ibm01145", "cp01145" }; yield return new object[] { 1145, "ibm01145", "ebcdic-es-284+euro" }; yield return new object[] { 1146, "ibm01146", "ibm01146" }; yield return new object[] { 1146, "ibm01146", "ccsid01146" }; yield return new object[] { 1146, "ibm01146", "cp01146" }; yield return new object[] { 1146, "ibm01146", "ebcdic-gb-285+euro" }; yield return new object[] { 1147, "ibm01147", "ibm01147" }; yield return new object[] { 1147, "ibm01147", "ccsid01147" }; yield return new object[] { 1147, "ibm01147", "cp01147" }; yield return new object[] { 1147, "ibm01147", "ebcdic-fr-297+euro" }; yield return new object[] { 1148, "ibm01148", "ibm01148" }; yield return new object[] { 1148, "ibm01148", "ccsid01148" }; yield return new object[] { 1148, "ibm01148", "cp01148" }; yield return new object[] { 1148, "ibm01148", "ebcdic-international-500+euro" }; yield return new object[] { 1149, "ibm01149", "ibm01149" }; yield return new object[] { 1149, "ibm01149", "ccsid01149" }; yield return new object[] { 1149, "ibm01149", "cp01149" }; yield return new object[] { 1149, "ibm01149", "ebcdic-is-871+euro" }; yield return new object[] { 1250, "windows-1250", "windows-1250" }; yield return new object[] { 1250, "windows-1250", "x-cp1250" }; yield return new object[] { 1251, "windows-1251", "windows-1251" }; yield return new object[] { 1251, "windows-1251", "x-cp1251" }; yield return new object[] { 1252, "windows-1252", "windows-1252" }; yield return new object[] { 1252, "windows-1252", "x-ansi" }; yield return new object[] { 1253, "windows-1253", "windows-1253" }; yield return new object[] { 1254, "windows-1254", "windows-1254" }; yield return new object[] { 1255, "windows-1255", "windows-1255" }; yield return new object[] { 1256, "windows-1256", "windows-1256" }; yield return new object[] { 1256, "windows-1256", "cp1256" }; yield return new object[] { 1257, "windows-1257", "windows-1257" }; yield return new object[] { 1258, "windows-1258", "windows-1258" }; yield return new object[] { 1361, "johab", "johab" }; yield return new object[] { 10000, "macintosh", "macintosh" }; yield return new object[] { 10001, "x-mac-japanese", "x-mac-japanese" }; yield return new object[] { 10002, "x-mac-chinesetrad", "x-mac-chinesetrad" }; yield return new object[] { 10003, "x-mac-korean", "x-mac-korean" }; yield return new object[] { 10004, "x-mac-arabic", "x-mac-arabic" }; yield return new object[] { 10005, "x-mac-hebrew", "x-mac-hebrew" }; yield return new object[] { 10006, "x-mac-greek", "x-mac-greek" }; yield return new object[] { 10007, "x-mac-cyrillic", "x-mac-cyrillic" }; yield return new object[] { 10008, "x-mac-chinesesimp", "x-mac-chinesesimp" }; yield return new object[] { 10010, "x-mac-romanian", "x-mac-romanian" }; yield return new object[] { 10017, "x-mac-ukrainian", "x-mac-ukrainian" }; yield return new object[] { 10021, "x-mac-thai", "x-mac-thai" }; yield return new object[] { 10029, "x-mac-ce", "x-mac-ce" }; yield return new object[] { 10079, "x-mac-icelandic", "x-mac-icelandic" }; yield return new object[] { 10081, "x-mac-turkish", "x-mac-turkish" }; yield return new object[] { 10082, "x-mac-croatian", "x-mac-croatian" }; yield return new object[] { 20000, "x-chinese-cns", "x-chinese-cns" }; yield return new object[] { 20001, "x-cp20001", "x-cp20001" }; yield return new object[] { 20002, "x-chinese-eten", "x-chinese-eten" }; yield return new object[] { 20003, "x-cp20003", "x-cp20003" }; yield return new object[] { 20004, "x-cp20004", "x-cp20004" }; yield return new object[] { 20005, "x-cp20005", "x-cp20005" }; yield return new object[] { 20105, "x-ia5", "x-ia5" }; yield return new object[] { 20105, "x-ia5", "irv" }; yield return new object[] { 20106, "x-ia5-german", "x-ia5-german" }; yield return new object[] { 20106, "x-ia5-german", "din_66003" }; yield return new object[] { 20106, "x-ia5-german", "german" }; yield return new object[] { 20107, "x-ia5-swedish", "x-ia5-swedish" }; yield return new object[] { 20107, "x-ia5-swedish", "sen_850200_b" }; yield return new object[] { 20107, "x-ia5-swedish", "swedish" }; yield return new object[] { 20108, "x-ia5-norwegian", "x-ia5-norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "norwegian" }; yield return new object[] { 20108, "x-ia5-norwegian", "ns_4551-1" }; yield return new object[] { 20261, "x-cp20261", "x-cp20261" }; yield return new object[] { 20269, "x-cp20269", "x-cp20269" }; yield return new object[] { 20273, "ibm273", "ibm273" }; yield return new object[] { 20273, "ibm273", "cp273" }; yield return new object[] { 20273, "ibm273", "csibm273" }; yield return new object[] { 20277, "ibm277", "ibm277" }; yield return new object[] { 20277, "ibm277", "csibm277" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-dk" }; yield return new object[] { 20277, "ibm277", "ebcdic-cp-no" }; yield return new object[] { 20278, "ibm278", "ibm278" }; yield return new object[] { 20278, "ibm278", "cp278" }; yield return new object[] { 20278, "ibm278", "csibm278" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-fi" }; yield return new object[] { 20278, "ibm278", "ebcdic-cp-se" }; yield return new object[] { 20280, "ibm280", "ibm280" }; yield return new object[] { 20280, "ibm280", "cp280" }; yield return new object[] { 20280, "ibm280", "csibm280" }; yield return new object[] { 20280, "ibm280", "ebcdic-cp-it" }; yield return new object[] { 20284, "ibm284", "ibm284" }; yield return new object[] { 20284, "ibm284", "cp284" }; yield return new object[] { 20284, "ibm284", "csibm284" }; yield return new object[] { 20284, "ibm284", "ebcdic-cp-es" }; yield return new object[] { 20285, "ibm285", "ibm285" }; yield return new object[] { 20285, "ibm285", "cp285" }; yield return new object[] { 20285, "ibm285", "csibm285" }; yield return new object[] { 20285, "ibm285", "ebcdic-cp-gb" }; yield return new object[] { 20290, "ibm290", "ibm290" }; yield return new object[] { 20290, "ibm290", "cp290" }; yield return new object[] { 20290, "ibm290", "csibm290" }; yield return new object[] { 20290, "ibm290", "ebcdic-jp-kana" }; yield return new object[] { 20297, "ibm297", "ibm297" }; yield return new object[] { 20297, "ibm297", "cp297" }; yield return new object[] { 20297, "ibm297", "csibm297" }; yield return new object[] { 20297, "ibm297", "ebcdic-cp-fr" }; yield return new object[] { 20420, "ibm420", "ibm420" }; yield return new object[] { 20420, "ibm420", "cp420" }; yield return new object[] { 20420, "ibm420", "csibm420" }; yield return new object[] { 20420, "ibm420", "ebcdic-cp-ar1" }; yield return new object[] { 20423, "ibm423", "ibm423" }; yield return new object[] { 20423, "ibm423", "cp423" }; yield return new object[] { 20423, "ibm423", "csibm423" }; yield return new object[] { 20423, "ibm423", "ebcdic-cp-gr" }; yield return new object[] { 20424, "ibm424", "ibm424" }; yield return new object[] { 20424, "ibm424", "cp424" }; yield return new object[] { 20424, "ibm424", "csibm424" }; yield return new object[] { 20424, "ibm424", "ebcdic-cp-he" }; yield return new object[] { 20833, "x-ebcdic-koreanextended", "x-ebcdic-koreanextended" }; yield return new object[] { 20838, "ibm-thai", "ibm-thai" }; yield return new object[] { 20838, "ibm-thai", "csibmthai" }; yield return new object[] { 20866, "koi8-r", "koi8-r" }; yield return new object[] { 20866, "koi8-r", "cskoi8r" }; yield return new object[] { 20866, "koi8-r", "koi" }; yield return new object[] { 20866, "koi8-r", "koi8" }; yield return new object[] { 20866, "koi8-r", "koi8r" }; yield return new object[] { 20871, "ibm871", "ibm871" }; yield return new object[] { 20871, "ibm871", "cp871" }; yield return new object[] { 20871, "ibm871", "csibm871" }; yield return new object[] { 20871, "ibm871", "ebcdic-cp-is" }; yield return new object[] { 20880, "ibm880", "ibm880" }; yield return new object[] { 20880, "ibm880", "cp880" }; yield return new object[] { 20880, "ibm880", "csibm880" }; yield return new object[] { 20880, "ibm880", "ebcdic-cyrillic" }; yield return new object[] { 20905, "ibm905", "ibm905" }; yield return new object[] { 20905, "ibm905", "cp905" }; yield return new object[] { 20905, "ibm905", "csibm905" }; yield return new object[] { 20905, "ibm905", "ebcdic-cp-tr" }; yield return new object[] { 20924, "ibm00924", "ibm00924" }; yield return new object[] { 20924, "ibm00924", "ccsid00924" }; yield return new object[] { 20924, "ibm00924", "cp00924" }; yield return new object[] { 20924, "ibm00924", "ebcdic-latin9--euro" }; yield return new object[] { 20932, "euc-jp", "euc-jp" }; yield return new object[] { 20936, "x-cp20936", "x-cp20936" }; yield return new object[] { 20949, "x-cp20949", "x-cp20949" }; yield return new object[] { 21025, "cp1025", "cp1025" }; yield return new object[] { 21866, "koi8-u", "koi8-u" }; yield return new object[] { 21866, "koi8-u", "koi8-ru" }; yield return new object[] { 28592, "iso-8859-2", "iso-8859-2" }; yield return new object[] { 28592, "iso-8859-2", "csisolatin2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso_8859-2:1987" }; yield return new object[] { 28592, "iso-8859-2", "iso8859-2" }; yield return new object[] { 28592, "iso-8859-2", "iso-ir-101" }; yield return new object[] { 28592, "iso-8859-2", "l2" }; yield return new object[] { 28592, "iso-8859-2", "latin2" }; yield return new object[] { 28593, "iso-8859-3", "iso-8859-3" }; yield return new object[] { 28593, "iso-8859-3", "csisolatin3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3" }; yield return new object[] { 28593, "iso-8859-3", "iso_8859-3:1988" }; yield return new object[] { 28593, "iso-8859-3", "iso-ir-109" }; yield return new object[] { 28593, "iso-8859-3", "l3" }; yield return new object[] { 28593, "iso-8859-3", "latin3" }; yield return new object[] { 28594, "iso-8859-4", "iso-8859-4" }; yield return new object[] { 28594, "iso-8859-4", "csisolatin4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4" }; yield return new object[] { 28594, "iso-8859-4", "iso_8859-4:1988" }; yield return new object[] { 28594, "iso-8859-4", "iso-ir-110" }; yield return new object[] { 28594, "iso-8859-4", "l4" }; yield return new object[] { 28594, "iso-8859-4", "latin4" }; yield return new object[] { 28595, "iso-8859-5", "iso-8859-5" }; yield return new object[] { 28595, "iso-8859-5", "csisolatincyrillic" }; yield return new object[] { 28595, "iso-8859-5", "cyrillic" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5" }; yield return new object[] { 28595, "iso-8859-5", "iso_8859-5:1988" }; yield return new object[] { 28595, "iso-8859-5", "iso-ir-144" }; yield return new object[] { 28596, "iso-8859-6", "iso-8859-6" }; yield return new object[] { 28596, "iso-8859-6", "arabic" }; yield return new object[] { 28596, "iso-8859-6", "csisolatinarabic" }; yield return new object[] { 28596, "iso-8859-6", "ecma-114" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6" }; yield return new object[] { 28596, "iso-8859-6", "iso_8859-6:1987" }; yield return new object[] { 28596, "iso-8859-6", "iso-ir-127" }; yield return new object[] { 28597, "iso-8859-7", "iso-8859-7" }; yield return new object[] { 28597, "iso-8859-7", "csisolatingreek" }; yield return new object[] { 28597, "iso-8859-7", "ecma-118" }; yield return new object[] { 28597, "iso-8859-7", "elot_928" }; yield return new object[] { 28597, "iso-8859-7", "greek" }; yield return new object[] { 28597, "iso-8859-7", "greek8" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7" }; yield return new object[] { 28597, "iso-8859-7", "iso_8859-7:1987" }; yield return new object[] { 28597, "iso-8859-7", "iso-ir-126" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8" }; yield return new object[] { 28598, "iso-8859-8", "csisolatinhebrew" }; yield return new object[] { 28598, "iso-8859-8", "hebrew" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8" }; yield return new object[] { 28598, "iso-8859-8", "iso_8859-8:1988" }; yield return new object[] { 28598, "iso-8859-8", "iso-8859-8 visual" }; yield return new object[] { 28598, "iso-8859-8", "iso-ir-138" }; yield return new object[] { 28598, "iso-8859-8", "logical" }; yield return new object[] { 28598, "iso-8859-8", "visual" }; yield return new object[] { 28599, "iso-8859-9", "iso-8859-9" }; yield return new object[] { 28599, "iso-8859-9", "csisolatin5" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9" }; yield return new object[] { 28599, "iso-8859-9", "iso_8859-9:1989" }; yield return new object[] { 28599, "iso-8859-9", "iso-ir-148" }; yield return new object[] { 28599, "iso-8859-9", "l5" }; yield return new object[] { 28599, "iso-8859-9", "latin5" }; yield return new object[] { 28603, "iso-8859-13", "iso-8859-13" }; yield return new object[] { 28605, "iso-8859-15", "iso-8859-15" }; yield return new object[] { 28605, "iso-8859-15", "csisolatin9" }; yield return new object[] { 28605, "iso-8859-15", "iso_8859-15" }; yield return new object[] { 28605, "iso-8859-15", "l9" }; yield return new object[] { 28605, "iso-8859-15", "latin9" }; yield return new object[] { 29001, "x-europa", "x-europa" }; yield return new object[] { 38598, "iso-8859-8-i", "iso-8859-8-i" }; yield return new object[] { 50220, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50221, "csiso2022jp", "csiso2022jp" }; yield return new object[] { 50222, "iso-2022-jp", "iso-2022-jp" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr" }; yield return new object[] { 50225, "iso-2022-kr", "csiso2022kr" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7" }; yield return new object[] { 50225, "iso-2022-kr", "iso-2022-kr-7bit" }; yield return new object[] { 50227, "x-cp50227", "x-cp50227" }; yield return new object[] { 50227, "x-cp50227", "cp50227" }; yield return new object[] { 51932, "euc-jp", "euc-jp" }; yield return new object[] { 51932, "euc-jp", "cseucpkdfmtjapanese" }; yield return new object[] { 51932, "euc-jp", "extended_unix_code_packed_format_for_japanese" }; yield return new object[] { 51932, "euc-jp", "iso-2022-jpeuc" }; yield return new object[] { 51932, "euc-jp", "x-euc" }; yield return new object[] { 51932, "euc-jp", "x-euc-jp" }; yield return new object[] { 51936, "euc-cn", "euc-cn" }; yield return new object[] { 51936, "euc-cn", "x-euc-cn" }; yield return new object[] { 51949, "euc-kr", "euc-kr" }; yield return new object[] { 51949, "euc-kr", "cseuckr" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8" }; yield return new object[] { 51949, "euc-kr", "iso-2022-kr-8bit" }; yield return new object[] { 52936, "hz-gb-2312", "hz-gb-2312" }; yield return new object[] { 54936, "gb18030", "gb18030" }; yield return new object[] { 57002, "x-iscii-de", "x-iscii-de" }; yield return new object[] { 57003, "x-iscii-be", "x-iscii-be" }; yield return new object[] { 57004, "x-iscii-ta", "x-iscii-ta" }; yield return new object[] { 57005, "x-iscii-te", "x-iscii-te" }; yield return new object[] { 57006, "x-iscii-as", "x-iscii-as" }; yield return new object[] { 57007, "x-iscii-or", "x-iscii-or" }; yield return new object[] { 57008, "x-iscii-ka", "x-iscii-ka" }; yield return new object[] { 57009, "x-iscii-ma", "x-iscii-ma" }; yield return new object[] { 57010, "x-iscii-gu", "x-iscii-gu" }; yield return new object[] { 57011, "x-iscii-pa", "x-iscii-pa" }; } public static IEnumerable<object[]> SpecificCodepageEncodings() { // Layout is codepage encoding, bytes, and matching unicode string. yield return new object[] { "Windows-1256", new byte[] { 0xC7, 0xE1, 0xE1, 0xE5, 0x20, 0xC7, 0xCD, 0xCF }, "\x0627\x0644\x0644\x0647\x0020\x0627\x062D\x062F" }; yield return new object[] {"Windows-1252", new byte[] { 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF } , "\x00D0\x00D1\x00D2\x00D3\x00D4\x00D5\x00D6\x00D7\x00D8\x00D9\x00DA\x00DB\x00DC\x00DD\x00DE\x00DF"}; yield return new object[] { "GB2312", new byte[] { 0xCD, 0xE2, 0xCD, 0xE3, 0xCD, 0xE4 }, "\x5916\x8C4C\x5F2F" }; yield return new object[] {"GB18030", new byte[] { 0x81, 0x30, 0x89, 0x37, 0x81, 0x30, 0x89, 0x38, 0xA8, 0xA4, 0xA8, 0xA2, 0x81, 0x30, 0x89, 0x39, 0x81, 0x30, 0x8A, 0x30 } , "\x00DE\x00DF\x00E0\x00E1\x00E2\x00E3"}; } public static IEnumerable<object[]> MultibyteCharacterEncodings() { // Layout is the encoding, bytes, and expected result. yield return new object[] { "iso-2022-jp", new byte[] { 0xA, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x1B, 0x24, 0x42, 0x25, 0x4A, 0x0E, 0x25, 0x4A, 0x1B, 0x28, 0x42, 0x41, 0x42, 0x0E, 0x25, 0x0F, 0x43 }, new int[] { 0xA, 0x30CA, 0x30CA, 0x30CA, 0x30CA, 0x1B, 0x1, 0x2, 0x3, 0x4, 0x30CA, 0xFF65, 0xFF8A, 0x41, 0x42, 0xFF65, 0x43} }; yield return new object[] { "GB18030", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x40, 0x82, 0x80, 0x81, 0x30, 0x82, 0x31, 0x81, 0x20 }, new int[] { 0x41, 0x42, 0x43, 0x4E02, 0x500B, 0x8B, 0x3F, 0x20 } }; yield return new object[] { "shift_jis", new byte[] { 0x41, 0x42, 0x43, 0x81, 0x42, 0xE0, 0x43, 0x44, 0x45 }, new int[] { 0x41, 0x42, 0x43, 0x3002, 0x6F86, 0x44, 0x45 } }; yield return new object[] { "iso-2022-kr", new byte[] { 0x0E, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E, 0x0F, 0x21, 0x7E, 0x1B, 0x24, 0x29, 0x43, 0x21, 0x7E }, new int[] { 0xFFE2, 0xFFE2, 0x21, 0x7E, 0x21, 0x7E } }; yield return new object[] { "hz-gb-2312", new byte[] { 0x7E, 0x42, 0x7E, 0x7E, 0x7E, 0x7B, 0x21, 0x7E, 0x7E, 0x7D, 0x42, 0x42, 0x7E, 0xA, 0x43, 0x43 }, new int[] { 0x7E, 0x42, 0x7E, 0x3013, 0x42, 0x42, 0x43, 0x43, } }; } private static IEnumerable<KeyValuePair<int, string>> CrossplatformDefaultEncodings() { yield return Map(1200, "utf-16"); yield return Map(12000, "utf-32"); yield return Map(20127, "us-ascii"); yield return Map(65000, "utf-7"); yield return Map(65001, "utf-8"); } private static KeyValuePair<int, string> Map(int codePage, string webName) { return new KeyValuePair<int, string>(codePage, webName); } [Fact] public static void TestDefaultEncodings() { ValidateDefaultEncodings(); // The default encoding should be something from the known list. Encoding defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); KeyValuePair<int, string> mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); if (defaultEncoding.CodePage == Encoding.UTF8.CodePage) { // if the default encoding is not UTF8 that means either we are running on the full framework // or the encoding provider is registered throw the call Encoding.RegisterProvider. // at that time we shouldn't expect exceptions when creating the following encodings. foreach (object[] mapping in CodePageInfo()) { Assert.Throws<NotSupportedException>(() => Encoding.GetEncoding((int)mapping[0])); Assert.Throws<ArgumentException>(() => Encoding.GetEncoding((string)mapping[2])); } // Currently the class EncodingInfo isn't present in corefx, so this checks none of the code pages are present. // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings, Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings()); } // Add the code page provider. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Make sure added code pages are identical between the provider and the Encoding class. foreach (object[] mapping in CodePageInfo()) { Encoding encoding = Encoding.GetEncoding((int)mapping[0]); Encoding codePageEncoding = CodePagesEncodingProvider.Instance.GetEncoding((int)mapping[0]); Assert.Equal(encoding, codePageEncoding); Assert.Equal(encoding.CodePage, (int)mapping[0]); Assert.Equal(encoding.WebName, (string)mapping[1]); // If available, validate serializing and deserializing with BinaryFormatter ValidateSerializeDeserialize(encoding); // Get encoding via query string. Assert.Equal(Encoding.GetEncoding((string)mapping[2]), CodePagesEncodingProvider.Instance.GetEncoding((string)mapping[2])); } // Adding the code page provider should keep the originals, too. ValidateDefaultEncodings(); // Currently the class EncodingInfo isn't present in corefx, so this checks the complete list // When it is, comment out this line and remove the previous foreach/assert. // Assert.Equal(CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])).OrderBy(i => i.Key)), // Encoding.GetEncodings().OrderBy(i => i.CodePage).Select(i => Map(i.CodePage, i.WebName))); // Default encoding may have changed, should still be something on the combined list. defaultEncoding = Encoding.GetEncoding(0); Assert.NotNull(defaultEncoding); mappedEncoding = Map(defaultEncoding.CodePage, defaultEncoding.WebName); Assert.Contains(mappedEncoding, CrossplatformDefaultEncodings().Union(CodePageInfo().Select(i => Map((int)i[0], (string)i[1])))); } static partial void ValidateSerializeDeserialize(Encoding e); private static void ValidateDefaultEncodings() { foreach (var mapping in CrossplatformDefaultEncodings()) { Encoding encoding = Encoding.GetEncoding(mapping.Key); Assert.NotNull(encoding); Assert.Equal(encoding, Encoding.GetEncoding(mapping.Value)); Assert.Equal(mapping.Value, encoding.WebName); } } [Theory] [MemberData(nameof(SpecificCodepageEncodings))] public static void TestRoundtrippingSpecificCodepageEncoding(string encodingName, byte[] bytes, string expected) { Encoding encoding = CodePagesEncodingProvider.Instance.GetEncoding(encodingName); string encoded = encoding.GetString(bytes, 0, bytes.Length); Assert.Equal(expected, encoded); Assert.Equal(bytes, encoding.GetBytes(encoded)); byte[] resultBytes = encoding.GetBytes(encoded); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestCodepageEncoding(int codePage, string webName, string queryString) { Encoding encoding; // There are two names that have duplicate associated CodePages. For those two names, // we have to test with the expectation that querying the name will always return the // same codepage. if (codePage != 20932 && codePage != 50222) { encoding = CodePagesEncodingProvider.Instance.GetEncoding(queryString); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(codePage)); Assert.Equal(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } else { encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(queryString)); Assert.NotEqual(encoding, CodePagesEncodingProvider.Instance.GetEncoding(webName)); } Assert.NotNull(encoding); Assert.Equal(codePage, encoding.CodePage); Assert.Equal(webName, encoding.WebName); // Small round-trip for ASCII alphanumeric range (some code pages use different punctuation!) // Start with space. string asciiPrintable = " 0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char[] traveled = encoding.GetChars(encoding.GetBytes(asciiPrintable)); Assert.Equal(asciiPrintable.ToCharArray(), traveled); } [Theory] [MemberData(nameof(MultibyteCharacterEncodings))] public static void TestSpecificMultibyteCharacterEncodings(string codepageName, byte[] bytes, int[] expected) { Decoder decoder = CodePagesEncodingProvider.Instance.GetEncoding(codepageName).GetDecoder(); char[] buffer = new char[expected.Length]; for (int byteIndex = 0, charIndex = 0, charCount = 0; byteIndex < bytes.Length; byteIndex++, charIndex += charCount) { charCount = decoder.GetChars(bytes, byteIndex, 1, buffer, charIndex); } Assert.Equal(expected, buffer.Select(c => (int)c)); } [Theory] [MemberData(nameof(CodePageInfo))] public static void TestEncodingDisplayNames(int codePage, string webName, string queryString) { var encoding = CodePagesEncodingProvider.Instance.GetEncoding(codePage); string name = encoding.EncodingName; // Names can't be empty, and must be printable characters. Assert.False(string.IsNullOrWhiteSpace(name)); Assert.All(name, c => Assert.True(c >= ' ' && c < '~' + 1, "Name: " + name + " contains character: " + c)); } } public class CultureSetup : IDisposable { private readonly CultureInfo _originalUICulture; public CultureSetup() { _originalUICulture = CultureInfo.CurrentUICulture; CultureInfo.CurrentUICulture = new CultureInfo("en-US"); } public void Dispose() { CultureInfo.CurrentUICulture = _originalUICulture; } } }
/* * 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.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using RegionFlags = OpenMetaverse.RegionFlags; namespace OpenSim.Region.CoreModules.World.Land { /// <summary> /// Keeps track of a specific piece of land's information /// </summary> public class LandObject : ILandObject { #region Member Variables private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #pragma warning disable 0429 private const int landArrayMax = ((int)((int)Constants.RegionSize / 4) >= 64) ? (int)((int)Constants.RegionSize / 4) : 64; #pragma warning restore 0429 private bool[,] m_landBitmap = new bool[landArrayMax,landArrayMax]; private int m_lastSeqId = 0; protected LandData m_landData = new LandData(); protected Scene m_scene; protected List<SceneObjectGroup> primsOverMe = new List<SceneObjectGroup>(); protected Dictionary<uint, UUID> m_listTransactions = new Dictionary<uint, UUID>(); protected ExpiringCache<UUID, bool> m_groupMemberCache = new ExpiringCache<UUID, bool>(); protected TimeSpan m_groupMemberCacheTimeout = TimeSpan.FromSeconds(30); // cache invalidation after 30 seconds public bool[,] LandBitmap { get { return m_landBitmap; } set { m_landBitmap = value; } } #endregion public int GetPrimsFree() { m_scene.EventManager.TriggerParcelPrimCountUpdate(); int free = GetSimulatorMaxPrimCount() - m_landData.SimwidePrims; return free; } public LandData LandData { get { return m_landData; } set { m_landData = value; } } public IPrimCounts PrimCounts { get; set; } public UUID RegionUUID { get { return m_scene.RegionInfo.RegionID; } } public Vector3 StartPoint { get { for (int y = 0; y < landArrayMax; y++) { for (int x = 0; x < landArrayMax; x++) { if (LandBitmap[x, y]) return new Vector3(x * 4, y * 4, 0); } } return new Vector3(-1, -1, -1); } } public Vector3 EndPoint { get { for (int y = landArrayMax - 1; y >= 0; y--) { for (int x = landArrayMax - 1; x >= 0; x--) { if (LandBitmap[x, y]) { return new Vector3(x * 4 + 4, y * 4 + 4, 0); } } } return new Vector3(-1, -1, -1); } } #region Constructors public LandObject(UUID owner_id, bool is_group_owned, Scene scene) { m_scene = scene; LandData.OwnerID = owner_id; if (is_group_owned) LandData.GroupID = owner_id; else LandData.GroupID = UUID.Zero; LandData.IsGroupOwned = is_group_owned; } #endregion #region Member Functions #region General Functions /// <summary> /// Checks to see if this land object contains a point /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns>Returns true if the piece of land contains the specified point</returns> public bool ContainsPoint(int x, int y) { if (x >= 0 && y >= 0 && x < Constants.RegionSize && y < Constants.RegionSize) { return (LandBitmap[x / 4, y / 4] == true); } else { return false; } } public ILandObject Copy() { ILandObject newLand = new LandObject(LandData.OwnerID, LandData.IsGroupOwned, m_scene); //Place all new variables here! newLand.LandBitmap = (bool[,]) (LandBitmap.Clone()); newLand.LandData = LandData.Copy(); return newLand; } static overrideParcelMaxPrimCountDelegate overrideParcelMaxPrimCount; static overrideSimulatorMaxPrimCountDelegate overrideSimulatorMaxPrimCount; public void SetParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { overrideParcelMaxPrimCount = overrideDel; } public void SetSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { overrideSimulatorMaxPrimCount = overrideDel; } public int GetParcelMaxPrimCount() { if (overrideParcelMaxPrimCount != null) { return overrideParcelMaxPrimCount(this); } else { // Normal Calculations int parcelMax = (int)(((float)LandData.Area / 65536.0f) * (float)m_scene.RegionInfo.ObjectCapacity * (float)m_scene.RegionInfo.RegionSettings.ObjectBonus); // TODO: The calculation of ObjectBonus should be refactored. It does still not work in the same manner as SL! return parcelMax; } } public int GetSimulatorMaxPrimCount() { if (overrideSimulatorMaxPrimCount != null) { return overrideSimulatorMaxPrimCount(this); } else { //Normal Calculations int simMax = (int)(((float)LandData.SimwideArea / 65536.0f) * (float)m_scene.RegionInfo.ObjectCapacity); return simMax; } } #endregion #region Packet Request Handling public void SendLandProperties(int sequence_id, bool snap_selection, int request_result, IClientAPI remote_client) { IEstateModule estateModule = m_scene.RequestModuleInterface<IEstateModule>(); uint regionFlags = 336723974 & ~((uint)(RegionFlags.AllowLandmark | RegionFlags.AllowSetHome)); if (estateModule != null) regionFlags = estateModule.GetRegionFlags(); int seq_id; if (snap_selection && (sequence_id == 0)) { seq_id = m_lastSeqId; } else { seq_id = sequence_id; m_lastSeqId = seq_id; } remote_client.SendLandProperties(seq_id, snap_selection, request_result, this, (float)m_scene.RegionInfo.RegionSettings.ObjectBonus, GetParcelMaxPrimCount(), GetSimulatorMaxPrimCount(), regionFlags); } public void UpdateLandProperties(LandUpdateArgs args, IClientAPI remote_client) { //Needs later group support bool snap_selection = false; LandData newData = LandData.Copy(); uint allowedDelta = 0; // These two are always blocked as no client can set them anyway // ParcelFlags.ForSaleObjects // ParcelFlags.LindenHome if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions)) { allowedDelta |= (uint)(ParcelFlags.AllowLandmark | ParcelFlags.AllowTerraform | ParcelFlags.AllowDamage | ParcelFlags.CreateObjects | ParcelFlags.RestrictPushObject | ParcelFlags.AllowOtherScripts | ParcelFlags.AllowGroupScripts | ParcelFlags.CreateGroupObjects | ParcelFlags.AllowAPrimitiveEntry | ParcelFlags.AllowGroupObjectEntry | ParcelFlags.AllowFly); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandSetSale)) { if (args.AuthBuyerID != newData.AuthBuyerID || args.SalePrice != newData.SalePrice) { snap_selection = true; } newData.AuthBuyerID = args.AuthBuyerID; newData.SalePrice = args.SalePrice; if (!LandData.IsGroupOwned) { newData.GroupID = args.GroupID; allowedDelta |= (uint)(ParcelFlags.AllowDeedToGroup | ParcelFlags.ContributeWithDeed | ParcelFlags.SellParcelObjects); } allowedDelta |= (uint)ParcelFlags.ForSale; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.FindPlaces)) { newData.Category = args.Category; allowedDelta |= (uint)(ParcelFlags.ShowDirectory | ParcelFlags.AllowPublish | ParcelFlags.MaturePublish); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandChangeIdentity)) { newData.Description = args.Desc; newData.Name = args.Name; newData.SnapshotID = args.SnapshotID; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.SetLandingPoint)) { newData.LandingType = args.LandingType; newData.UserLocation = args.UserLocation; newData.UserLookAt = args.UserLookAt; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.ChangeMedia)) { newData.MediaAutoScale = args.MediaAutoScale; newData.MediaID = args.MediaID; newData.MediaURL = args.MediaURL; newData.MusicURL = args.MusicURL; newData.MediaType = args.MediaType; newData.MediaDescription = args.MediaDescription; newData.MediaWidth = args.MediaWidth; newData.MediaHeight = args.MediaHeight; newData.MediaLoop = args.MediaLoop; newData.ObscureMusic = args.ObscureMusic; newData.ObscureMedia = args.ObscureMedia; allowedDelta |= (uint)(ParcelFlags.SoundLocal | ParcelFlags.UrlWebPage | ParcelFlags.UrlRawHtml | ParcelFlags.AllowVoiceChat | ParcelFlags.UseEstateVoiceChan); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId,this, GroupPowers.LandManagePasses)) { newData.PassHours = args.PassHours; newData.PassPrice = args.PassPrice; allowedDelta |= (uint)ParcelFlags.UsePassList; } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandManageAllowed)) { allowedDelta |= (uint)(ParcelFlags.UseAccessGroup | ParcelFlags.UseAccessList); } if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandManageBanned)) { allowedDelta |= (uint)(ParcelFlags.UseBanList | ParcelFlags.DenyAnonymous | ParcelFlags.DenyAgeUnverified); } uint preserve = LandData.Flags & ~allowedDelta; newData.Flags = preserve | (args.ParcelFlags & allowedDelta); m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); SendLandUpdateToAvatarsOverMe(snap_selection); } public void UpdateLandSold(UUID avatarID, UUID groupID, bool groupOwned, uint AuctionID, int claimprice, int area) { LandData newData = LandData.Copy(); newData.OwnerID = avatarID; newData.GroupID = groupID; newData.IsGroupOwned = groupOwned; //newData.auctionID = AuctionID; newData.ClaimDate = Util.UnixTimeSinceEpoch(); newData.ClaimPrice = claimprice; newData.SalePrice = 0; newData.AuthBuyerID = UUID.Zero; newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); m_scene.EventManager.TriggerParcelPrimCountUpdate(); SendLandUpdateToAvatarsOverMe(true); } public void DeedToGroup(UUID groupID) { LandData newData = LandData.Copy(); newData.OwnerID = groupID; newData.GroupID = groupID; newData.IsGroupOwned = true; // Reset show in directory flag on deed newData.Flags &= ~(uint) (ParcelFlags.ForSale | ParcelFlags.ForSaleObjects | ParcelFlags.SellParcelObjects | ParcelFlags.ShowDirectory); m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); m_scene.EventManager.TriggerParcelPrimCountUpdate(); SendLandUpdateToAvatarsOverMe(true); } public bool IsEitherBannedOrRestricted(UUID avatar) { if (IsBannedFromLand(avatar)) { return true; } else if (IsRestrictedFromLand(avatar)) { return true; } return false; } public bool HasGroupAccess(UUID avatar) { if (LandData.GroupID != UUID.Zero && (LandData.Flags & (uint)ParcelFlags.UseAccessGroup) == (uint)ParcelFlags.UseAccessGroup) { ScenePresence sp; if (!m_scene.TryGetScenePresence(avatar, out sp)) { bool isMember; if (m_groupMemberCache.TryGetValue(avatar, out isMember)) { m_groupMemberCache.Update(avatar, isMember, m_groupMemberCacheTimeout); return isMember; } IGroupsModule groupsModule = m_scene.RequestModuleInterface<IGroupsModule>(); if (groupsModule == null) return false; GroupMembershipData[] membership = groupsModule.GetMembershipData(avatar); if (membership == null || membership.Length == 0) { m_groupMemberCache.Add(avatar, false, m_groupMemberCacheTimeout); return false; } foreach (GroupMembershipData d in membership) { if (d.GroupID == LandData.GroupID) { m_groupMemberCache.Add(avatar, true, m_groupMemberCacheTimeout); return true; } } m_groupMemberCache.Add(avatar, false, m_groupMemberCacheTimeout); return false; } return sp.ControllingClient.IsGroupMember(LandData.GroupID); } return false; } public bool IsBannedFromLand(UUID avatar) { ExpireAccessList(); if (m_scene.Permissions.IsAdministrator(avatar)) return false; if (m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(avatar)) return false; if (avatar == LandData.OwnerID) return false; if ((LandData.Flags & (uint) ParcelFlags.UseBanList) > 0) { if (LandData.ParcelAccessList.FindIndex( delegate(LandAccessEntry e) { if (e.AgentID == avatar && e.Flags == AccessList.Ban) return true; return false; }) != -1) { return true; } } return false; } public bool IsRestrictedFromLand(UUID avatar) { if ((LandData.Flags & (uint) ParcelFlags.UseAccessList) == 0) return false; if (m_scene.Permissions.IsAdministrator(avatar)) return false; if (m_scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(avatar)) return false; if (avatar == LandData.OwnerID) return false; if (HasGroupAccess(avatar)) return false; return !IsInLandAccessList(avatar); } public bool IsInLandAccessList(UUID avatar) { ExpireAccessList(); if (LandData.ParcelAccessList.FindIndex( delegate(LandAccessEntry e) { if (e.AgentID == avatar && e.Flags == AccessList.Access) return true; return false; }) == -1) { return false; } return true; } public void SendLandUpdateToClient(IClientAPI remote_client) { SendLandProperties(0, false, 0, remote_client); } public void SendLandUpdateToClient(bool snap_selection, IClientAPI remote_client) { m_scene.EventManager.TriggerParcelPrimCountUpdate(); SendLandProperties(0, snap_selection, 0, remote_client); } public void SendLandUpdateToAvatarsOverMe() { SendLandUpdateToAvatarsOverMe(false); } public void SendLandUpdateToAvatarsOverMe(bool snap_selection) { m_scene.ForEachRootScenePresence(delegate(ScenePresence avatar) { ILandObject over = null; try { over = m_scene.LandChannel.GetLandObject(Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.X), 0, ((int)Constants.RegionSize - 1)), Util.Clamp<int>((int)Math.Round(avatar.AbsolutePosition.Y), 0, ((int)Constants.RegionSize - 1))); } catch (Exception) { m_log.Warn("[LAND]: " + "unable to get land at x: " + Math.Round(avatar.AbsolutePosition.X) + " y: " + Math.Round(avatar.AbsolutePosition.Y)); } if (over != null) { if (over.LandData.LocalID == LandData.LocalID) { if (((over.LandData.Flags & (uint)ParcelFlags.AllowDamage) != 0) && m_scene.RegionInfo.RegionSettings.AllowDamage) avatar.Invulnerable = false; else avatar.Invulnerable = true; SendLandUpdateToClient(snap_selection, avatar.ControllingClient); } } }); } #endregion #region AccessList Functions public List<LandAccessEntry> CreateAccessListArrayByFlag(AccessList flag) { ExpireAccessList(); List<LandAccessEntry> list = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in LandData.ParcelAccessList) { if (entry.Flags == flag) list.Add(entry); } if (list.Count == 0) { LandAccessEntry e = new LandAccessEntry(); e.AgentID = UUID.Zero; e.Flags = 0; e.Expires = 0; list.Add(e); } return list; } public void SendAccessList(UUID agentID, UUID sessionID, uint flags, int sequenceID, IClientAPI remote_client) { if (flags == (uint) AccessList.Access || flags == (uint) AccessList.Both) { List<LandAccessEntry> accessEntries = CreateAccessListArrayByFlag(AccessList.Access); remote_client.SendLandAccessListData(accessEntries,(uint) AccessList.Access,LandData.LocalID); } if (flags == (uint) AccessList.Ban || flags == (uint) AccessList.Both) { List<LandAccessEntry> accessEntries = CreateAccessListArrayByFlag(AccessList.Ban); remote_client.SendLandAccessListData(accessEntries, (uint)AccessList.Ban, LandData.LocalID); } } public void UpdateAccessList(uint flags, UUID transactionID, int sequenceID, int sections, List<LandAccessEntry> entries, IClientAPI remote_client) { LandData newData = LandData.Copy(); if ((!m_listTransactions.ContainsKey(flags)) || m_listTransactions[flags] != transactionID) { m_listTransactions[flags] = transactionID; List<LandAccessEntry> toRemove = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in newData.ParcelAccessList) { if (entry.Flags == (AccessList)flags) toRemove.Add(entry); } foreach (LandAccessEntry entry in toRemove) { newData.ParcelAccessList.Remove(entry); } // Checked here because this will always be the first // and only packet in a transaction if (entries.Count == 1 && entries[0].AgentID == UUID.Zero) { m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); return; } } foreach (LandAccessEntry entry in entries) { LandAccessEntry temp = new LandAccessEntry(); temp.AgentID = entry.AgentID; temp.Expires = entry.Expires; temp.Flags = (AccessList)flags; newData.ParcelAccessList.Add(temp); } m_scene.LandChannel.UpdateLandObject(LandData.LocalID, newData); } #endregion #region Update Functions public void UpdateLandBitmapByteArray() { LandData.Bitmap = ConvertLandBitmapToBytes(); } /// <summary> /// Update all settings in land such as area, bitmap byte array, etc /// </summary> public void ForceUpdateLandInfo() { UpdateAABBAndAreaValues(); UpdateLandBitmapByteArray(); } public void SetLandBitmapFromByteArray() { LandBitmap = ConvertBytesToLandBitmap(); } /// <summary> /// Updates the AABBMin and AABBMax values after area/shape modification of the land object /// </summary> private void UpdateAABBAndAreaValues() { int min_x = 64; int min_y = 64; int max_x = 0; int max_y = 0; int tempArea = 0; int x, y; for (x = 0; x < 64; x++) { for (y = 0; y < 64; y++) { if (LandBitmap[x, y] == true) { if (min_x > x) min_x = x; if (min_y > y) min_y = y; if (max_x < x) max_x = x; if (max_y < y) max_y = y; tempArea += 16; //16sqm peice of land } } } int tx = min_x * 4; if (tx > ((int)Constants.RegionSize - 1)) tx = ((int)Constants.RegionSize - 1); int ty = min_y * 4; if (ty > ((int)Constants.RegionSize - 1)) ty = ((int)Constants.RegionSize - 1); LandData.AABBMin = new Vector3( (float)(min_x * 4), (float)(min_y * 4), m_scene != null ? (float)m_scene.Heightmap[tx, ty] : 0); tx = max_x * 4; if (tx > ((int)Constants.RegionSize - 1)) tx = ((int)Constants.RegionSize - 1); ty = max_y * 4; if (ty > ((int)Constants.RegionSize - 1)) ty = ((int)Constants.RegionSize - 1); LandData.AABBMax = new Vector3( (float)(max_x * 4), (float)(max_y * 4), m_scene != null ? (float)m_scene.Heightmap[tx, ty] : 0); LandData.Area = tempArea; } #endregion #region Land Bitmap Functions /// <summary> /// Sets the land's bitmap manually /// </summary> /// <param name="bitmap">64x64 block representing where this land is on a map</param> public void SetLandBitmap(bool[,] bitmap) { if (bitmap.GetLength(0) != 64 || bitmap.GetLength(1) != 64 || bitmap.Rank != 2) { //Throw an exception - The bitmap is not 64x64 //throw new Exception("Error: Invalid Parcel Bitmap"); } else { //Valid: Lets set it LandBitmap = bitmap; ForceUpdateLandInfo(); } } /// <summary> /// Gets the land's bitmap manually /// </summary> /// <returns></returns> public bool[,] GetLandBitmap() { return LandBitmap; } public bool[,] BasicFullRegionLandBitmap() { return GetSquareLandBitmap(0, 0, (int) Constants.RegionSize, (int) Constants.RegionSize); } public bool[,] GetSquareLandBitmap(int start_x, int start_y, int end_x, int end_y) { bool[,] tempBitmap = new bool[64,64]; tempBitmap.Initialize(); tempBitmap = ModifyLandBitmapSquare(tempBitmap, start_x, start_y, end_x, end_y, true); return tempBitmap; } /// <summary> /// Change a land bitmap at within a square and set those points to a specific value /// </summary> /// <param name="land_bitmap"></param> /// <param name="start_x"></param> /// <param name="start_y"></param> /// <param name="end_x"></param> /// <param name="end_y"></param> /// <param name="set_value"></param> /// <returns></returns> public bool[,] ModifyLandBitmapSquare(bool[,] land_bitmap, int start_x, int start_y, int end_x, int end_y, bool set_value) { if (land_bitmap.GetLength(0) != 64 || land_bitmap.GetLength(1) != 64 || land_bitmap.Rank != 2) { //Throw an exception - The bitmap is not 64x64 //throw new Exception("Error: Invalid Parcel Bitmap in modifyLandBitmapSquare()"); } int x, y; for (y = 0; y < 64; y++) { for (x = 0; x < 64; x++) { if (x >= start_x / 4 && x < end_x / 4 && y >= start_y / 4 && y < end_y / 4) { land_bitmap[x, y] = set_value; } } } return land_bitmap; } /// <summary> /// Join the true values of 2 bitmaps together /// </summary> /// <param name="bitmap_base"></param> /// <param name="bitmap_add"></param> /// <returns></returns> public bool[,] MergeLandBitmaps(bool[,] bitmap_base, bool[,] bitmap_add) { if (bitmap_base.GetLength(0) != 64 || bitmap_base.GetLength(1) != 64 || bitmap_base.Rank != 2) { //Throw an exception - The bitmap is not 64x64 throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_base in mergeLandBitmaps"); } if (bitmap_add.GetLength(0) != 64 || bitmap_add.GetLength(1) != 64 || bitmap_add.Rank != 2) { //Throw an exception - The bitmap is not 64x64 throw new Exception("Error: Invalid Parcel Bitmap - Bitmap_add in mergeLandBitmaps"); } int x, y; for (y = 0; y < 64; y++) { for (x = 0; x < 64; x++) { if (bitmap_add[x, y]) { bitmap_base[x, y] = true; } } } return bitmap_base; } /// <summary> /// Converts the land bitmap to a packet friendly byte array /// </summary> /// <returns></returns> private byte[] ConvertLandBitmapToBytes() { byte[] tempConvertArr = new byte[512]; byte tempByte = 0; int x, y, i, byteNum = 0; i = 0; for (y = 0; y < 64; y++) { for (x = 0; x < 64; x++) { tempByte = Convert.ToByte(tempByte | Convert.ToByte(LandBitmap[x, y]) << (i++ % 8)); if (i % 8 == 0) { tempConvertArr[byteNum] = tempByte; tempByte = (byte) 0; i = 0; byteNum++; } } } return tempConvertArr; } private bool[,] ConvertBytesToLandBitmap() { bool[,] tempConvertMap = new bool[landArrayMax, landArrayMax]; tempConvertMap.Initialize(); byte tempByte = 0; int x = 0, y = 0, i = 0, bitNum = 0; for (i = 0; i < 512; i++) { tempByte = LandData.Bitmap[i]; for (bitNum = 0; bitNum < 8; bitNum++) { bool bit = Convert.ToBoolean(Convert.ToByte(tempByte >> bitNum) & (byte) 1); tempConvertMap[x, y] = bit; x++; if (x > 63) { x = 0; y++; } } } return tempConvertMap; } #endregion #region Object Select and Object Owner Listing public void SendForceObjectSelect(int local_id, int request_type, List<UUID> returnIDs, IClientAPI remote_client) { if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions)) { List<uint> resultLocalIDs = new List<uint>(); try { lock (primsOverMe) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.LocalId > 0) { if (request_type == LandChannel.LAND_SELECT_OBJECTS_OWNER && obj.OwnerID == LandData.OwnerID) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == LandChannel.LAND_SELECT_OBJECTS_GROUP && obj.GroupID == LandData.GroupID && LandData.GroupID != UUID.Zero) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == LandChannel.LAND_SELECT_OBJECTS_OTHER && obj.OwnerID != remote_client.AgentId) { resultLocalIDs.Add(obj.LocalId); } else if (request_type == (int)ObjectReturnType.List && returnIDs.Contains(obj.OwnerID)) { resultLocalIDs.Add(obj.LocalId); } } } } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to force select the parcel objects. Arr."); } remote_client.SendForceClientSelectObjects(resultLocalIDs); } } /// <summary> /// Notify the parcel owner each avatar that owns prims situated on their land. This notification includes /// aggreagete details such as the number of prims. /// /// </summary> /// <param name="remote_client"> /// A <see cref="IClientAPI"/> /// </param> public void SendLandObjectOwners(IClientAPI remote_client) { if (m_scene.Permissions.CanEditParcelProperties(remote_client.AgentId, this, GroupPowers.LandOptions)) { Dictionary<UUID, int> primCount = new Dictionary<UUID, int>(); List<UUID> groups = new List<UUID>(); lock (primsOverMe) { // m_log.DebugFormat( // "[LAND OBJECT]: Request for SendLandObjectOwners() from {0} with {1} known prims on region", // remote_client.Name, primsOverMe.Count); try { foreach (SceneObjectGroup obj in primsOverMe) { try { if (!primCount.ContainsKey(obj.OwnerID)) { primCount.Add(obj.OwnerID, 0); } } catch (NullReferenceException) { m_log.Error("[LAND]: " + "Got Null Reference when searching land owners from the parcel panel"); } try { primCount[obj.OwnerID] += obj.PrimCount; } catch (KeyNotFoundException) { m_log.Error("[LAND]: Unable to match a prim with it's owner."); } if (obj.OwnerID == obj.GroupID && (!groups.Contains(obj.OwnerID))) groups.Add(obj.OwnerID); } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to Enumerate Land object arr."); } } remote_client.SendLandObjectOwners(LandData, groups, primCount); } } public Dictionary<UUID, int> GetLandObjectOwners() { Dictionary<UUID, int> ownersAndCount = new Dictionary<UUID, int>(); lock (primsOverMe) { try { foreach (SceneObjectGroup obj in primsOverMe) { if (!ownersAndCount.ContainsKey(obj.OwnerID)) { ownersAndCount.Add(obj.OwnerID, 0); } ownersAndCount[obj.OwnerID] += obj.PrimCount; } } catch (InvalidOperationException) { m_log.Error("[LAND]: Unable to enumerate land owners. arr."); } } return ownersAndCount; } #endregion #region Object Returning public void ReturnObject(SceneObjectGroup obj) { SceneObjectGroup[] objs = new SceneObjectGroup[1]; objs[0] = obj; m_scene.returnObjects(objs, obj.OwnerID); } public void ReturnLandObjects(uint type, UUID[] owners, UUID[] tasks, IClientAPI remote_client) { // m_log.DebugFormat( // "[LAND OBJECT]: Request to return objects in {0} from {1}", LandData.Name, remote_client.Name); Dictionary<UUID,List<SceneObjectGroup>> returns = new Dictionary<UUID,List<SceneObjectGroup>>(); lock (primsOverMe) { if (type == (uint)ObjectReturnType.Owner) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.OwnerID == m_landData.OwnerID) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.Group && m_landData.GroupID != UUID.Zero) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.GroupID == m_landData.GroupID) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.Other) { foreach (SceneObjectGroup obj in primsOverMe) { if (obj.OwnerID != m_landData.OwnerID && (obj.GroupID != m_landData.GroupID || m_landData.GroupID == UUID.Zero)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } else if (type == (uint)ObjectReturnType.List) { List<UUID> ownerlist = new List<UUID>(owners); foreach (SceneObjectGroup obj in primsOverMe) { if (ownerlist.Contains(obj.OwnerID)) { if (!returns.ContainsKey(obj.OwnerID)) returns[obj.OwnerID] = new List<SceneObjectGroup>(); returns[obj.OwnerID].Add(obj); } } } } foreach (List<SceneObjectGroup> ol in returns.Values) { if (m_scene.Permissions.CanReturnObjects(this, remote_client.AgentId, ol)) m_scene.returnObjects(ol.ToArray(), remote_client.AgentId); } } #endregion #region Object Adding/Removing from Parcel public void ResetOverMeRecord() { lock (primsOverMe) primsOverMe.Clear(); } public void AddPrimOverMe(SceneObjectGroup obj) { // m_log.DebugFormat("[LAND OBJECT]: Adding scene object {0} {1} over {2}", obj.Name, obj.LocalId, LandData.Name); lock (primsOverMe) primsOverMe.Add(obj); } public void RemovePrimFromOverMe(SceneObjectGroup obj) { // m_log.DebugFormat("[LAND OBJECT]: Removing scene object {0} {1} from over {2}", obj.Name, obj.LocalId, LandData.Name); lock (primsOverMe) primsOverMe.Remove(obj); } #endregion /// <summary> /// Set the media url for this land parcel /// </summary> /// <param name="url"></param> public void SetMediaUrl(string url) { LandData.MediaURL = url; SendLandUpdateToAvatarsOverMe(); } /// <summary> /// Set the music url for this land parcel /// </summary> /// <param name="url"></param> public void SetMusicUrl(string url) { LandData.MusicURL = url; SendLandUpdateToAvatarsOverMe(); } /// <summary> /// Get the music url for this land parcel /// </summary> /// <returns>The music url.</returns> public string GetMusicUrl() { return LandData.MusicURL; } #endregion private void ExpireAccessList() { List<LandAccessEntry> delete = new List<LandAccessEntry>(); foreach (LandAccessEntry entry in LandData.ParcelAccessList) { if (entry.Expires != 0 && entry.Expires < Util.UnixTimeSinceEpoch()) delete.Add(entry); } foreach (LandAccessEntry entry in delete) LandData.ParcelAccessList.Remove(entry); if (delete.Count > 0) m_scene.EventManager.TriggerLandObjectUpdated((uint)LandData.LocalID, this); } } }
//------------------------------------------------------------------------------ // <copyright file="Lift.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <disclaimer> // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. // </disclaimer> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Windows.Forms; using System.Drawing; using System.Media; using System.Threading; using Microsoft.Research.Joins; namespace LiftController { using LiftController; using Time = System.Int32; using Reservation = Buffer<bool>; using WaitTime = Pair<int /*Time*/, Buffer<bool> /* Reservation */>; using FloorNum = System.Int32; public enum Dir { Up, Down }; public delegate void Act(); public class Sprite : ActiveObject { private readonly Asynchronous.Channel ViewLock; protected readonly Synchronous.Channel<Act> UnderViewLock; public Synchronous.Channel<Pair<TimeSpan, Graphics>> Redraw; protected readonly Asynchronous.Channel EndTransition; protected readonly Synchronous.Channel WaitForEndTransition; public virtual void RedrawUnderViewLock(TimeSpan t, Graphics g) { } protected Sprite() { join.Initialize(out ViewLock); join.Initialize(out Redraw); join.Initialize(out UnderViewLock); join.Initialize(out WaitForEndTransition); join.Initialize(out EndTransition); join.When(UnderViewLock).And(ViewLock).Do(delegate(Act action) { action(); ViewLock(); }); join.When(Redraw).And(ViewLock).Do(delegate(Pair<TimeSpan, Graphics> p) { RedrawUnderViewLock(p.Fst, p.Snd); ViewLock(); }); join.When(WaitForEndTransition).And(EndTransition).Do(delegate { }); ViewLock(); } } public class Floor : Sprite { public Button mUpButton = new Button(); public Button mDownButton = new Button(); public Color mUpButtonBackColor = Color.Silver; public Color mDownButtonBackColor = Color.Silver; private List<Person> mPeople = new List<Person>(); List<Lift> mLifts; public int mNum; public Lift Reserve(Dir dir) { List<Pair<Lift, WaitTime>> wait = WaitTimes(dir); wait.Sort(delegate(Pair<Lift, WaitTime> v1, Pair<Lift, WaitTime> v2) { return v1.Snd.Fst.CompareTo(v2.Snd.Fst); }); wait[0].Snd.Snd.Put(true); for (int i = 1; i < wait.Count; i++) { wait[i].Snd.Snd.Put(false); } return wait[0].Fst; } private List<Pair<Lift, WaitTime>> WaitTimes(Dir dir) { List<Pair<Lift, WaitTime>> wait = new List<Pair<Lift, WaitTime>>(); foreach (Lift lift in mLifts) { Buffer<Pair<Time, Buffer<bool>>> b = new Buffer<Pair<Time, Buffer<bool>>>(); lift.HowLong(Helpers.pair(Helpers.pair(mNum, dir), b)); WaitTime waittime = b.Get(); wait.Add(Helpers.pair(lift, waittime)); } return wait; } public readonly Asynchronous.Channel Up; public readonly Asynchronous.Channel Down; public readonly Asynchronous.Channel<Lift> Arrived; public readonly Asynchronous.Channel<Pair<Person, Ack>> PersonArrived; public readonly Asynchronous.Channel<Person> PersonDeparted; private Lift mReservedUp = null; private Lift mReservedDown = null; public Floor(List<Lift> lifts, FloorNum floor) { this.mLifts = lifts; this.mNum = floor; join.Initialize(out Up); join.Initialize(out Down); join.Initialize(out Arrived); join.Initialize(out PersonArrived); join.Initialize(out PersonDeparted); join.When(ProcessMessage).And(Up).Do(delegate { mReservedUp = Reserve(Dir.Up); UnderViewLock(delegate { mUpButtonBackColor = Color.Yellow; }); }); join.When(ProcessMessage).And(Down).Do(delegate { mReservedDown = Reserve(Dir.Down); UnderViewLock(delegate { mDownButtonBackColor = Color.Yellow; }); }); join.When(ProcessMessage).And(Arrived).Do(delegate(Lift lift) { if (mReservedUp == lift) { mReservedUp = null; UnderViewLock(delegate { mUpButtonBackColor = Color.Silver; }); foreach (Person p in mPeople) p.Arrived(Helpers.pair(lift, Dir.Up)); }; if (mReservedDown == lift) { mReservedDown = null; UnderViewLock(delegate { mDownButtonBackColor = Color.Silver; }); foreach (Person p in mPeople) p.Arrived(Helpers.pair(lift, Dir.Down)); }; }); join.When(ProcessMessage).And(PersonArrived).Do(delegate(Pair<Person, Ack> p) { mPeople.Add(p.Fst); p.Snd.Send(); }); join.When(ProcessMessage).And(PersonDeparted).Do(delegate(Person person) { mPeople.Remove(person); }); Font Wingdings = new System.Drawing.Font("Wingdings", 10.0F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(2))); Button up = mUpButton; up.Location = new Point(Program.COLUMNWIDTH, (Program.NUMFLOORS - mNum) * Program.COLUMNHEIGHT); up.Font = Wingdings; up.Text = "\x00F1"; up.Size = new Size(Program.COLUMNWIDTH / 2, Program.COLUMNHEIGHT); up.ForeColor = Color.Green; up.BackColor = Color.Silver; up.Click += new EventHandler(delegate { this.Up(); }); Button down = mDownButton; down.Location = new Point(Program.COLUMNWIDTH + Program.COLUMNWIDTH / 2 , (Program.NUMFLOORS - mNum) * Program.COLUMNHEIGHT); down.Text = "\x00F2"; down.Font = Wingdings; down.Size = new Size(Program.COLUMNWIDTH / 2, Program.COLUMNHEIGHT); down.ForeColor = Color.Red; down.BackColor = Color.Silver; down.Click += new EventHandler(delegate { this.Down(); }); } public override void RedrawUnderViewLock(TimeSpan t, Graphics g) { if (mUpButton.BackColor != mUpButtonBackColor) mUpButton.BackColor = mUpButtonBackColor; if (mDownButton.BackColor != mDownButtonBackColor) mDownButton.BackColor = mDownButtonBackColor; } } public class Lift : Sprite { public Button[] mStopButtons = new Button[Program.NUMFLOORS]; public Color[] mStopButtonBackColors = new Color[Program.NUMFLOORS]; public List<Person> mPeople = new List<Person>(); public Asynchronous.Channel<Pair<Pair<FloorNum, Dir>, Buffer<WaitTime>>> HowLong; public Asynchronous.Channel<Pair<Floor, Buffer<Action>>> Arrived; public Asynchronous.Channel<FloorNum> Stop; public readonly Asynchronous.Channel<Pair<Person, Ack>> PersonArrived; public readonly Asynchronous.Channel<Person> PersonDeparted; public const Time StopTime = 5; private FloorNum Now = 0; public int mNum; private Lst<FloorNum> Stops = Lst<FloorNum>.nil; public Lift(int num) { mNum = num; join.Initialize(out HowLong); join.Initialize(out Arrived); join.Initialize(out Stop); join.Initialize(out PersonArrived); join.Initialize(out PersonDeparted); join.When(ProcessMessage).And(HowLong).Do(delegate(Pair<Pair<FloorNum, Dir>, Buffer<WaitTime>> p) { howLong(p.Fst.Fst, p.Fst.Snd, p.Snd); }); join.When(ProcessMessage).And(Arrived).Do(delegate(Pair<Floor, Buffer<Action>> p) { UnderViewLock(delegate { mStopButtonBackColors[p.Fst.mNum] = Color.Silver; }); arrived(p.Fst, p.Snd); }); join.When(ProcessMessage).And(Stop).Do(delegate(FloorNum floor) { UnderViewLock(delegate { mStopButtonBackColors[floor] = Color.Yellow; }); Stops = StopAt(floor, Now, Stops); }); join.When(ProcessMessage).And(PersonArrived).Do(delegate(Pair<Person, Ack> p) { mPeople.Add(p.Fst); p.Snd.Send(); }); join.When(ProcessMessage).And(PersonDeparted).Do(delegate(Person person) { mPeople.Remove(person); }); for (int i = 0; i < Program.NUMFLOORS; i++) { Button stop = new Button(); stop.Location = new Point((2 + (1 + 2 * mNum)) * Program.COLUMNWIDTH, (Program.NUMFLOORS - i) * Program.COLUMNHEIGHT); stop.Text = i.ToString(); stop.Size = new Size(Program.COLUMNWIDTH,Program.COLUMNHEIGHT); stop.BackColor = Color.Silver; int _i = i; stop.Click += new EventHandler(delegate { this.Stop(_i); }); mStopButtons[i] = stop; mStopButtonBackColors[i] = Color.Silver; } } private void arrived(Floor floor, Buffer<Action> b) { Now = floor.mNum; if (Stops.Null()) { b.Put(Action.Wait); return; } if (Stops.Hd() == Now) { Stops = Stops.Tl(); b.Put(Action.Stop); foreach (Person p in mPeople) { p.Stopped(floor); }; return; } if (Stops.Hd() > Now) { b.Put(Action.Up); return; } if (Stops.Hd() < Now) { b.Put(Action.Down); return; } } private void howLong(FloorNum floor, Dir dir, Buffer<WaitTime> b) { Time t = WaitTime(dir, floor, Now, Stops); Reservation reservation = new Reservation(); b.Put(new WaitTime(t, reservation)); if (reservation.Get()) { Stops = Insert(dir, floor, Now, Stops); } } private Lst<FloorNum> Insert(Dir dir, FloorNum floor, FloorNum now, Lst<FloorNum> stop) { return Insert(dir, floor, now, new Nil<FloorNum>(), stop); } private Lst<FloorNum> Insert(Dir dir, FloorNum floor, FloorNum now, Lst<FloorNum> before, Lst<FloorNum> stop) { if (stop.Null()) { return before.Cons(floor).Reverse(); } FloorNum next = stop.Hd(); Lst<FloorNum> after = stop.Tl(); if (floor == next) { return before.ReverseAppend(stop); } if (floor == now) { return before.ReverseAppend(stop); } if (dir == Dir.Up && now < floor && floor < next) { return before.ReverseAppend(stop.Cons(floor)); } if (dir == Dir.Down && next < floor && floor < now) { return before.ReverseAppend(stop.Cons(floor)); } return Insert(dir, floor, next, before.Cons(next), after); } private Time WaitTime(Dir dir, FloorNum floor, FloorNum now, Lst<FloorNum> stop) { return WaitTime(dir, floor, now, 0, stop); } private Time WaitTime(Dir dir, FloorNum floor, FloorNum now, Time t, Lst<FloorNum> stops) { if (stops.Null()) { return t + Math.Abs(floor - now); } FloorNum next = stops.Hd(); Lst<FloorNum> after = stops.Tl(); if (floor == next) { return t + Math.Abs(floor - now); } if (dir == Dir.Up && now <= floor && floor <= next) { return t + floor - now; } if (dir == Dir.Down && now >= floor && floor >= next) { return t + now - floor; } return WaitTime(dir, floor, next, t + Math.Abs(now - next) + StopTime, after); } private Lst<FloorNum> StopAt(FloorNum floor, FloorNum now, Lst<FloorNum> stops) { return StopAt(floor, Lst<FloorNum>.nil, stops.Cons(now)).Tl(); //NB: we take the tail to avoid restopping at now. } private Lst<FloorNum> StopAt(FloorNum floor, Lst<FloorNum> before, Lst<FloorNum> stops) { if (stops.Null()) { return before.Cons(floor).Reverse(); } if (floor == stops.Hd()) { return before.ReverseAppend(stops); } if (!stops.Tl().Null()) { FloorNum X = stops.Hd(); FloorNum Y = stops.Tl().Hd(); Lst<FloorNum> afterXY = stops.Tl().Tl(); if (X < floor && floor < Y) { return before.ReverseAppend(afterXY.Cons(Y).Cons(floor).Cons(X)); } if (Y < floor && floor < X) { return before.ReverseAppend(afterXY.Cons(Y).Cons(floor).Cons(X)); } } return StopAt(floor, before.Cons(stops.Hd()), stops.Tl()); } public override void RedrawUnderViewLock(TimeSpan t, Graphics g) { for (int i = 0; i < Program.NUMFLOORS; i++) { if (mStopButtons[i].BackColor != mStopButtonBackColors[i]) mStopButtons[i].BackColor = mStopButtonBackColors[i]; } } } public enum Action { Wait, Stop, Up, Down }; public enum CabinState { Waiting, Stopping, GoingUp, GoingDown }; public class Cabin : Sprite { CabinState mState; readonly int mNum; Lift mLift; List<Floor> mFloors; public Cabin(int num, Lift lift, List<Floor> floors) { this.mNum = num; this.mLift = lift; this.mFloors = floors; join.When(ProcessMessage).Do(CabinLoop); } FloorNum mFloor = 0; private void CabinLoop() { Buffer<Action> b = new Buffer<Action>(); while (true) { mLift.Arrived(Helpers.pair(mFloors[mFloor], b)); switch (b.Get()) { case Action.Wait: UnderViewLock(delegate { mState = CabinState.Waiting; }); break; case Action.Stop: mFloors[mFloor].Arrived(mLift); UnderViewLock(delegate { mState = CabinState.Stopping; }); WaitForEndTransition(); break; case Action.Up: UnderViewLock(delegate { nextY = (mFloor + 1) * Program.COLUMNHEIGHT; mState = CabinState.GoingUp; }); WaitForEndTransition(); mFloor++; break; case Action.Down: UnderViewLock(delegate { nextY = (mFloor - 1) * Program.COLUMNHEIGHT; mState = CabinState.GoingDown; }); WaitForEndTransition(); mFloor--; break; default: Debug.Assert(false); break; } } } int Y; int nextY; int timestopped; public override void RedrawUnderViewLock(TimeSpan timepassed, Graphics g) { int speed = Program.SPEED; int tm = (int)timepassed.TotalMilliseconds; int distance = speed * ((int)Math.Round((double)tm / Program.INTERVAL)); switch (mState) { case CabinState.Waiting: Y = nextY; g.FillRectangle(Brushes.Black, LiftRectangle()); break; case CabinState.GoingUp: Y += distance; if (Y > nextY) { Y = nextY; EndTransition(); }; g.FillRectangle(Brushes.Green, LiftRectangle()); break; case CabinState.GoingDown: Y -= distance; if (Y < nextY) { Y = nextY; EndTransition(); }; g.FillRectangle(Brushes.Red, LiftRectangle()); break; case CabinState.Stopping: Y = nextY; timestopped += distance; if (timestopped > 5 * Program.COLUMNHEIGHT) { timestopped = 0; EndTransition(); }; g.DrawRectangle(Pens.Black, LiftRectangle()); break; } } private Rectangle LiftRectangle() { return new Rectangle(new Point((2 + 2 * mNum) * Program.COLUMNWIDTH, ( Program.NUMFLOORS * Program.COLUMNHEIGHT) - Y), new Size(Program.COLUMNWIDTH, Program.COLUMNHEIGHT)); } } public enum PersonState { Waiting, Exiting, Entering, Travelling } public class Person : Sprite { private readonly int mNum; private Dir mDir; private FloorNum mNext; Brush mBrush; PersonState State; public Asynchronous.Channel<Floor> GotoFloor; public Asynchronous.Channel<Pair<Lift, Dir>> Arrived; public Asynchronous.Channel<Floor> Stopped; private Asynchronous.Channel<Floor> OnFloor; private Asynchronous.Channel<Lift> InLift; Random random; private void ChooseDir(Floor floor) { mDir = (floor.mNum == 0) ? Dir.Up : (floor.mNum == Program.NUMFLOORS - 1) ? Dir.Down : (Dir)random.Next(0, 2); if (mDir == Dir.Up) { floor.Up(); } if (mDir == Dir.Down) { floor.Down(); } } private void ChooseFloor(Floor floor, Lift lift) { if (mDir == Dir.Up) mNext = random.Next(floor.mNum + 1, Program.NUMFLOORS); if (mDir == Dir.Down) mNext = random.Next(0, floor.mNum); lift.Stop(mNext); } public Person(int num) { random = new Random(num); mNum = num; mBrush = mBrushes[num % mBrushes.Length]; join.Initialize(out GotoFloor); join.Initialize(out Stopped); join.Initialize(out Arrived); join.Initialize(out OnFloor); join.Initialize(out InLift); join.When(ProcessMessage).And(GotoFloor).Do(delegate(Floor floor) { UnderViewLock(delegate { Y = (Program.NUMFLOORS - floor.mNum) * Program.COLUMNHEIGHT; }); OnFloor(floor); Ack a = new Ack(); floor.PersonArrived(Helpers.pair(this, a)); a.Receive(); ChooseDir(floor); }); join.When(ProcessMessage).And(OnFloor).And(Arrived).Do(delegate(Floor floor, Pair<Lift, Dir> p) { Lift lift = p.Fst; Dir dir = p.Snd; if (dir == mDir) { floor.PersonDeparted(this); UnderViewLock(delegate { State = PersonState.Entering; X = 0; nextX = (2 + 2 * lift.mNum) * Program.COLUMNWIDTH; speed = (int)Math.Round((double)(Program.SPEED * 2 * nextX / (1.0 * Program.STOPTIME * Program.COLUMNHEIGHT))); }); WaitForEndTransition(); UnderViewLock(delegate { X = nextX; State = PersonState.Travelling; }); Ack ack = new Ack(); lift.PersonArrived(Helpers.pair(this, ack)); ack.Receive(); InLift(lift); ChooseFloor(floor, lift); } else OnFloor(floor); }); join.When(ProcessMessage).And(InLift).And(Arrived).Do(delegate(Lift lift, Pair<Lift, Dir> p) { InLift(lift); }); join.When(ProcessMessage).And(InLift).And(Stopped).Do(delegate(Lift lift, Floor stop) { if (stop.mNum == mNext) { lift.PersonDeparted(this); UnderViewLock(delegate { State = PersonState.Exiting; nextX = 0; Y = (Program.NUMFLOORS - stop.mNum) * Program.COLUMNHEIGHT; }); WaitForEndTransition(); UnderViewLock(delegate { X = 0; State = PersonState.Waiting; }); OnFloor(stop); Thread.Sleep(1000 * random.Next(1, 10)); Ack ack = new Ack(); stop.PersonArrived(Helpers.pair(this, ack)); ack.Receive(); ChooseDir(stop); } else InLift(lift); }); XOffSet = (mNum % 16) * 2; YOffSet = mNum / 16 * 2; X = 0; nextX = 0; } int speed; int X; int nextX; int Y; int XOffSet; int YOffSet; public override void RedrawUnderViewLock(TimeSpan timepassed, Graphics g) { int tm = (int)timepassed.TotalMilliseconds; int distance = speed * ((int)Math.Round((double)tm / Program.INTERVAL)); switch (State) { case PersonState.Waiting: g.FillEllipse(mBrush, PersonRectangle()); break; case PersonState.Travelling: // nothing to draw; break; case PersonState.Exiting: X -= distance; if (X < nextX) { X = nextX; EndTransition(); }; g.FillEllipse(mBrush, PersonRectangle()); break; case PersonState.Entering: X += distance; if (X > nextX) { X = nextX; EndTransition(); }; g.FillEllipse(mBrush, PersonRectangle()); break; } } public static Brush[] mBrushes = { Brushes.MediumAquamarine,Brushes.MediumBlue, Brushes.MediumOrchid, Brushes.MediumPurple, Brushes.MediumSeaGreen, Brushes.MediumSlateBlue, Brushes.MediumTurquoise, Brushes.MediumVioletRed }; private Rectangle PersonRectangle() { return new Rectangle(new Point(X + XOffSet, Y + YOffSet), new Size(Program.COLUMNWIDTH / 4,Program.COLUMNHEIGHT)); } } }
namespace valaya_vedan { partial class ValayaVedanv { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ValayaVedanv)); this.convert = new System.Windows.Forms.Button(); this.inputText = new System.Windows.Forms.RichTextBox(); this.outputText = new System.Windows.Forms.RichTextBox(); this.loadingMsg = new System.Windows.Forms.Label(); this.languageList = new System.Windows.Forms.ComboBox(); this.fontList = new System.Windows.Forms.ComboBox(); this.extractText = new System.Windows.Forms.Button(); this.openPDFFileDialog = new System.Windows.Forms.OpenFileDialog(); this.extarctingMsg = new System.Windows.Forms.Label(); this.saveOutput = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.extractTextFromFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.convertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveOutputTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveExtractedTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.changeLanguageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.changeFontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.changeDefaultToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openHelpFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.aboutUsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveTextFileDialog = new System.Windows.Forms.SaveFileDialog(); this.Input = new System.Windows.Forms.Label(); this.output = new System.Windows.Forms.Label(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // convert // this.convert.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F); this.convert.Location = new System.Drawing.Point(370, 36); this.convert.Margin = new System.Windows.Forms.Padding(2); this.convert.Name = "convert"; this.convert.Size = new System.Drawing.Size(175, 49); this.convert.TabIndex = 3; this.convert.Text = "Convert"; this.convert.UseVisualStyleBackColor = true; this.convert.Click += new System.EventHandler(this.convert_Click); // // inputText // this.inputText.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.inputText.Location = new System.Drawing.Point(7, 103); this.inputText.Margin = new System.Windows.Forms.Padding(2); this.inputText.Name = "inputText"; this.inputText.Size = new System.Drawing.Size(358, 323); this.inputText.TabIndex = 2; this.inputText.Text = ""; this.inputText.WordWrap = false; // // outputText // this.outputText.Location = new System.Drawing.Point(370, 103); this.outputText.Margin = new System.Windows.Forms.Padding(2); this.outputText.Name = "outputText"; this.outputText.Size = new System.Drawing.Size(358, 323); this.outputText.TabIndex = 4; this.outputText.Text = ""; this.outputText.WordWrap = false; // // loadingMsg // this.loadingMsg.AutoSize = true; this.loadingMsg.Location = new System.Drawing.Point(368, 430); this.loadingMsg.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.loadingMsg.Name = "loadingMsg"; this.loadingMsg.Size = new System.Drawing.Size(61, 13); this.loadingMsg.TabIndex = 16; this.loadingMsg.Text = "loadingMsg"; // // languageList // this.languageList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.languageList.FormattingEnabled = true; this.languageList.Location = new System.Drawing.Point(195, 56); this.languageList.Margin = new System.Windows.Forms.Padding(2); this.languageList.Name = "languageList"; this.languageList.Size = new System.Drawing.Size(80, 21); this.languageList.TabIndex = 7; this.languageList.SelectedIndexChanged += new System.EventHandler(this.languageList_SelectedIndexChanged); // // fontList // this.fontList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.fontList.FormattingEnabled = true; this.fontList.Location = new System.Drawing.Point(277, 56); this.fontList.Margin = new System.Windows.Forms.Padding(2); this.fontList.Name = "fontList"; this.fontList.Size = new System.Drawing.Size(80, 21); this.fontList.TabIndex = 6; this.fontList.SelectedIndexChanged += new System.EventHandler(this.comboBox2_SelectedIndexChanged_1); // // extractText // this.extractText.Location = new System.Drawing.Point(7, 36); this.extractText.Margin = new System.Windows.Forms.Padding(2); this.extractText.Name = "extractText"; this.extractText.Size = new System.Drawing.Size(182, 49); this.extractText.TabIndex = 1; this.extractText.Text = "Extract text from file"; this.extractText.UseVisualStyleBackColor = true; this.extractText.Click += new System.EventHandler(this.extract_Click); // // extarctingMsg // this.extarctingMsg.AutoSize = true; this.extarctingMsg.Location = new System.Drawing.Point(4, 430); this.extarctingMsg.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.extarctingMsg.Name = "extarctingMsg"; this.extarctingMsg.Size = new System.Drawing.Size(73, 13); this.extarctingMsg.TabIndex = 19; this.extarctingMsg.Text = "extarctingMsg"; // // saveOutput // this.saveOutput.Location = new System.Drawing.Point(553, 35); this.saveOutput.Margin = new System.Windows.Forms.Padding(2); this.saveOutput.Name = "saveOutput"; this.saveOutput.Size = new System.Drawing.Size(175, 49); this.saveOutput.TabIndex = 5; this.saveOutput.Text = "Save output text"; this.saveOutput.UseVisualStyleBackColor = true; this.saveOutput.Click += new System.EventHandler(this.button3_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(193, 40); this.label1.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(69, 13); this.label1.TabIndex = 21; this.label1.Text = "Language(s):"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(274, 40); this.label2.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(42, 13); this.label2.TabIndex = 22; this.label2.Text = "Font(s):"; // // menuStrip1 // this.menuStrip1.BackColor = System.Drawing.Color.Transparent; this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2); this.menuStrip1.Size = new System.Drawing.Size(736, 24); this.menuStrip1.TabIndex = 23; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.extractTextFromFileToolStripMenuItem, this.convertToolStripMenuItem, this.saveOutputTextToolStripMenuItem, this.saveExtractedTextToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // extractTextFromFileToolStripMenuItem // this.extractTextFromFileToolStripMenuItem.Name = "extractTextFromFileToolStripMenuItem"; this.extractTextFromFileToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D1))); this.extractTextFromFileToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.extractTextFromFileToolStripMenuItem.Text = "Extract text from file"; this.extractTextFromFileToolStripMenuItem.Click += new System.EventHandler(this.extract_Click); // // convertToolStripMenuItem // this.convertToolStripMenuItem.Name = "convertToolStripMenuItem"; this.convertToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D2))); this.convertToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.convertToolStripMenuItem.Text = "Convert"; this.convertToolStripMenuItem.Click += new System.EventHandler(this.convert_Click); // // saveOutputTextToolStripMenuItem // this.saveOutputTextToolStripMenuItem.Name = "saveOutputTextToolStripMenuItem"; this.saveOutputTextToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D3))); this.saveOutputTextToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.saveOutputTextToolStripMenuItem.Text = "Save output text"; this.saveOutputTextToolStripMenuItem.Click += new System.EventHandler(this.button3_Click); // // saveExtractedTextToolStripMenuItem // this.saveExtractedTextToolStripMenuItem.Name = "saveExtractedTextToolStripMenuItem"; this.saveExtractedTextToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D4))); this.saveExtractedTextToolStripMenuItem.Size = new System.Drawing.Size(219, 22); this.saveExtractedTextToolStripMenuItem.Text = "Save extracted text"; this.saveExtractedTextToolStripMenuItem.Click += new System.EventHandler(this.saveExtractedTextToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.changeLanguageToolStripMenuItem, this.changeFontToolStripMenuItem, this.changeDefaultToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20); this.editToolStripMenuItem.Text = "Edit"; // // changeLanguageToolStripMenuItem // this.changeLanguageToolStripMenuItem.Name = "changeLanguageToolStripMenuItem"; this.changeLanguageToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.L))); this.changeLanguageToolStripMenuItem.Size = new System.Drawing.Size(207, 22); this.changeLanguageToolStripMenuItem.Text = "Change language"; this.changeLanguageToolStripMenuItem.Click += new System.EventHandler(this.changeLanguageToolStripMenuItem_Click); // // changeFontToolStripMenuItem // this.changeFontToolStripMenuItem.Name = "changeFontToolStripMenuItem"; this.changeFontToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F))); this.changeFontToolStripMenuItem.Size = new System.Drawing.Size(207, 22); this.changeFontToolStripMenuItem.Text = "Change font"; this.changeFontToolStripMenuItem.Click += new System.EventHandler(this.changeFontToolStripMenuItem_Click); // // changeDefaultToolStripMenuItem // this.changeDefaultToolStripMenuItem.Name = "changeDefaultToolStripMenuItem"; this.changeDefaultToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.D))); this.changeDefaultToolStripMenuItem.Size = new System.Drawing.Size(207, 22); this.changeDefaultToolStripMenuItem.Text = "Change default"; this.changeDefaultToolStripMenuItem.Click += new System.EventHandler(this.changeDefaultToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openHelpFileToolStripMenuItem, this.helpToolStripMenuItem1, this.aboutUsToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "Help"; // // openHelpFileToolStripMenuItem // this.openHelpFileToolStripMenuItem.Name = "openHelpFileToolStripMenuItem"; this.openHelpFileToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F1))); this.openHelpFileToolStripMenuItem.Size = new System.Drawing.Size(198, 22); this.openHelpFileToolStripMenuItem.Text = "Open Help File"; this.openHelpFileToolStripMenuItem.Click += new System.EventHandler(this.openHelpFileToolStripMenuItem_Click); // // helpToolStripMenuItem1 // this.helpToolStripMenuItem1.Name = "helpToolStripMenuItem1"; this.helpToolStripMenuItem1.ShortcutKeys = System.Windows.Forms.Keys.F1; this.helpToolStripMenuItem1.Size = new System.Drawing.Size(198, 22); this.helpToolStripMenuItem1.Text = "Help"; this.helpToolStripMenuItem1.Click += new System.EventHandler(this.helpToolStripMenuItem1_Click); // // aboutUsToolStripMenuItem // this.aboutUsToolStripMenuItem.Name = "aboutUsToolStripMenuItem"; this.aboutUsToolStripMenuItem.Size = new System.Drawing.Size(198, 22); this.aboutUsToolStripMenuItem.Text = "About Us"; this.aboutUsToolStripMenuItem.Click += new System.EventHandler(this.aboutUsToolStripMenuItem_Click); // // Input // this.Input.AutoSize = true; this.Input.Location = new System.Drawing.Point(4, 87); this.Input.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.Input.Name = "Input"; this.Input.Size = new System.Drawing.Size(54, 13); this.Input.TabIndex = 24; this.Input.Text = "Input text:"; // // output // this.output.AutoSize = true; this.output.Location = new System.Drawing.Point(368, 87); this.output.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.output.Name = "output"; this.output.Size = new System.Drawing.Size(62, 13); this.output.TabIndex = 25; this.output.Text = "Output text:"; // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(585, 431); this.progressBar1.Margin = new System.Windows.Forms.Padding(2); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(142, 13); this.progressBar1.TabIndex = 26; // // ValayaVedanv // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(736, 451); this.Controls.Add(this.progressBar1); this.Controls.Add(this.output); this.Controls.Add(this.Input); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.saveOutput); this.Controls.Add(this.extarctingMsg); this.Controls.Add(this.extractText); this.Controls.Add(this.fontList); this.Controls.Add(this.languageList); this.Controls.Add(this.loadingMsg); this.Controls.Add(this.outputText); this.Controls.Add(this.inputText); this.Controls.Add(this.convert); this.Controls.Add(this.menuStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Margin = new System.Windows.Forms.Padding(2); this.MaximizeBox = false; this.Name = "ValayaVedanv"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Valaya Vedan - Text PDF reader"; this.Load += new System.EventHandler(this.Form1_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button convert; private System.Windows.Forms.RichTextBox inputText; private System.Windows.Forms.RichTextBox outputText; private System.Windows.Forms.Label loadingMsg; private System.Windows.Forms.ComboBox languageList; private System.Windows.Forms.ComboBox fontList; private System.Windows.Forms.Button extractText; private System.Windows.Forms.OpenFileDialog openPDFFileDialog; private System.Windows.Forms.Label extarctingMsg; private System.Windows.Forms.Button saveOutput; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem extractTextFromFileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem convertToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveOutputTextToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveExtractedTextToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem changeLanguageToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem changeFontToolStripMenuItem; private System.Windows.Forms.SaveFileDialog saveTextFileDialog; private System.Windows.Forms.Label Input; private System.Windows.Forms.Label output; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.ToolStripMenuItem changeDefaultToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openHelpFileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem1; private System.Windows.Forms.ToolStripMenuItem aboutUsToolStripMenuItem; } }
namespace AgentRalph.Options { partial class SimianOptionsPage { /// <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.label1 = new System.Windows.Forms.Label(); this.panelIncludes = new System.Windows.Forms.Panel(); this.IncludesTextBox = new System.Windows.Forms.TextBox(); this.panel4 = new System.Windows.Forms.Panel(); this.panel9 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.panelExcludes = new System.Windows.Forms.Panel(); this.ExcludesTextBox = new System.Windows.Forms.TextBox(); this.SimianPathTextBox = new System.Windows.Forms.TextBox(); this.panelPathToSimian = new System.Windows.Forms.Panel(); this.button1 = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.panel3 = new System.Windows.Forms.Panel(); this.panelFilters = new System.Windows.Forms.Panel(); this.panelOptionsContainer = new System.Windows.Forms.Panel(); this.panelIncludes.SuspendLayout(); this.panel4.SuspendLayout(); this.panel9.SuspendLayout(); this.panelExcludes.SuspendLayout(); this.panelPathToSimian.SuspendLayout(); this.panel3.SuspendLayout(); this.panelFilters.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Dock = System.Windows.Forms.DockStyle.Fill; this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(47, 13); this.label1.TabIndex = 5; this.label1.Text = "Includes"; // // panelIncludes // this.panelIncludes.Controls.Add(this.IncludesTextBox); this.panelIncludes.Controls.Add(this.panel4); this.panelIncludes.Dock = System.Windows.Forms.DockStyle.Left; this.panelIncludes.Location = new System.Drawing.Point(0, 0); this.panelIncludes.Name = "panelIncludes"; this.panelIncludes.Padding = new System.Windows.Forms.Padding(3); this.panelIncludes.Size = new System.Drawing.Size(256, 234); this.panelIncludes.TabIndex = 16; // // IncludesTextBox // this.IncludesTextBox.AcceptsReturn = true; this.IncludesTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.IncludesTextBox.Location = new System.Drawing.Point(3, 20); this.IncludesTextBox.Multiline = true; this.IncludesTextBox.Name = "IncludesTextBox"; this.IncludesTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.IncludesTextBox.Size = new System.Drawing.Size(250, 211); this.IncludesTextBox.TabIndex = 10; // // panel4 // this.panel4.Controls.Add(this.label1); this.panel4.Dock = System.Windows.Forms.DockStyle.Top; this.panel4.Location = new System.Drawing.Point(3, 3); this.panel4.Name = "panel4"; this.panel4.Size = new System.Drawing.Size(250, 17); this.panel4.TabIndex = 9; // // panel9 // this.panel9.Controls.Add(this.label2); this.panel9.Dock = System.Windows.Forms.DockStyle.Top; this.panel9.Location = new System.Drawing.Point(3, 3); this.panel9.Name = "panel9"; this.panel9.Size = new System.Drawing.Size(250, 17); this.panel9.TabIndex = 18; // // label2 // this.label2.AutoSize = true; this.label2.Dock = System.Windows.Forms.DockStyle.Fill; this.label2.Location = new System.Drawing.Point(0, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(50, 13); this.label2.TabIndex = 6; this.label2.Text = "Excludes"; // // panelExcludes // this.panelExcludes.Controls.Add(this.ExcludesTextBox); this.panelExcludes.Controls.Add(this.panel9); this.panelExcludes.Dock = System.Windows.Forms.DockStyle.Fill; this.panelExcludes.Location = new System.Drawing.Point(256, 0); this.panelExcludes.Name = "panelExcludes"; this.panelExcludes.Padding = new System.Windows.Forms.Padding(3); this.panelExcludes.Size = new System.Drawing.Size(256, 234); this.panelExcludes.TabIndex = 19; // // ExcludesTextBox // this.ExcludesTextBox.AcceptsReturn = true; this.ExcludesTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.ExcludesTextBox.Location = new System.Drawing.Point(3, 20); this.ExcludesTextBox.Multiline = true; this.ExcludesTextBox.Name = "ExcludesTextBox"; this.ExcludesTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.ExcludesTextBox.Size = new System.Drawing.Size(250, 211); this.ExcludesTextBox.TabIndex = 19; // // SimianPathTextBox // this.SimianPathTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.SimianPathTextBox.Location = new System.Drawing.Point(3, 3); this.SimianPathTextBox.Name = "SimianPathTextBox"; this.SimianPathTextBox.Size = new System.Drawing.Size(474, 20); this.SimianPathTextBox.TabIndex = 20; // // panelPathToSimian // this.panelPathToSimian.Controls.Add(this.button1); this.panelPathToSimian.Controls.Add(this.SimianPathTextBox); this.panelPathToSimian.Dock = System.Windows.Forms.DockStyle.Bottom; this.panelPathToSimian.Location = new System.Drawing.Point(0, 445); this.panelPathToSimian.Name = "panelPathToSimian"; this.panelPathToSimian.Padding = new System.Windows.Forms.Padding(3); this.panelPathToSimian.Size = new System.Drawing.Size(512, 26); this.panelPathToSimian.TabIndex = 21; // // button1 // this.button1.AutoSize = true; this.button1.Dock = System.Windows.Forms.DockStyle.Right; this.button1.Location = new System.Drawing.Point(483, 3); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(26, 20); this.button1.TabIndex = 22; this.button1.Text = "..."; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // label3 // this.label3.AutoSize = true; this.label3.Dock = System.Windows.Forms.DockStyle.Fill; this.label3.Location = new System.Drawing.Point(0, 3); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(130, 13); this.label3.TabIndex = 21; this.label3.Text = "Path to Simian executable"; // // panel3 // this.panel3.Controls.Add(this.label3); this.panel3.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel3.Location = new System.Drawing.Point(0, 429); this.panel3.Name = "panel3"; this.panel3.Padding = new System.Windows.Forms.Padding(0, 3, 0, 0); this.panel3.Size = new System.Drawing.Size(512, 16); this.panel3.TabIndex = 22; // // panelFilters // this.panelFilters.Controls.Add(this.panelExcludes); this.panelFilters.Controls.Add(this.panelIncludes); this.panelFilters.Dock = System.Windows.Forms.DockStyle.Top; this.panelFilters.Location = new System.Drawing.Point(0, 0); this.panelFilters.Name = "panelFilters"; this.panelFilters.Size = new System.Drawing.Size(512, 234); this.panelFilters.TabIndex = 23; // // panelOptionsContainer // this.panelOptionsContainer.AutoScroll = true; this.panelOptionsContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.panelOptionsContainer.Location = new System.Drawing.Point(0, 234); this.panelOptionsContainer.Name = "panelOptionsContainer"; this.panelOptionsContainer.Size = new System.Drawing.Size(512, 195); this.panelOptionsContainer.TabIndex = 24; // // SimianOptionsPage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.panelOptionsContainer); this.Controls.Add(this.panelFilters); this.Controls.Add(this.panel3); this.Controls.Add(this.panelPathToSimian); this.Name = "SimianOptionsPage"; this.Size = new System.Drawing.Size(512, 471); this.panelIncludes.ResumeLayout(false); this.panelIncludes.PerformLayout(); this.panel4.ResumeLayout(false); this.panel4.PerformLayout(); this.panel9.ResumeLayout(false); this.panel9.PerformLayout(); this.panelExcludes.ResumeLayout(false); this.panelExcludes.PerformLayout(); this.panelPathToSimian.ResumeLayout(false); this.panelPathToSimian.PerformLayout(); this.panel3.ResumeLayout(false); this.panel3.PerformLayout(); this.panelFilters.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel panelIncludes; private System.Windows.Forms.Panel panel4; private System.Windows.Forms.TextBox IncludesTextBox; private System.Windows.Forms.Panel panel9; private System.Windows.Forms.Label label2; private System.Windows.Forms.Panel panelExcludes; private System.Windows.Forms.TextBox ExcludesTextBox; private System.Windows.Forms.TextBox SimianPathTextBox; private System.Windows.Forms.Panel panelPathToSimian; private System.Windows.Forms.Label label3; private System.Windows.Forms.Panel panel3; private System.Windows.Forms.Button button1; private System.Windows.Forms.Panel panelFilters; private System.Windows.Forms.Panel panelOptionsContainer; } }
// 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.Threading.Tasks; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Internal methods internal async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBase64"); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBinHex"); } if (!await InitAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64"); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex"); } if (!await InitOnElementAsync().ConfigureAwait(false)) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return await ReadElementContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); } internal async Task FinishAsync() { if (_state != State.None) { while (await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) ; if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); } } Reset(); } // Private methods private async Task<bool> InitAsync() { // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private async Task<bool> InitOnElementAsync() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element await _reader.ReadAsync().ConfigureAwait(false); if (isEmpty) { return false; } // make sure we are on a content node if (!await MoveToNextContentNodeAsync(false).ConfigureAwait(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element await _reader.ReadAsync().ConfigureAwait(false); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private async Task<int> ReadContentAsBinaryAsync(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ;) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ;) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = await _reader.GetValueAsync().ConfigureAwait(false); int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!await MoveToNextContentNodeAsync(true).ConfigureAwait(false)) { _isEnd = true; return _decoder.DecodedCount; } } } private async Task<int> ReadElementContentAsBinaryAsync(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = await ReadContentAsBinaryAsync(buffer, index, count).ConfigureAwait(false); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement await _reader.ReadAsync().ConfigureAwait(false); _state = State.None; return 0; } private async Task<bool> MoveToNextContentNodeAsync(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (await _reader.ReadAsync().ConfigureAwait(false)); return false; } } }
using System; using System.Linq; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Cecil.Metadata; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class TypeTests : BaseTestFixture { [Test] public void TypeLayout () { TestCSharp ("Layouts.cs", module => { var foo = module.GetType ("Foo"); Assert.IsNotNull (foo); Assert.IsTrue (foo.IsValueType); Assert.IsTrue (foo.HasLayoutInfo); Assert.AreEqual (16, foo.ClassSize); var babar = module.GetType ("Babar"); Assert.IsNotNull (babar); Assert.IsFalse (babar.IsValueType); Assert.IsFalse (babar.HasLayoutInfo); }); } [Test] public void EmptyStructLayout () { TestModule ("hello.exe", module => { var foo = new TypeDefinition ("", "Foo", TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit | TypeAttributes.SequentialLayout, module.ImportReference (typeof (ValueType))) ; module.Types.Add (foo) ; }) ; } [Test] public void SimpleInterfaces () { TestIL ("types.il", module => { var ibaz = module.GetType ("IBaz"); Assert.IsNotNull (ibaz); Assert.IsTrue (ibaz.HasInterfaces); var interfaces = ibaz.Interfaces; Assert.AreEqual (2, interfaces.Count); // Mono's ilasm and .NET's are ordering interfaces differently Assert.IsNotNull (interfaces.Single (i => i.InterfaceType.FullName == "IBar")); Assert.IsNotNull (interfaces.Single (i => i.InterfaceType.FullName == "IFoo")); }); } [Test] public void GenericTypeDefinition () { TestCSharp ("Generics.cs", module => { var foo = module.GetType ("Foo`2"); Assert.IsNotNull (foo); Assert.IsTrue (foo.HasGenericParameters); Assert.AreEqual (2, foo.GenericParameters.Count); var tbar = foo.GenericParameters [0]; Assert.AreEqual ("TBar", tbar.Name); Assert.AreEqual (foo, tbar.Owner); var tbaz = foo.GenericParameters [1]; Assert.AreEqual ("TBaz", tbaz.Name); Assert.AreEqual (foo, tbaz.Owner); }); } [Test] public void ConstrainedGenericType () { TestCSharp ("Generics.cs", module => { var bongo_t = module.GetType ("Bongo`1"); Assert.IsNotNull (bongo_t); var t = bongo_t.GenericParameters [0]; Assert.IsNotNull (t); Assert.AreEqual ("T", t.Name); Assert.IsTrue (t.HasConstraints); Assert.AreEqual (2, t.Constraints.Count); Assert.AreEqual ("Zap", t.Constraints [0].FullName); Assert.AreEqual ("IZoom", t.Constraints [1].FullName); }); } [Test] public void GenericBaseType () { TestCSharp ("Generics.cs", module => { var child = module.GetType ("Child`1"); var child_t = child.GenericParameters [0]; Assert.IsNotNull (child_t); var instance = child.BaseType as GenericInstanceType; Assert.IsNotNull (instance); Assert.AreNotEqual (0, instance.MetadataToken.RID); Assert.AreEqual (child_t, instance.GenericArguments [0]); }); } [Test] public void GenericConstraintOnGenericParameter () { TestCSharp ("Generics.cs", module => { var duel = module.GetType ("Duel`3"); Assert.AreEqual (3, duel.GenericParameters.Count); var t1 = duel.GenericParameters [0]; var t2 = duel.GenericParameters [1]; var t3 = duel.GenericParameters [2]; Assert.AreEqual (t1, t2.Constraints [0]); Assert.AreEqual (t2, t3.Constraints [0]); }); } [Test] public void GenericForwardBaseType () { TestCSharp ("Generics.cs", module => { var tamchild = module.GetType ("TamChild"); Assert.IsNotNull (tamchild); Assert.IsNotNull (tamchild.BaseType); var generic_instance = tamchild.BaseType as GenericInstanceType; Assert.IsNotNull (generic_instance); Assert.AreEqual (1, generic_instance.GenericArguments.Count); Assert.AreEqual (module.GetType ("Tamtam"), generic_instance.GenericArguments [0]); }); } [Test] public void TypeExtentingGenericOfSelf () { TestCSharp ("Generics.cs", module => { var rec_child = module.GetType ("RecChild"); Assert.IsNotNull (rec_child); Assert.IsNotNull (rec_child.BaseType); var generic_instance = rec_child.BaseType as GenericInstanceType; Assert.IsNotNull (generic_instance); Assert.AreEqual (1, generic_instance.GenericArguments.Count); Assert.AreEqual (rec_child, generic_instance.GenericArguments [0]); }); } [Test] public void TypeReferenceValueType () { TestCSharp ("Methods.cs", module => { var baz = module.GetType ("Baz"); var method = baz.GetMethod ("PrintAnswer"); var box = method.Body.Instructions.Where (i => i.OpCode == OpCodes.Box).First (); var int32 = (TypeReference) box.Operand; Assert.IsTrue (int32.IsValueType); }); } [Test] public void GenericInterfaceReference () { TestModule ("gifaceref.exe", module => { var type = module.GetType ("Program"); var iface = type.Interfaces [0]; var instance = (GenericInstanceType) iface.InterfaceType; var owner = instance.ElementType; Assert.AreEqual (1, instance.GenericArguments.Count); Assert.AreEqual (1, owner.GenericParameters.Count); }); } [Test] public void UnboundGenericParameter () { TestModule ("cscgpbug.dll", module => { var type = module.GetType ("ListViewModel"); var method = type.GetMethod ("<>n__FabricatedMethod1"); var parameter = method.ReturnType as GenericParameter; Assert.IsNotNull (parameter); Assert.AreEqual (0, parameter.Position); Assert.IsNull (parameter.Owner); }, verify: false); } [Test] public void GenericMultidimensionalArray () { TestCSharp ("Generics.cs", module => { var type = module.GetType ("LaMatrix"); var method = type.GetMethod ("At"); var call = method.Body.Instructions.Where (i => i.Operand is MethodReference).First (); var get = (MethodReference) call.Operand; Assert.IsNotNull (get); Assert.AreEqual (0, get.GenericParameters.Count); Assert.AreEqual (MethodCallingConvention.Default, get.CallingConvention); Assert.AreEqual (method.GenericParameters [0], get.ReturnType); }); } [Test] public void CorlibPrimitive () { var module = typeof (TypeTests).ToDefinition ().Module; var int32 = module.TypeSystem.Int32; Assert.IsTrue (int32.IsPrimitive); Assert.AreEqual (MetadataType.Int32, int32.MetadataType); var int32_def = int32.Resolve (); Assert.IsTrue (int32_def.IsPrimitive); Assert.AreEqual (MetadataType.Int32, int32_def.MetadataType); } [Test] public void ExplicitThis () { TestIL ("explicitthis.il", module => { var type = module.GetType ("MakeDecision"); var method = type.GetMethod ("Decide"); var fptr = method.ReturnType as FunctionPointerType; Assert.IsNotNull (fptr); Assert.IsTrue (fptr.HasThis); Assert.IsTrue (fptr.ExplicitThis); Assert.AreEqual (0, fptr.Parameters [0].Sequence); Assert.AreEqual (1, fptr.Parameters [1].Sequence); }, verify: false); } [Test] public void DeferredCorlibTypeDef () { using (var module = ModuleDefinition.ReadModule (typeof (object).Assembly.Location, new ReaderParameters (ReadingMode.Deferred))) { var object_type = module.TypeSystem.Object; Assert.IsInstanceOf<TypeDefinition> (object_type); } } [Test] public void CorlibTypesMetadataType () { using (var module = ModuleDefinition.ReadModule (typeof (object).Assembly.Location)) { var type = module.GetType ("System.String"); Assert.IsNotNull (type); Assert.IsNotNull (type.BaseType); Assert.AreEqual ("System.Object", type.BaseType.FullName); Assert.IsInstanceOf<TypeDefinition> (type.BaseType); Assert.AreEqual (MetadataType.String, type.MetadataType); Assert.AreEqual (MetadataType.Object, type.BaseType.MetadataType); } } } }
// 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.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Net.Security; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class OpenSsl { private static readonly Ssl.SslCtxSetVerifyCallback s_verifyClientCertificate = VerifyClientCertificate; private static readonly Ssl.SslCtxSetAlpnCallback s_alpnServerCallback = AlpnServerSelectCallback; #region internal methods internal static SafeChannelBindingHandle QueryChannelBinding(SafeSslHandle context, ChannelBindingKind bindingType) { Debug.Assert( bindingType != ChannelBindingKind.Endpoint, "Endpoint binding should be handled by EndpointChannelBindingToken"); SafeChannelBindingHandle bindingHandle; switch (bindingType) { case ChannelBindingKind.Unique: bindingHandle = new SafeChannelBindingHandle(bindingType); QueryUniqueChannelBinding(context, bindingHandle); break; default: // Keeping parity with windows, we should return null in this case. bindingHandle = null; break; } return bindingHandle; } internal static SafeSslHandle AllocateSslContext(SslProtocols protocols, SafeX509Handle certHandle, SafeEvpPKeyHandle certKeyHandle, EncryptionPolicy policy, SslAuthenticationOptions sslAuthenticationOptions) { SafeSslHandle context = null; // Always use SSLv23_method, regardless of protocols. It supports negotiating to the highest // mutually supported version and can thus handle any of the set protocols, and we then use // SetProtocolOptions to ensure we only allow the ones requested. using (SafeSslContextHandle innerContext = Ssl.SslCtxCreate(Ssl.SslMethods.SSLv23_method)) { if (innerContext.IsInvalid) { throw CreateSslException(SR.net_allocate_ssl_context_failed); } // Configure allowed protocols. It's ok to use DangerousGetHandle here without AddRef/Release as we just // create the handle, it's rooted by the using, no one else has a reference to it, etc. Ssl.SetProtocolOptions(innerContext.DangerousGetHandle(), protocols); // The logic in SafeSslHandle.Disconnect is simple because we are doing a quiet // shutdown (we aren't negotiating for session close to enable later session // restoration). // // If you find yourself wanting to remove this line to enable bidirectional // close-notify, you'll probably need to rewrite SafeSslHandle.Disconnect(). // https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html Ssl.SslCtxSetQuietShutdown(innerContext); if (!Ssl.SetEncryptionPolicy(innerContext, policy)) { throw new PlatformNotSupportedException(SR.Format(SR.net_ssl_encryptionpolicy_notsupported, policy)); } bool hasCertificateAndKey = certHandle != null && !certHandle.IsInvalid && certKeyHandle != null && !certKeyHandle.IsInvalid; if (hasCertificateAndKey) { SetSslCertificate(innerContext, certHandle, certKeyHandle); } if (sslAuthenticationOptions.IsServer && sslAuthenticationOptions.RemoteCertRequired) { Ssl.SslCtxSetVerify(innerContext, s_verifyClientCertificate); //update the client CA list UpdateCAListFromRootStore(innerContext); } if (sslAuthenticationOptions.ApplicationProtocols != null) { if (sslAuthenticationOptions.IsServer) { byte[] protos = Interop.Ssl.ConvertAlpnProtocolListToByteArray(sslAuthenticationOptions.ApplicationProtocols); sslAuthenticationOptions.AlpnProtocolsHandle = GCHandle.Alloc(protos); Interop.Ssl.SslCtxSetAlpnSelectCb(innerContext, s_alpnServerCallback, GCHandle.ToIntPtr(sslAuthenticationOptions.AlpnProtocolsHandle)); } else { if (Interop.Ssl.SslCtxSetAlpnProtos(innerContext, sslAuthenticationOptions.ApplicationProtocols) != 0) { throw CreateSslException(SR.net_alpn_config_failed); } } } context = SafeSslHandle.Create(innerContext, sslAuthenticationOptions.IsServer); Debug.Assert(context != null, "Expected non-null return value from SafeSslHandle.Create"); if (context.IsInvalid) { context.Dispose(); throw CreateSslException(SR.net_allocate_ssl_context_failed); } if (hasCertificateAndKey) { bool hasCertReference = false; try { certHandle.DangerousAddRef(ref hasCertReference); using (X509Certificate2 cert = new X509Certificate2(certHandle.DangerousGetHandle())) { using (X509Chain chain = TLSCertificateExtensions.BuildNewChain(cert, includeClientApplicationPolicy: false)) { if (chain != null && !Ssl.AddExtraChainCertificates(context, chain)) throw CreateSslException(SR.net_ssl_use_cert_failed); } } } finally { if (hasCertReference) certHandle.DangerousRelease(); } } } return context; } internal static bool DoSslHandshake(SafeSslHandle context, byte[] recvBuf, int recvOffset, int recvCount, out byte[] sendBuf, out int sendCount) { sendBuf = null; sendCount = 0; if ((recvBuf != null) && (recvCount > 0)) { BioWrite(context.InputBio, recvBuf, recvOffset, recvCount); } int retVal = Ssl.SslDoHandshake(context); if (retVal != 1) { Exception innerError; Ssl.SslErrorCode error = GetSslError(context, retVal, out innerError); if ((retVal != -1) || (error != Ssl.SslErrorCode.SSL_ERROR_WANT_READ)) { throw new SslException(SR.Format(SR.net_ssl_handshake_failed_error, error), innerError); } } sendCount = Crypto.BioCtrlPending(context.OutputBio); if (sendCount > 0) { sendBuf = new byte[sendCount]; try { sendCount = BioRead(context.OutputBio, sendBuf, sendCount); } finally { if (sendCount <= 0) { sendBuf = null; sendCount = 0; } } } bool stateOk = Ssl.IsSslStateOK(context); if (stateOk) { context.MarkHandshakeCompleted(); } return stateOk; } internal static int Encrypt(SafeSslHandle context, ReadOnlyMemory<byte> input, ref byte[] output, out Ssl.SslErrorCode errorCode) { errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal; unsafe { using (MemoryHandle handle = input.Retain(pin: true)) { retVal = Ssl.SslWrite(context, (byte*)handle.Pointer, input.Length); } } if (retVal != input.Length) { errorCode = GetSslError(context, retVal, out Exception innerError); retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: break; default: throw new SslException(SR.Format(SR.net_ssl_encrypt_failed, errorCode), innerError); } } else { int capacityNeeded = Crypto.BioCtrlPending(context.OutputBio); if (output == null || output.Length < capacityNeeded) { output = new byte[capacityNeeded]; } retVal = BioRead(context.OutputBio, output, capacityNeeded); } return retVal; } internal static int Decrypt(SafeSslHandle context, byte[] outBuffer, int offset, int count, out Ssl.SslErrorCode errorCode) { errorCode = Ssl.SslErrorCode.SSL_ERROR_NONE; int retVal = BioWrite(context.InputBio, outBuffer, offset, count); if (retVal == count) { unsafe { fixed (byte* fixedBuffer = outBuffer) { retVal = Ssl.SslRead(context, fixedBuffer + offset, outBuffer.Length); } } if (retVal > 0) { count = retVal; } } if (retVal != count) { Exception innerError; errorCode = GetSslError(context, retVal, out innerError); retVal = 0; switch (errorCode) { // indicate end-of-file case Ssl.SslErrorCode.SSL_ERROR_ZERO_RETURN: break; case Ssl.SslErrorCode.SSL_ERROR_WANT_READ: // update error code to renegotiate if renegotiate is pending, otherwise make it SSL_ERROR_WANT_READ errorCode = Ssl.IsSslRenegotiatePending(context) ? Ssl.SslErrorCode.SSL_ERROR_RENEGOTIATE : Ssl.SslErrorCode.SSL_ERROR_WANT_READ; break; default: throw new SslException(SR.Format(SR.net_ssl_decrypt_failed, errorCode), innerError); } } return retVal; } internal static SafeX509Handle GetPeerCertificate(SafeSslHandle context) { return Ssl.SslGetPeerCertificate(context); } internal static SafeSharedX509StackHandle GetPeerCertificateChain(SafeSslHandle context) { return Ssl.SslGetPeerCertChain(context); } #endregion #region private methods private static void QueryUniqueChannelBinding(SafeSslHandle context, SafeChannelBindingHandle bindingHandle) { bool sessionReused = Ssl.SslSessionReused(context); int certHashLength = context.IsServer ^ sessionReused ? Ssl.SslGetPeerFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length) : Ssl.SslGetFinished(context, bindingHandle.CertHashPtr, bindingHandle.Length); if (0 == certHashLength) { throw CreateSslException(SR.net_ssl_get_channel_binding_token_failed); } bindingHandle.SetCertHashLength(certHashLength); } private static int VerifyClientCertificate(int preverify_ok, IntPtr x509_ctx_ptr) { // Full validation is handled after the handshake in VerifyCertificateProperties and the // user callback. It's also up to those handlers to decide if a null certificate // is appropriate. So just return success to tell OpenSSL that the cert is acceptable, // we'll process it after the handshake finishes. const int OpenSslSuccess = 1; return OpenSslSuccess; } private static unsafe int AlpnServerSelectCallback(IntPtr ssl, out IntPtr outp, out byte outlen, IntPtr inp, uint inlen, IntPtr arg) { GCHandle protocols = GCHandle.FromIntPtr(arg); byte[] server = (byte[])protocols.Target; fixed (byte* sp = server) { return Interop.Ssl.SslSelectNextProto(out outp, out outlen, (IntPtr)sp, (uint)server.Length, inp, inlen) == Interop.Ssl.OPENSSL_NPN_NEGOTIATED ? Interop.Ssl.SSL_TLSEXT_ERR_OK : Interop.Ssl.SSL_TLSEXT_ERR_NOACK; } } private static void UpdateCAListFromRootStore(SafeSslContextHandle context) { using (SafeX509NameStackHandle nameStack = Crypto.NewX509NameStack()) { //maintaining the HashSet of Certificate's issuer name to keep track of duplicates HashSet<string> issuerNameHashSet = new HashSet<string>(); //Enumerate Certificates from LocalMachine and CurrentUser root store AddX509Names(nameStack, StoreLocation.LocalMachine, issuerNameHashSet); AddX509Names(nameStack, StoreLocation.CurrentUser, issuerNameHashSet); Ssl.SslCtxSetClientCAList(context, nameStack); // The handle ownership has been transferred into the CTX. nameStack.SetHandleAsInvalid(); } } private static void AddX509Names(SafeX509NameStackHandle nameStack, StoreLocation storeLocation, HashSet<string> issuerNameHashSet) { using (var store = new X509Store(StoreName.Root, storeLocation)) { store.Open(OpenFlags.ReadOnly); foreach (var certificate in store.Certificates) { //Check if issuer name is already present //Avoiding duplicate names if (!issuerNameHashSet.Add(certificate.Issuer)) { continue; } using (SafeX509Handle certHandle = Crypto.X509UpRef(certificate.Handle)) { using (SafeX509NameHandle nameHandle = Crypto.DuplicateX509Name(Crypto.X509GetIssuerName(certHandle))) { if (Crypto.PushX509NameStackField(nameStack, nameHandle)) { // The handle ownership has been transferred into the STACK_OF(X509_NAME). nameHandle.SetHandleAsInvalid(); } else { throw new CryptographicException(SR.net_ssl_x509Name_push_failed_error); } } } } } } private static int BioRead(SafeBioHandle bio, byte[] buffer, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= count); int bytes = Crypto.BioRead(bio, buffer, count); if (bytes != count) { throw CreateSslException(SR.net_ssl_read_bio_failed_error); } return bytes; } private static int BioWrite(SafeBioHandle bio, byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); Debug.Assert(buffer.Length >= offset + count); int bytes; unsafe { fixed (byte* bufPtr = buffer) { bytes = Ssl.BioWrite(bio, bufPtr + offset, count); } } if (bytes != count) { throw CreateSslException(SR.net_ssl_write_bio_failed_error); } return bytes; } private static Ssl.SslErrorCode GetSslError(SafeSslHandle context, int result, out Exception innerError) { ErrorInfo lastErrno = Sys.GetLastErrorInfo(); // cache it before we make more P/Invoke calls, just in case we need it Ssl.SslErrorCode retVal = Ssl.SslGetError(context, result); switch (retVal) { case Ssl.SslErrorCode.SSL_ERROR_SYSCALL: // Some I/O error occurred innerError = Crypto.ErrPeekError() != 0 ? Crypto.CreateOpenSslCryptographicException() : // crypto error queue not empty result == 0 ? new EndOfStreamException() : // end of file that violates protocol result == -1 && lastErrno.Error != Error.SUCCESS ? new IOException(lastErrno.GetErrorMessage(), lastErrno.RawErrno) : // underlying I/O error null; // no additional info available break; case Ssl.SslErrorCode.SSL_ERROR_SSL: // OpenSSL failure occurred. The error queue contains more details. innerError = Interop.Crypto.CreateOpenSslCryptographicException(); break; default: // No additional info available. innerError = null; break; } return retVal; } private static void SetSslCertificate(SafeSslContextHandle contextPtr, SafeX509Handle certPtr, SafeEvpPKeyHandle keyPtr) { Debug.Assert(certPtr != null && !certPtr.IsInvalid, "certPtr != null && !certPtr.IsInvalid"); Debug.Assert(keyPtr != null && !keyPtr.IsInvalid, "keyPtr != null && !keyPtr.IsInvalid"); int retVal = Ssl.SslCtxUseCertificate(contextPtr, certPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_cert_failed); } retVal = Ssl.SslCtxUsePrivateKey(contextPtr, keyPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_use_private_key_failed); } //check private key retVal = Ssl.SslCtxCheckPrivateKey(contextPtr); if (1 != retVal) { throw CreateSslException(SR.net_ssl_check_private_key_failed); } } internal static SslException CreateSslException(string message) { ulong errorVal = Crypto.ErrGetError(); string msg = SR.Format(message, Marshal.PtrToStringAnsi(Crypto.ErrReasonErrorString(errorVal))); return new SslException(msg, (int)errorVal); } #endregion #region Internal class internal sealed class SslException : Exception { public SslException(string inputMessage) : base(inputMessage) { } public SslException(string inputMessage, Exception ex) : base(inputMessage, ex) { } public SslException(string inputMessage, int error) : this(inputMessage) { HResult = error; } public SslException(int error) : this(SR.Format(SR.net_generic_operation_failed, error)) { HResult = error; } } #endregion } }
// Copyright (c) .NET Foundation. 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.IO.Pipelines; using System.Threading; using System.Threading.Tasks; using HtcSharp.HttpModule.Connections.Abstractions.Exceptions; using HtcSharp.HttpModule.Http; namespace HtcSharp.HttpModule.Core.Internal.Http { // SourceTools-Start // Remote-File C:\ASP\src\Servers\Kestrel\Core\src\Internal\Http\Http1ContentLengthMessageBody.cs // Start-At-Remote-Line 11 // SourceTools-End internal sealed class Http1ContentLengthMessageBody : Http1MessageBody { private ReadResult _readResult; private readonly long _contentLength; private long _inputLength; private bool _readCompleted; private bool _isReading; private int _userCanceled; private bool _finalAdvanceCalled; public Http1ContentLengthMessageBody(bool keepAlive, long contentLength, Http1Connection context) : base(context) { RequestKeepAlive = keepAlive; _contentLength = contentLength; _inputLength = _contentLength; } public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default) { ThrowIfCompleted(); return ReadAsyncInternal(cancellationToken); } public override async ValueTask<ReadResult> ReadAsyncInternal(CancellationToken cancellationToken = default) { if (_isReading) { throw new InvalidOperationException("Reading is already in progress."); } if (_readCompleted) { _isReading = true; return new ReadResult(_readResult.Buffer, Interlocked.Exchange(ref _userCanceled, 0) == 1, _readResult.IsCompleted); } TryStart(); // The while(true) loop is required because the Http1 connection calls CancelPendingRead to unblock // the call to StartTimingReadAsync to check if the request timed out. // However, if the user called CancelPendingRead, we want that to return a canceled ReadResult // We internally track an int for that. while (true) { // The issue is that TryRead can get a canceled read result // which is unknown to StartTimingReadAsync. if (_context.RequestTimedOut) { BadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } try { var readAwaitable = _context.Input.ReadAsync(cancellationToken); _isReading = true; _readResult = await StartTimingReadAsync(readAwaitable, cancellationToken); } catch (ConnectionAbortedException ex) { _isReading = false; throw new TaskCanceledException("The request was aborted", ex); } void ResetReadingState() { _isReading = false; // Reset the timing read here for the next call to read. StopTimingRead(0); _context.Input.AdvanceTo(_readResult.Buffer.Start); } if (_context.RequestTimedOut) { ResetReadingState(); BadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTimeout); } if (_readResult.IsCompleted) { ResetReadingState(); ThrowUnexpectedEndOfRequestContent(); } // Ignore the canceled readResult if it wasn't canceled by the user. if (!_readResult.IsCanceled || Interlocked.Exchange(ref _userCanceled, 0) == 1) { var returnedReadResultLength = CreateReadResultFromConnectionReadResult(); // Don't count bytes belonging to the next request, since read rate timeouts are done on a per-request basis. StopTimingRead(returnedReadResultLength); if (_readResult.IsCompleted) { TryStop(); } break; } ResetReadingState(); } return _readResult; } public override bool TryRead(out ReadResult readResult) { ThrowIfCompleted(); return TryReadInternal(out readResult); } public override bool TryReadInternal(out ReadResult readResult) { if (_isReading) { throw new InvalidOperationException("Reading is already in progress."); } if (_readCompleted) { _isReading = true; readResult = new ReadResult(_readResult.Buffer, Interlocked.Exchange(ref _userCanceled, 0) == 1, _readResult.IsCompleted); return true; } TryStart(); // The while(true) because we don't want to return a canceled ReadResult if the user themselves didn't cancel it. while (true) { if (!_context.Input.TryRead(out _readResult)) { readResult = default; return false; } if (!_readResult.IsCanceled || Interlocked.Exchange(ref _userCanceled, 0) == 1) { break; } _context.Input.AdvanceTo(_readResult.Buffer.Start); } if (_readResult.IsCompleted) { _context.Input.AdvanceTo(_readResult.Buffer.Start); ThrowUnexpectedEndOfRequestContent(); } var returnedReadResultLength = CreateReadResultFromConnectionReadResult(); // Don't count bytes belonging to the next request, since read rate timeouts are done on a per-request basis. CountBytesRead(returnedReadResultLength); // Only set _isReading if we are returning true. _isReading = true; readResult = _readResult; if (readResult.IsCompleted) { TryStop(); } return true; } private long CreateReadResultFromConnectionReadResult() { var initialLength = _readResult.Buffer.Length; var maxLength = _inputLength + _examinedUnconsumedBytes; if (initialLength < maxLength) { return initialLength; } _readCompleted = true; _readResult = new ReadResult( _readResult.Buffer.Slice(0, maxLength), _readResult.IsCanceled, isCompleted: true); return maxLength; } public override void AdvanceTo(SequencePosition consumed) { AdvanceTo(consumed, consumed); } public override void AdvanceTo(SequencePosition consumed, SequencePosition examined) { if (!_isReading) { throw new InvalidOperationException("No reading operation to complete."); } _isReading = false; if (_readCompleted) { // If the old stored _readResult was canceled, it's already been observed. Do not store a canceled read result permanently. _readResult = new ReadResult(_readResult.Buffer.Slice(consumed, _readResult.Buffer.End), isCanceled: false, _readCompleted); if (!_finalAdvanceCalled && _readResult.Buffer.Length == 0) { _context.Input.AdvanceTo(consumed); _finalAdvanceCalled = true; _context.OnTrailersComplete(); } return; } _inputLength -= OnAdvance(_readResult, consumed, examined); _context.Input.AdvanceTo(consumed, examined); } protected override void OnReadStarting() { if (_contentLength > _context.MaxRequestBodySize) { BadHttpRequestException.Throw(RequestRejectionReason.RequestBodyTooLarge); } } public override void Complete(Exception exception) { _context.ReportApplicationError(exception); _completed = true; } public override void CancelPendingRead() { Interlocked.Exchange(ref _userCanceled, 1); _context.Input.CancelPendingRead(); } protected override Task OnStopAsync() { Complete(null); return Task.CompletedTask; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net; using System.Security.Authentication.ExtendedProtection; using System.Security.Principal; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel { public class ClientCredentialsSecurityTokenManager : SecurityTokenManager { private ClientCredentials _parent; public ClientCredentialsSecurityTokenManager(ClientCredentials clientCredentials) { if (clientCredentials == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("clientCredentials"); } _parent = clientCredentials; } public ClientCredentials ClientCredentials { get { return _parent; } } string GetServicePrincipalName(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement) { EndpointAddress targetAddress = initiatorRequirement.TargetAddress; if (targetAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.Format(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement)); } IdentityVerifier identityVerifier; SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement; if (securityBindingElement != null) { identityVerifier = securityBindingElement.LocalClientSettings.IdentityVerifier; } else { identityVerifier = IdentityVerifier.CreateDefault(); } EndpointIdentity identity; identityVerifier.TryGetIdentity(targetAddress, out identity); return SecurityUtils.GetSpnFromIdentity(identity, targetAddress); } private bool IsDigestAuthenticationScheme(SecurityTokenRequirement requirement) { if (requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty)) { AuthenticationSchemes authScheme = (AuthenticationSchemes)requirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty]; if (!authScheme.IsSingleton()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authScheme", string.Format(SR.HttpRequiresSingleAuthScheme, authScheme)); } return (authScheme == AuthenticationSchemes.Digest); } else { return false; } } internal protected bool IsIssuedSecurityTokenRequirement(SecurityTokenRequirement requirement) { if (requirement != null && requirement.Properties.ContainsKey(ServiceModelSecurityTokenRequirement.IssuerAddressProperty)) { // handle all issued token requirements except for spnego, tlsnego and secure conversation if (requirement.TokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.MutualSslnego || requirement.TokenType == ServiceModelSecurityTokenTypes.SecureConversation || requirement.TokenType == ServiceModelSecurityTokenTypes.Spnego) { return false; } else { return true; } } return false; } public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } SecurityTokenProvider result = null; if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange) { // this is the uncorrelated duplex case if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate); } else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement) { InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)"); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange"); } else { if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate); } } else if (tokenType == SecurityTokenTypes.Kerberos) { string spn = GetServicePrincipalName(initiatorRequirement); result = new KerberosSecurityTokenProviderWrapper( new KerberosSecurityTokenProvider(spn, _parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential))); } else if (tokenType == SecurityTokenTypes.UserName) { if (_parent.UserName.UserName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UserNamePasswordNotProvidedOnClientCredentials)); } result = new UserNameSecurityTokenProvider(_parent.UserName.UserName, _parent.UserName.Password); } else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential) { if (IsDigestAuthenticationScheme(initiatorRequirement)) { result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.HttpDigest.ClientCredential), true, TokenImpersonationLevel.Delegation); } else { #pragma warning disable 618 // to disable AllowNtlm obsolete wanring. result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential), _parent.Windows.AllowNtlm, _parent.Windows.AllowedImpersonationLevel); #pragma warning restore 618 } } } if ((result == null) && !tokenRequirement.IsOptionalToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement))); } return result; } public override SecurityTokenSerializer CreateSecurityTokenSerializer(SecurityTokenVersion version) { // not referenced anywhere in current code, but must implement abstract. throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenSerializer(SecurityTokenVersion version) not supported"); } private X509SecurityTokenAuthenticator CreateServerX509TokenAuthenticator() { return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.Authentication.GetCertificateValidator(), false); } private X509SecurityTokenAuthenticator CreateServerSslX509TokenAuthenticator() { if (_parent.ServiceCertificate.SslCertificateAuthentication != null) { return new X509SecurityTokenAuthenticator(_parent.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator(), false); } return CreateServerX509TokenAuthenticator(); } public override SecurityTokenAuthenticator CreateSecurityTokenAuthenticator(SecurityTokenRequirement tokenRequirement, out SecurityTokenResolver outOfBandTokenResolver) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } outOfBandTokenResolver = null; SecurityTokenAuthenticator result = null; InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; if (initiatorRequirement != null) { string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator"); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.IsOutOfBandToken) { // when the client side soap security asks for a token authenticator, its for doing // identity checks on the out of band server certificate result = new X509SecurityTokenAuthenticator(X509CertificateValidator.None); } else if (initiatorRequirement.PreferSslCertificateAuthenticator) { result = CreateServerSslX509TokenAuthenticator(); } else { result = CreateServerX509TokenAuthenticator(); } } else if (tokenType == SecurityTokenTypes.Rsa) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Rsa"); } else if (tokenType == SecurityTokenTypes.Kerberos) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : SecurityTokenTypes.Kerberos"); } else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation || tokenType == ServiceModelSecurityTokenTypes.MutualSslnego || tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego || tokenType == ServiceModelSecurityTokenTypes.Spnego) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenAuthenticator : GenericXmlSecurityTokenAuthenticator"); } } else if ((tokenRequirement is RecipientServiceModelSecurityTokenRequirement) && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate) { // uncorrelated duplex case result = CreateServerX509TokenAuthenticator(); } if (result == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateAuthenticatorForRequirement, tokenRequirement))); } return result; } } internal class KerberosSecurityTokenProviderWrapper : CommunicationObjectSecurityTokenProvider { private KerberosSecurityTokenProvider innerProvider; public KerberosSecurityTokenProviderWrapper(KerberosSecurityTokenProvider innerProvider) { this.innerProvider = innerProvider; } internal Task<SecurityToken> GetTokenAsync(CancellationToken cancellationToken, ChannelBinding channelbinding) { return Task.FromResult((SecurityToken)new KerberosRequestorSecurityToken(this.innerProvider.ServicePrincipalName, this.innerProvider.TokenImpersonationLevel, this.innerProvider.NetworkCredential, SecurityUniqueId.Create().Value)); } protected override Task<SecurityToken> GetTokenCoreAsync(CancellationToken cancellationToken) { return GetTokenAsync(cancellationToken, 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.Generic; using System.Diagnostics.Contracts; using System.Linq; using Microsoft.Cci.Extensions; using Microsoft.Cci.Extensions.CSharp; using Microsoft.Cci.Writers.Syntax; namespace Microsoft.Cci.Writers.CSharp { public partial class CSDeclarationWriter { private void WriteMethodDefinition(IMethodDefinition method) { if (method.IsPropertyOrEventAccessor()) return; if (method.IsDestructor()) { WriteDestructor(method); return; } string name = method.GetMethodName(); WriteMethodPseudoCustomAttributes(method); WriteAttributes(method.Attributes); WriteAttributes(method.SecurityAttributes); if (!method.ContainingTypeDefinition.IsInterface) { if (!method.IsExplicitInterfaceMethod()) WriteVisibility(method.Visibility); WriteMethodModifiers(method); } WriteInterfaceMethodModifiers(method); WriteMethodDefinitionSignature(method, name); WriteMethodBody(method); } private void WriteDestructor(IMethodDefinition method) { WriteSymbol("~"); WriteIdentifier(((INamedEntity)method.ContainingTypeDefinition).Name); WriteSymbol("("); WriteSymbol(")", false); WriteEmptyBody(); } private void WriteTypeName(ITypeReference type, ITypeReference containingType, bool isDynamic = false) { var useKeywords = containingType.GetTypeName() != type.GetTypeName(); WriteTypeName(type, isDynamic: isDynamic, useTypeKeywords: useKeywords); } private void WriteMethodDefinitionSignature(IMethodDefinition method, string name) { bool isOperator = method.IsConversionOperator(); if (!isOperator && !method.IsConstructor) { WriteAttributes(method.ReturnValueAttributes, true); // We are ignoring custom modifiers right now, we might need to add them later. WriteTypeName(method.Type, method.ContainingType, isDynamic: IsDynamic(method.ReturnValueAttributes)); } WriteIdentifier(name); if (isOperator) { WriteSpace(); WriteTypeName(method.Type, method.ContainingType); } Contract.Assert(!(method is IGenericMethodInstance), "Currently don't support generic method instances"); if (method.IsGeneric) WriteGenericParameters(method.GenericParameters); WriteParameters(method.Parameters, method.ContainingType, extensionMethod: method.IsExtensionMethod(), acceptsExtraArguments: method.AcceptsExtraArguments); if (method.IsGeneric && !method.IsOverride() && !method.IsExplicitInterfaceMethod()) WriteGenericContraints(method.GenericParameters); } private void WriteParameters(IEnumerable<IParameterDefinition> parameters, ITypeReference containingType, bool property = false, bool extensionMethod = false, bool acceptsExtraArguments = false) { string start = property ? "[" : "("; string end = property ? "]" : ")"; WriteSymbol(start); _writer.WriteList(parameters, p => { WriteParameter(p, containingType, extensionMethod); extensionMethod = false; }); if (acceptsExtraArguments) { if (parameters.Any()) _writer.WriteSymbol(","); _writer.WriteSpace(); _writer.Write("__arglist"); } WriteSymbol(end); } private void WriteParameter(IParameterDefinition parameter, ITypeReference containingType, bool extensionMethod) { WriteAttributes(parameter.Attributes, true); if (extensionMethod) WriteKeyword("this"); if (parameter.IsParameterArray) WriteKeyword("params"); if (parameter.IsOut && !parameter.IsIn && parameter.IsByReference) { WriteKeyword("out"); } else { // For In/Out we should not emit them until we find a scenario that is needs thems. //if (parameter.IsIn) // WriteFakeAttribute("System.Runtime.InteropServices.In", writeInline: true); //if (parameter.IsOut) // WriteFakeAttribute("System.Runtime.InteropServices.Out", writeInline: true); if (parameter.IsByReference) WriteKeyword("ref"); } WriteTypeName(parameter.Type, containingType, isDynamic: IsDynamic(parameter.Attributes)); WriteIdentifier(parameter.Name); if (parameter.IsOptional && parameter.HasDefaultValue) { WriteSymbol("="); WriteMetadataConstant(parameter.DefaultValue, parameter.Type); } } private void WriteInterfaceMethodModifiers(IMethodDefinition method) { if (method.GetHiddenBaseMethod(_filter) != Dummy.Method) WriteKeyword("new"); } private void WriteMethodModifiers(IMethodDefinition method) { if (method.IsMethodUnsafe()) WriteKeyword("unsafe"); if (method.IsStatic) WriteKeyword("static"); if (method.IsPlatformInvoke) WriteKeyword("extern"); if (method.IsVirtual) { if (method.IsNewSlot) { if (method.IsAbstract) WriteKeyword("abstract"); else if (!method.IsSealed) // non-virtual interfaces implementations are sealed virtual newslots WriteKeyword("virtual"); } else { if (method.IsAbstract) WriteKeyword("abstract"); else if (method.IsSealed) WriteKeyword("sealed"); WriteKeyword("override"); } } } private void WriteMethodBody(IMethodDefinition method) { if (method.IsAbstract || !_forCompilation || method.IsPlatformInvoke) { WriteSymbol(";"); return; } if (method.IsConstructor) WriteBaseConstructorCall(method.ContainingTypeDefinition); // Write Dummy Body WriteSpace(); WriteSymbol("{", true); WriteOutParameterInitializations(method); if (_forCompilationThrowPlatformNotSupported) { Write("throw new "); if (_forCompilationIncludeGlobalprefix) Write("global::"); Write("System.PlatformNotSupportedException(); "); } else if (method.ContainingTypeDefinition.IsValueType && method.IsConstructor) { // Structs cannot have empty constructors so we need to output this dummy body Write("throw null;"); } else if (!TypeHelper.TypesAreEquivalent(method.Type, method.ContainingTypeDefinition.PlatformType.SystemVoid)) { WriteKeyword("throw null;"); } WriteSymbol("}"); } private void WritePrivateConstructor(ITypeDefinition type) { if (!_forCompilation || type.IsInterface || type.IsEnum || type.IsDelegate || type.IsValueType || type.IsStatic) return; WriteVisibility(TypeMemberVisibility.Assembly); WriteIdentifier(((INamedEntity)type).Name); WriteSymbol("("); WriteSymbol(")"); WriteBaseConstructorCall(type); WriteEmptyBody(); } private void WriteOutParameterInitializations(IMethodDefinition method) { if (!_forCompilation) return; var outParams = method.Parameters.Where(p => p.IsOut); foreach (var param in outParams) { WriteIdentifier(param.Name); WriteSpace(); WriteSymbol("=", true); WriteDefaultOf(param.Type); WriteSymbol(";", true); } } private void WriteBaseConstructorCall(ITypeDefinition type) { if (!_forCompilation) return; ITypeDefinition baseType = type.BaseClasses.FirstOrDefault().GetDefinitionOrNull(); if (baseType == null) return; var ctors = baseType.Methods.Where(m => m.IsConstructor && _filter.Include(m)); var defaultCtor = ctors.Where(c => c.ParameterCount == 0); // Don't need a base call if we have a default constructor if (defaultCtor.Any()) return; var ctor = ctors.FirstOrDefault(); if (ctor == null) return; WriteSpace(); WriteSymbol(":", true); WriteKeyword("base"); WriteSymbol("("); _writer.WriteList(ctor.Parameters, p => WriteDefaultOf(p.Type)); WriteSymbol(")"); } private void WriteEmptyBody() { if (!_forCompilation) { WriteSymbol(";"); } else { WriteSpace(); WriteSymbol("{", true); WriteSymbol("}"); } } private void WriteDefaultOf(ITypeReference type) { WriteKeyword("default", true); WriteSymbol("("); WriteTypeName(type, true); WriteSymbol(")"); } public static IDefinition GetDummyConstructor(ITypeDefinition type) { return new DummyInternalConstructor() { ContainingType = type }; } private class DummyInternalConstructor : IDefinition { public ITypeDefinition ContainingType { get; set; } public IEnumerable<ICustomAttribute> Attributes { get { throw new System.NotImplementedException(); } } public void Dispatch(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } public IEnumerable<ILocation> Locations { get { throw new System.NotImplementedException(); } } public void DispatchAsReference(IMetadataVisitor visitor) { throw new System.NotImplementedException(); } } } }
// 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 CompareNotLessThanSingle() { var test = new SimpleBinaryOpTest__CompareNotLessThanSingle(); 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__CompareNotLessThanSingle { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[ElementCount]; private static Single[] _data2 = new Single[ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private SimpleBinaryOpTest__DataTable<Single> _dataTable; static SimpleBinaryOpTest__CompareNotLessThanSingle() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareNotLessThanSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single>(_data1, _data2, new Single[ElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareNotLessThan( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse.CompareNotLessThan( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse.CompareNotLessThan( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareNotLessThan), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse.CompareNotLessThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareNotLessThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareNotLessThanSingle(); var result = Sse.CompareNotLessThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.CompareNotLessThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[ElementCount]; Single[] inArray2 = new Single[ElementCount]; Single[] outArray = new Single[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != (!(left[0] < right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != (!(left[i] < right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareNotLessThan)}<Single>: {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 MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Xml; using System.Text; using System.Reflection; using System.Collections; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Diagnostics; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.VisualStudio.Internal; namespace Microsoft.Build.UnitTests { /* * Class: ObjectModelHelpers * Owner: jomof * * Utility methods for unit tests that work through the object model. * */ public static class ObjectModelHelpers { private const string msbuildNamespace = "http://schemas.microsoft.com/developer/msbuild/2003"; private const string msbuildDefaultToolsVersion = BrandNames.VSGeneralVersion; private const string msbuildAssemblyVersion = BrandNames.VSGeneralAssemblyVersion; /// <summary> /// Return the default tools version /// </summary> internal static string MSBuildDefaultToolsVersion { get { return msbuildDefaultToolsVersion; } private set { } } /// <summary> /// Return the current assembly version /// </summary> internal static string MSBuildAssemblyVersion { get { return msbuildAssemblyVersion; } private set { } } /// <summary> /// Helper method to tell us whether a particular metadata name is an MSBuild well-known metadata /// (e.g., "RelativeDir", "FullPath", etc.) /// </summary> /// <owner>RGoel</owner> private static Hashtable builtInMetadataNames = null; static private bool IsBuiltInItemMetadataName(string metadataName) { if (builtInMetadataNames == null) { builtInMetadataNames = new Hashtable(); Microsoft.Build.Utilities.TaskItem dummyTaskItem = new Microsoft.Build.Utilities.TaskItem(); foreach (string builtInMetadataName in dummyTaskItem.MetadataNames) { builtInMetadataNames[builtInMetadataName] = String.Empty; } } return builtInMetadataNames.Contains(metadataName); } /// <summary> /// Asserts that there are no items in the project of the specified type /// </summary> static internal void AssertNoItem(Project p, string type) { BuildItemGroup items = p.GetEvaluatedItemsByName(type); Assertion.AssertEquals(0, items.Count); } /// <summary> /// Gets an item list from the project and assert that it contains /// exactly one item with the supplied name. /// </summary> /// <param name="p"></param> /// <param name="type"></param> /// <param name="itemInclude"></param> /// <owner>JomoF</owner> static internal BuildItem AssertSingleItem(Project p, string type, string itemInclude) { BuildItemGroup items = p.GetEvaluatedItemsByName(type); int count = 0; foreach(BuildItem item in items) { // This was item.Include before, but I believe it really should have been item.FinalItemSpec, which // is what is actually used by tasks, etc. Assertion.AssertEquals(itemInclude.ToUpperInvariant(), item.FinalItemSpec.ToUpperInvariant()); ++count; } Assertion.AssertEquals(1, count); return items[0]; } /// <summary> /// Given a hash table of ITaskItems, make sure there is exactly one /// item and that the key is 'key' and the Value is an ITaskItem with /// an item spec of 'itemSpec' /// </summary> /// <param name="d"></param> /// <param name="key"></param> /// <param name="itemSpec"></param> /// <owner>JomoF</owner> static internal void AssertSingleItemInDictionary(IDictionary d, string expectedItemSpec) { List<ITaskItem> actualItems = new List<ITaskItem>(); string projectDir= Path.GetTempPath(); Console.WriteLine("cd={0}", projectDir); foreach(DictionaryEntry e in d) { foreach(ITaskItem i in (ITaskItem[])e.Value) { i.ItemSpec = i.ItemSpec.Replace(projectDir, "<|proj|>"); actualItems.Add(i); } } AssertItemsMatch(expectedItemSpec, actualItems.ToArray()); } /// <summary> /// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from /// a task match the expected set of ITaskItems. It can also check that the ITaskItems have the expected /// metadata, and that the ITaskItems are returned in the correct order. /// /// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see. /// The format is: /// /// itemspec1 : metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ... /// itemspec2 : metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ... /// itemspec3 : metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ... /// /// (Each item needs to be on its own line.) /// /// </summary> /// <param name="expectedItemsString"></param> /// <param name="actualItems"></param> /// <owner>RGoel</owner> static internal void AssertItemsMatch(string expectedItemsString, ITaskItem[] actualItems) { AssertItemsMatch(expectedItemsString, actualItems, true); } /// <summary> /// Amazingly sophisticated :) helper function to determine if the set of ITaskItems returned from /// a task match the expected set of ITaskItems. It can also check that the ITaskItems have the expected /// metadata, and that the ITaskItems are returned in the correct order. /// /// The "expectedItemsString" is a formatted way of easily specifying which items you expect to see. /// The format is: /// /// itemspec1 : metadataname1=metadatavalue1 ; metadataname2=metadatavalue2 ; ... /// itemspec2 : metadataname3=metadatavalue3 ; metadataname4=metadatavalue4 ; ... /// itemspec3 : metadataname5=metadatavalue5 ; metadataname6=metadatavalue6 ; ... /// /// (Each item needs to be on its own line.) /// /// </summary> /// <param name="expectedItemsString"></param> /// <param name="actualItems"></param> /// <param name="orderOfItemsShouldMatch"></param> /// <owner>RGoel</owner> static internal void AssertItemsMatch(string expectedItemsString, ITaskItem[] actualItems, bool orderOfItemsShouldMatch) { List<ITaskItem> expectedItems = ParseExpectedItemsString(expectedItemsString); // Form a string of expected item specs. For logging purposes only. StringBuilder expectedItemSpecs = new StringBuilder(); foreach (ITaskItem expectedItem in expectedItems) { if (expectedItemSpecs.Length > 0) { expectedItemSpecs.Append("; "); } expectedItemSpecs.Append(expectedItem.ItemSpec); } // Form a string of expected item specs. For logging purposes only. StringBuilder actualItemSpecs = new StringBuilder(); foreach (ITaskItem actualItem in actualItems) { if (actualItemSpecs.Length > 0) { actualItemSpecs.Append("; "); } actualItemSpecs.Append(actualItem.ItemSpec); } bool outOfOrder = false; // Loop through all the actual items. for (int actualItemIndex = 0 ; actualItemIndex < actualItems.Length ; actualItemIndex++) { ITaskItem actualItem = actualItems[actualItemIndex]; // Loop through all the expected items to find one with the same item spec. ITaskItem expectedItem = null; int expectedItemIndex; for (expectedItemIndex = 0 ; expectedItemIndex < expectedItems.Count ; expectedItemIndex++) { if (expectedItems[expectedItemIndex].ItemSpec == actualItem.ItemSpec) { expectedItem = expectedItems[expectedItemIndex]; // If the items are expected to be in the same order, then the expected item // should always be found at index zero, because we remove items from the expected // list as we find them. if ((expectedItemIndex != 0) && (orderOfItemsShouldMatch)) { outOfOrder = true; } break; } } Assertion.Assert(String.Format("Item '{0}' was returned but not expected.", actualItem.ItemSpec), expectedItem != null); // Make sure all the metadata on the expected item matches the metadata on the actual item. // Don't check built-in metadata ... only check custom metadata. foreach (string metadataName in expectedItem.MetadataNames) { // This check filters out any built-in item metadata, like "RelativeDir", etc. if (!IsBuiltInItemMetadataName(metadataName)) { string expectedMetadataValue = expectedItem.GetMetadata(metadataName); string actualMetadataValue = actualItem.GetMetadata(metadataName); Assertion.Assert(string.Format("Item '{0}' does not have expected metadata '{1}'.", actualItem.ItemSpec, metadataName), actualMetadataValue.Length > 0 || expectedMetadataValue.Length == 0); Assertion.Assert(string.Format("Item '{0}' has unexpected metadata {1}={2}.", actualItem.ItemSpec, metadataName, actualMetadataValue), actualMetadataValue.Length == 0 || expectedMetadataValue.Length > 0); Assertion.Assert(string.Format("Item '{0}' has metadata {1}={2} instead of expected {1}={3}.", actualItem.ItemSpec, metadataName, actualMetadataValue, expectedMetadataValue), actualMetadataValue == expectedMetadataValue); } } expectedItems.RemoveAt(expectedItemIndex); } // Log an error for any leftover items in the expectedItems collection. foreach (ITaskItem expectedItem in expectedItems) { Assertion.Assert(String.Format("Item '{0}' was expected but not returned.", expectedItem.ItemSpec), false); } if (outOfOrder) { Console.WriteLine("ERROR: Items were returned in the incorrect order..."); Console.WriteLine("Expected: " + expectedItemSpecs); Console.WriteLine("Actual: " + actualItemSpecs); Assertion.Assert("Items were returned in the incorrect order. See 'Standard Out' tab for more details.", false); } } /// <summary> /// Parses the crazy string passed into AssertItemsMatch and returns a list of ITaskItems. /// </summary> /// <param name="expectedItemsString"></param> /// <returns></returns> /// <owner>RGoel</owner> static private List<ITaskItem> ParseExpectedItemsString(string expectedItemsString) { List<ITaskItem> expectedItems = new List<ITaskItem>(); // First, parse this massive string that we've been given, and create an ITaskItem[] out of it, // so we can more easily compare it against the actual items. string[] expectedItemsStringSplit = expectedItemsString.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries); foreach (string singleExpectedItemString in expectedItemsStringSplit) { string singleExpectedItemStringTrimmed = singleExpectedItemString.Trim(); if (singleExpectedItemStringTrimmed.Length > 0) { int indexOfColon = singleExpectedItemStringTrimmed.IndexOf(": "); if (indexOfColon == -1) { expectedItems.Add(new Microsoft.Build.Utilities.TaskItem(singleExpectedItemStringTrimmed)); } else { // We found a colon, which means there's metadata in there. // The item spec is the part before the colon. string itemSpec = singleExpectedItemStringTrimmed.Substring(0, indexOfColon).Trim(); // The metadata is the part after the colon. string itemMetadataString = singleExpectedItemStringTrimmed.Substring(indexOfColon + 1); ITaskItem expectedItem = new Microsoft.Build.Utilities.TaskItem(itemSpec); string[] itemMetadataPieces = itemMetadataString.Split(new char[]{';'}, StringSplitOptions.RemoveEmptyEntries); foreach (string itemMetadataPiece in itemMetadataPieces) { string itemMetadataPieceTrimmed = itemMetadataPiece.Trim(); if (itemMetadataPieceTrimmed.Length > 0) { int indexOfEquals = itemMetadataPieceTrimmed.IndexOf('='); Assertion.Assert(String.Format("Could not find <equals> in item metadata definition '{0}'", itemMetadataPieceTrimmed), indexOfEquals != -1); string itemMetadataName = itemMetadataPieceTrimmed.Substring(0, indexOfEquals).Trim(); string itemMetadataValue = itemMetadataPieceTrimmed.Substring(indexOfEquals + 1).Trim(); expectedItem.SetMetadata(itemMetadataName, itemMetadataValue); } } expectedItems.Add(expectedItem); } } } return expectedItems; } /// <summary> /// Does certain replacements in a string representing the project file contents. /// This makes it easier to write unit tests because the author doesn't have /// to worry about escaping double-quotes, etc. /// </summary> /// <param name="projectFileContents"></param> /// <returns></returns> static internal string CleanupFileContents(string projectFileContents) { // Replace reverse-single-quotes with double-quotes. projectFileContents = projectFileContents.Replace("`", "\""); // Place the correct MSBuild namespace into the <Project> tag. projectFileContents = projectFileContents.Replace("msbuildnamespace", msbuildNamespace); projectFileContents = projectFileContents.Replace("msbuilddefaulttoolsversion", msbuildDefaultToolsVersion); projectFileContents = projectFileContents.Replace("msbuildassemblyversion", msbuildAssemblyVersion); return projectFileContents; } /// <summary> /// Normalizes all the whitespace in an Xml document so that two documents that /// differ only in whitespace can be easily compared to each other for sameness. /// </summary> /// <param name="xmldoc"></param> /// <returns></returns> /// <owner>RGoel</owner> static private string NormalizeXmlWhitespace(XmlDocument xmldoc) { // Normalize all the whitespace by writing the Xml document out to a // string, with PreserveWhitespace=false. xmldoc.PreserveWhitespace = false; StringWriter stringWriter = new StringWriter(); xmldoc.Save(stringWriter); return stringWriter.ToString(); } /// <summary> /// Create an MSBuild project file on disk and return the full path to it. /// </summary> /// <param name="xml"></param> /// <returns></returns> /// <owner>RGoel</owner> static internal string CreateTempFileOnDisk(string fileContents, params object[] args) { return CreateTempFileOnDiskNoFormat(String.Format(fileContents, args)); } /// <summary> /// Create an MSBuild project file on disk and return the full path to it. /// </summary> /// <param name="xml"></param> /// <returns></returns> /// <owner>RGoel</owner> static internal string CreateTempFileOnDiskNoFormat(string fileContents) { string projectFilePath = Path.GetTempFileName(); File.WriteAllText(projectFilePath, CleanupFileContents(fileContents)); return projectFilePath; } /// <summary> /// Create a project in memory. Load up the given XML. /// </summary> /// <param name="xml"></param> /// <returns></returns> /// <owner>JomoF</owner> static internal Project CreateInMemoryProject(string xml) { return CreateInMemoryProject(xml, new ConsoleLogger()); } /// <summary> /// Create a project in memory. Load up the given XML. /// </summary> /// <param name="xml"></param> /// <param name="logger"></param> /// <returns></returns> /// <owner>JomoF</owner> static internal Project CreateInMemoryProject(string xml, ILogger logger /* May be null */) { Engine e = new Engine(); e.DefaultToolsVersion = "4.0"; return CreateInMemoryProject(e, xml, logger); } /// <summary> /// Create an in-memory project and attach it to the passed-in engine. /// </summary> /// <param name="engine"></param> /// <param name="xml"></param> /// <param name="logger">May be null</param> /// <returns></returns> static internal Project CreateInMemoryProject(Engine e, string xml, ILogger logger /* May be null */) { return CreateInMemoryProject(e, xml, logger, null); } /// <summary> /// Create an in-memory project and attach it to the passed-in engine. /// </summary> /// <param name="logger">May be null</param> /// <param name="toolsVersion">May be null</param> static internal Project CreateInMemoryProject(Engine e, string xml, ILogger logger /* May be null */, string toolsVersion/* may be null */) { return CreateInMemoryProject(e, xml, logger, toolsVersion, ProjectLoadSettings.None); } /// <summary> /// Create an in-memory project and attach it to the passed-in engine. /// </summary> /// <param name="logger">May be null</param> /// <param name="toolsVersion">May be null</param> static internal Project CreateInMemoryProject(Engine e, string xml, ILogger logger /* May be null */, string toolsVersion/* may be null */, ProjectLoadSettings projectLoadSettings) { // Anonymous in-memory projects use the current directory for $(MSBuildProjectDirectory). // We need to set the directory to something reasonable. string originalDir = Directory.GetCurrentDirectory(); Directory.SetCurrentDirectory(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); #if _NEVER // Attach a console logger so that build output can go to the test // harness. e.RegisterLogger(new ConsoleLogger(ConsoleLogger.Verbosity.Verbose)); #endif Project p = new Project(e, toolsVersion); p.FullFileName = Path.Combine(Path.GetTempPath(), "Temporary.csproj"); if (logger != null) { p.ParentEngine.RegisterLogger(logger); } p.LoadXml(CleanupFileContents(xml), projectLoadSettings); // Return to the original directory. Directory.SetCurrentDirectory(originalDir); return p; } /// <summary> /// Creates a project in memory and builds the default targets. The build is /// expected to succeed. /// </summary> /// <param name="projectContents"></param> /// <returns></returns> /// <owner>RGoel</owner> internal static MockLogger BuildProjectExpectSuccess ( string projectContents ) { MockLogger logger = new MockLogger(); Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents, logger); bool success = project.Build(null, null); Assertion.Assert("Build failed. See Standard Out tab for details", success); return logger; } /// <summary> /// Creates a project in memory and builds the default targets. The build is /// expected to fail. /// </summary> /// <param name="projectContents"></param> /// <returns></returns> /// <owner>RGoel</owner> internal static MockLogger BuildProjectExpectFailure ( string projectContents ) { MockLogger logger = new MockLogger(); Project project = ObjectModelHelpers.CreateInMemoryProject(projectContents, logger); bool success = project.Build(null, null); Assertion.Assert("Build succeeded, but shouldn't have. See Standard Out tab for details", !success); return logger; } /// <summary> /// This helper method compares the final project contents with the expected /// value. /// </summary> /// <param name="project"></param> /// <param name="newExpectedProjectContents"></param> /// <owner>RGoel</owner> internal static void CompareProjectContents ( Project project, string newExpectedProjectContents ) { // Get the new XML for the project, normalizing the whitespace. string newActualProjectContents = project.Xml; // Replace single-quotes with double-quotes, and normalize whitespace. XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(ObjectModelHelpers.CleanupFileContents(newExpectedProjectContents)); newExpectedProjectContents = ObjectModelHelpers.NormalizeXmlWhitespace(xmldoc); // Compare the actual XML with the expected XML. Console.WriteLine("================================= EXPECTED ==========================================="); Console.WriteLine(newExpectedProjectContents); Console.WriteLine(); Console.WriteLine("================================== ACTUAL ============================================"); Console.WriteLine(newActualProjectContents); Console.WriteLine(); Assertion.AssertEquals("Project XML does not match expected XML. See 'Standard Out' tab for details.", newExpectedProjectContents, newActualProjectContents); } private static string tempProjectDir = null; /// <summary> /// Returns the path %TEMP%\TempDirForMSBuildUnitTests /// </summary> internal static string TempProjectDir { get { if (tempProjectDir == null) { tempProjectDir = Path.Combine(Path.GetTempPath(), "TempDirForMSBuildUnitTests"); } return tempProjectDir; } } /// <summary> /// Deletes the directory %TEMP%\TempDirForMSBuildUnitTests, and all its contents. /// </summary> internal static void DeleteTempProjectDirectory() { // For some reason sometimes get "directory is not empty" // Try to be as robust as possible using retries and catching all exceptions. for (int retries = 0; retries < 5; retries++) { try { // Manually deleting all children, but intentionally leaving the // Temp project directory behind due to locking issues which were causing // failures in main on Amd64-WOW runs. if (Directory.Exists(TempProjectDir)) { foreach (string directory in Directory.GetDirectories(TempProjectDir)) { Directory.Delete(directory, true); } foreach (string file in Directory.GetFiles(TempProjectDir)) { File.Delete(file); } } } catch(Exception ex) { Console.WriteLine(ex.ToString()); } } } /// <summary> /// Creates a file in the %TEMP%\TempDirForMSBuildUnitTests directory, after cleaning /// up the file contents (replacing single-back-quote with double-quote, etc.). /// </summary> /// <param name="fileRelativePath"></param> /// <param name="fileContents"></param> internal static string CreateFileInTempProjectDirectory(string fileRelativePath, string fileContents) { Assertion.Assert(!String.IsNullOrEmpty(fileRelativePath)); string fullFilePath = Path.Combine(TempProjectDir, fileRelativePath); Directory.CreateDirectory(Path.GetDirectoryName(fullFilePath)); // retries to deal with occasional locking issues where the file can't be written to initially for (int retries = 0; retries < 5; retries++) { try { File.WriteAllText(fullFilePath, CleanupFileContents(fileContents)); break; } catch(Exception ex) { if (retries < 4) { Console.WriteLine(ex.ToString()); } else { // All the retries have failed, so we're pretty much screwed. Might as well fail with the // actual problem now instead of with some more difficult-to-understand // issue later. throw ex; } } } return fullFilePath; } /// <summary> /// Loads a project file from disk /// </summary> /// <param name="fileRelativePath"></param> /// <returns></returns> /// <owner>LukaszG</owner> internal static Project LoadProjectFileInTempProjectDirectory(string projectFileRelativePath, ILogger logger) { return LoadProjectFileInTempProjectDirectory(projectFileRelativePath, logger, false /* don't touch project*/); } /// <summary> /// Loads a project file from disk /// </summary> /// <param name="fileRelativePath"></param> /// <returns></returns> /// <owner>LukaszG</owner> internal static Project LoadProjectFileInTempProjectDirectory(string projectFileRelativePath, ILogger logger, bool touchProject) { string projectFileFullPath = Path.Combine(TempProjectDir, projectFileRelativePath); // Create/initialize a new engine. Engine engine = new Engine(); if (logger != null) { engine.RegisterLogger(logger); } // Load the project off disk. Project project = engine.CreateNewProject(); if (touchProject) { File.SetLastWriteTime(projectFileFullPath, DateTime.Now); } project.Load(projectFileFullPath); return project; } /// <summary> /// Builds a project file from disk, and asserts if the build does not succeed. /// </summary> /// <param name="projectFileRelativePath"></param> /// <param name="targets"></param> /// <param name="additionalProperties">Can be null.</param> /// <param name="logger"></param> /// <returns></returns> internal static bool BuildTempProjectFileWithTargets ( string projectFileRelativePath, string[] targets, BuildPropertyGroup additionalProperties, MockLogger logger ) { return BuildTempProjectFileWithTargets(projectFileRelativePath, targets, additionalProperties, logger, false /* don't touch project*/); } /// <summary> /// Builds a project file from disk, and asserts if the build does not succeed. /// </summary> /// <param name="projectFileRelativePath"></param> /// <param name="targets"></param> /// <param name="additionalProperties">Can be null.</param> /// <param name="logger"></param> /// <returns></returns> internal static bool BuildTempProjectFileWithTargets ( string projectFileRelativePath, string[] targets, BuildPropertyGroup additionalProperties, MockLogger logger, bool touchProject ) { Project project = LoadProjectFileInTempProjectDirectory(projectFileRelativePath, logger, touchProject); if (additionalProperties != null) { // add extra properties foreach (BuildProperty additionalProperty in additionalProperties) { project.GlobalProperties.SetProperty(additionalProperty.Name, additionalProperty.Value); } } // Build the default targets. return project.Build(targets, null); } /// <summary> /// Builds a project file from disk, and asserts if the build does not succeed. /// </summary> /// <param name="projectFileRelativePath"></param> /// <returns></returns> /// <owner>RGoel</owner> internal static MockLogger BuildTempProjectFileExpectSuccess(string projectFileRelativePath) { return BuildTempProjectFileWithTargetsExpectSuccess(projectFileRelativePath, null, null, false); } /// <summary> /// Builds a project file from disk, and asserts if the build does not succeed. /// </summary> internal static MockLogger BuildTempProjectFileWithTargetsExpectSuccess(string projectFileRelativePath, string[] targets, BuildPropertyGroup additionalProperties) { MockLogger logger = new MockLogger(); bool success = BuildTempProjectFileWithTargets(projectFileRelativePath, targets, additionalProperties, logger, false); Assertion.Assert("Build failed. See Standard Out tab for details", success); return logger; } /// <summary> /// Builds a project file from disk, and asserts if the build does not succeed. /// </summary> internal static MockLogger BuildTempProjectFileWithTargetsExpectSuccess(string projectFileRelativePath, string[] targets, BuildPropertyGroup additionalProperties, bool touchProject) { MockLogger logger = new MockLogger(); bool success = BuildTempProjectFileWithTargets(projectFileRelativePath, targets, additionalProperties, logger, touchProject); Assertion.Assert("Build failed. See Standard Out tab for details", success); return logger; } /// <summary> /// Builds a project file from disk, and asserts if the build succeeds. /// </summary> internal static MockLogger BuildTempProjectFileExpectFailure(string projectFileRelativePath) { return BuildTempProjectFileWithTargetsExpectFailure(projectFileRelativePath, null, null); } /// <summary> /// Builds a project file from disk, and asserts if the build succeeds. /// </summary> private static MockLogger BuildTempProjectFileWithTargetsExpectFailure(string projectFileRelativePath, string[] targets, BuildPropertyGroup additionalProperties) { MockLogger logger = new MockLogger(); bool success = BuildTempProjectFileWithTargets(projectFileRelativePath, targets, additionalProperties, logger); Assertion.Assert("Build unexpectedly succeeded. See Standard Out tab for details", !success); return logger; } /// <summary> /// Runs an EXE and captures the stdout. /// </summary> /// <param name="builtExe"></param> /// <returns></returns> /// <owner>RGoel</owner> internal static string RunTempProjectBuiltApplication(string builtExe) { string builtExeFullPath = Path.Combine(TempProjectDir, builtExe); Assertion.Assert(@"Did not find expected file " + builtExe, File.Exists(builtExeFullPath)); ProcessStartInfo startInfo = new ProcessStartInfo(builtExeFullPath); startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; Process process = Process.Start(startInfo); process.WaitForExit(); string stdout = process.StandardOutput.ReadToEnd(); Console.WriteLine("================================================================="); Console.WriteLine("======= OUTPUT OF BUILT APPLICATION ============================="); Console.WriteLine("================================================================="); Console.WriteLine(stdout); Assertion.Assert("ConsoleApplication37.exe returned a non-zero exit code.", process.ExitCode == 0); return stdout; } /// <summary> /// Assert that a given file exists within the temp project directory. /// </summary> /// <param name="fileRelativePath"></param> /// <owner>RGoel</owner> internal static void AssertFileExistsInTempProjectDirectory(string fileRelativePath) { AssertFileExistsInTempProjectDirectory(fileRelativePath, null); } /// <summary> /// Assert that a given file exists within the temp project directory. /// </summary> /// <param name="fileRelativePath"></param> /// <param name="message">Can be null.</param> internal static void AssertFileExistsInTempProjectDirectory(string fileRelativePath, string message) { if (message == null) { message = fileRelativePath + " doesn't exist, but it should."; } AssertFileExistenceInTempProjectDirectory(fileRelativePath, message, true); } /// <summary> /// Assert that a given file does not exist within the temp project directory. /// </summary> /// <param name="fileRelativePath"></param> internal static void AssertFileDoesNotExistInTempProjectDirectory(string fileRelativePath) { AssertFileDoesNotExistInTempProjectDirectory(fileRelativePath, null); } /// <summary> /// Assert that a given file does not exist within the temp project directory. /// </summary> /// <param name="fileRelativePath"></param> /// <param name="message">Can be null.</param> internal static void AssertFileDoesNotExistInTempProjectDirectory(string fileRelativePath, string message) { if (message == null) { message = fileRelativePath + " exists, but it should not."; } AssertFileExistenceInTempProjectDirectory(fileRelativePath, message, false); } /// <summary> /// Assert that a given file exists (or not) within the temp project directory. /// </summary> /// <param name="fileRelativePath"></param> /// <param name="message">Can be null.</param> private static void AssertFileExistenceInTempProjectDirectory(string fileRelativePath, string message, bool exists) { Assertion.Assert(message, (exists == File.Exists(Path.Combine(TempProjectDir, fileRelativePath)))); } /// <summary> /// Delete any files in the list that currently exist. /// </summary> /// <param name="files"></param> internal static void DeleteTempFiles(string[] files) { for (int i = 0; i < files.Length; i++) { if (File.Exists(files[i])) File.Delete(files[i]); } } /// <summary> /// Returns the requested number of temporary files. /// </summary> internal static string[] GetTempFiles(int number) { return GetTempFiles(number, DateTime.Now); } /// <summary> /// Returns the requested number of temporary files, with the requested write time. /// </summary> internal static string[] GetTempFiles(int number, DateTime lastWriteTime) { string[] files = new string[number]; for (int i = 0; i < number; i++) { files[i] = Path.GetTempFileName(); File.SetLastWriteTime(files[i], lastWriteTime); } return files; } } }
using UnityEngine; using UnityEditor; /// <summary> /// This editor helper class makes it easy to create and show a context menu. /// It ensures that it's possible to add multiple items with the same name. /// </summary> public static class NGUIContextMenu { [MenuItem("Help/NGUI Documentation")] static void ShowHelp0 (MenuCommand command) { NGUIHelp.Show(); } [MenuItem("CONTEXT/UIWidget/Copy Widget")] static void CopyStyle (MenuCommand command) { NGUISettings.CopyWidget(command.context as UIWidget); } [MenuItem("CONTEXT/UIWidget/Paste Widget Values")] static void PasteStyle (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, true); } [MenuItem("CONTEXT/UIWidget/Paste Widget Style")] static void PasteStyle2 (MenuCommand command) { NGUISettings.PasteWidget(command.context as UIWidget, false); } [MenuItem("CONTEXT/UIWidget/Help")] static void ShowHelp1 (MenuCommand command) { NGUIHelp.Show(command.context); } [MenuItem("CONTEXT/UIButton/Help")] static void ShowHelp2 (MenuCommand command) { NGUIHelp.Show(typeof(UIButton)); } [MenuItem("CONTEXT/UIToggle/Help")] static void ShowHelp3 (MenuCommand command) { NGUIHelp.Show(typeof(UIToggle)); } [MenuItem("CONTEXT/UIRoot/Help")] static void ShowHelp4 (MenuCommand command) { NGUIHelp.Show(typeof(UIRoot)); } [MenuItem("CONTEXT/UICamera/Help")] static void ShowHelp5 (MenuCommand command) { NGUIHelp.Show(typeof(UICamera)); } [MenuItem("CONTEXT/UIAnchor/Help")] static void ShowHelp6 (MenuCommand command) { NGUIHelp.Show(typeof(UIAnchor)); } [MenuItem("CONTEXT/UIStretch/Help")] static void ShowHelp7 (MenuCommand command) { NGUIHelp.Show(typeof(UIStretch)); } [MenuItem("CONTEXT/UISlider/Help")] static void ShowHelp8 (MenuCommand command) { NGUIHelp.Show(typeof(UISlider)); } #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 [MenuItem("CONTEXT/UI2DSprite/Help")] static void ShowHelp9 (MenuCommand command) { NGUIHelp.Show(typeof(UI2DSprite)); } #endif [MenuItem("CONTEXT/UIScrollBar/Help")] static void ShowHelp10 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollBar)); } [MenuItem("CONTEXT/UIProgressBar/Help")] static void ShowHelp11 (MenuCommand command) { NGUIHelp.Show(typeof(UIProgressBar)); } [MenuItem("CONTEXT/UIPopupList/Help")] static void ShowHelp12 (MenuCommand command) { NGUIHelp.Show(typeof(UIPopupList)); } [MenuItem("CONTEXT/UIInput/Help")] static void ShowHelp13 (MenuCommand command) { NGUIHelp.Show(typeof(UIInput)); } [MenuItem("CONTEXT/UIKeyBinding/Help")] static void ShowHelp14 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyBinding)); } [MenuItem("CONTEXT/UIGrid/Help")] static void ShowHelp15 (MenuCommand command) { NGUIHelp.Show(typeof(UIGrid)); } [MenuItem("CONTEXT/UITable/Help")] static void ShowHelp16 (MenuCommand command) { NGUIHelp.Show(typeof(UITable)); } [MenuItem("CONTEXT/UIPlayTween/Help")] static void ShowHelp17 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayTween)); } [MenuItem("CONTEXT/UIPlayAnimation/Help")] static void ShowHelp18 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); } [MenuItem("CONTEXT/UIPlaySound/Help")] static void ShowHelp19 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlaySound)); } [MenuItem("CONTEXT/UIScrollView/Help")] static void ShowHelp20 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); } [MenuItem("CONTEXT/UIDragScrollView/Help")] static void ShowHelp21 (MenuCommand command) { NGUIHelp.Show(typeof(UIDragScrollView)); } [MenuItem("CONTEXT/UICenterOnChild/Help")] static void ShowHelp22 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnChild)); } [MenuItem("CONTEXT/UICenterOnClick/Help")] static void ShowHelp23 (MenuCommand command) { NGUIHelp.Show(typeof(UICenterOnClick)); } [MenuItem("CONTEXT/UITweener/Help")] [MenuItem("CONTEXT/UIPlayTween/Help")] static void ShowHelp24 (MenuCommand command) { NGUIHelp.Show(typeof(UITweener)); } [MenuItem("CONTEXT/ActiveAnimation/Help")] [MenuItem("CONTEXT/UIPlayAnimation/Help")] static void ShowHelp25 (MenuCommand command) { NGUIHelp.Show(typeof(UIPlayAnimation)); } [MenuItem("CONTEXT/UIScrollView/Help")] [MenuItem("CONTEXT/UIDragScrollView/Help")] static void ShowHelp26 (MenuCommand command) { NGUIHelp.Show(typeof(UIScrollView)); } [MenuItem("CONTEXT/UIPanel/Help")] static void ShowHelp27 (MenuCommand command) { NGUIHelp.Show(typeof(UIPanel)); } [MenuItem("CONTEXT/UILocalize/Help")] static void ShowHelp28 (MenuCommand command) { NGUIHelp.Show(typeof(UILocalize)); } [MenuItem("CONTEXT/Localization/Help")] static void ShowHelp29 (MenuCommand command) { NGUIHelp.Show(typeof(Localization)); } [MenuItem("CONTEXT/UIKeyNavigation/Help")] static void ShowHelp30 (MenuCommand command) { NGUIHelp.Show(typeof(UIKeyNavigation)); } [MenuItem("CONTEXT/PropertyBinding/Help")] static void ShowHelp31 (MenuCommand command) { NGUIHelp.Show(typeof(PropertyBinding)); } public delegate UIWidget AddFunc (GameObject go); static BetterList<string> mEntries = new BetterList<string>(); static GenericMenu mMenu; /// <summary> /// Clear the context menu list. /// </summary> static public void Clear () { mEntries.Clear(); mMenu = null; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddItem (string item, bool isChecked, GenericMenu.MenuFunction2 callback, object param) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.size; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, callback, param); } else AddDisabledItem(item); } /// <summary> /// Wrapper function called by the menu that in turn calls the correct callback. /// </summary> static public void AddChild (object obj) { AddFunc func = obj as AddFunc; UIWidget widget = func(Selection.activeGameObject); if (widget != null) Selection.activeGameObject = widget.gameObject; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddChildWidget (string item, bool isChecked, AddFunc callback) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.size; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, AddChild, callback); } else AddDisabledItem(item); } /// <summary> /// Wrapper function called by the menu that in turn calls the correct callback. /// </summary> static public void AddSibling (object obj) { AddFunc func = obj as AddFunc; UIWidget widget = func(Selection.activeTransform.parent.gameObject); if (widget != null) Selection.activeGameObject = widget.gameObject; } /// <summary> /// Add a new context menu entry. /// </summary> static public void AddSiblingWidget (string item, bool isChecked, AddFunc callback) { if (callback != null) { if (mMenu == null) mMenu = new GenericMenu(); int count = 0; for (int i = 0; i < mEntries.size; ++i) { string str = mEntries[i]; if (str == item) ++count; } mEntries.Add(item); if (count > 0) item += " [" + count + "]"; mMenu.AddItem(new GUIContent(item), isChecked, AddSibling, callback); } else AddDisabledItem(item); } /// <summary> /// Add commonly NGUI context menu options. /// </summary> static public void AddCommonItems (GameObject target) { if (target != null) { UIWidget widget = target.GetComponent<UIWidget>(); string myName = string.Format("Selected {0}", (widget != null) ? NGUITools.GetTypeName(widget) : "Object"); AddItem(myName + "/Bring to Front", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.BringForward(Selection.gameObjects[i]); }, null); AddItem(myName + "/Push to Back", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.PushBack(Selection.gameObjects[i]); }, null); AddItem(myName + "/Nudge Forward", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AdjustDepth(Selection.gameObjects[i], 1); }, null); AddItem(myName + "/Nudge Back", false, delegate(object obj) { for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AdjustDepth(Selection.gameObjects[i], -1); }, null); if (widget != null) { NGUIContextMenu.AddSeparator(myName + "/"); AddItem(myName + "/Make Pixel-Perfect", false, OnMakePixelPerfect, Selection.activeTransform); if (target.GetComponent<BoxCollider>() != null) { AddItem(myName + "/Reset Collider Size", false, OnBoxCollider, target); } } NGUIContextMenu.AddSeparator(myName + "/"); AddItem(myName + "/Delete", false, OnDelete, target); NGUIContextMenu.AddSeparator(""); if (Selection.activeTransform.parent != null && widget != null) { AddChildWidget("Create/Sprite/Child", false, NGUISettings.AddSprite); AddChildWidget("Create/Label/Child", false, NGUISettings.AddLabel); AddChildWidget("Create/Invisible Widget/Child", false, NGUISettings.AddWidget); AddChildWidget("Create/Simple Texture/Child", false, NGUISettings.AddTexture); #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 AddChildWidget("Create/Unity 2D Sprite/Child", false, NGUISettings.Add2DSprite); #endif AddSiblingWidget("Create/Sprite/Sibling", false, NGUISettings.AddSprite); AddSiblingWidget("Create/Label/Sibling", false, NGUISettings.AddLabel); AddSiblingWidget("Create/Invisible Widget/Sibling", false, NGUISettings.AddWidget); AddSiblingWidget("Create/Simple Texture/Sibling", false, NGUISettings.AddTexture); #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 AddSiblingWidget("Create/Unity 2D Sprite/Sibling", false, NGUISettings.Add2DSprite); #endif } else { AddChildWidget("Create/Sprite", false, NGUISettings.AddSprite); AddChildWidget("Create/Label", false, NGUISettings.AddLabel); AddChildWidget("Create/Invisible Widget", false, NGUISettings.AddWidget); AddChildWidget("Create/Simple Texture", false, NGUISettings.AddTexture); #if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 AddChildWidget("Create/Unity 2D Sprite", false, NGUISettings.Add2DSprite); #endif } NGUIContextMenu.AddSeparator("Create/"); AddItem("Create/Panel", false, AddPanel, target); AddItem("Create/Scroll View", false, AddScrollView, target); AddItem("Create/Grid", false, AddChild<UIGrid>, target); AddItem("Create/Table", false, AddChild<UITable>, target); AddItem("Create/Anchor (Legacy)", false, AddChild<UIAnchor>, target); if (target.GetComponent<UIPanel>() != null) { if (target.GetComponent<UIScrollView>() == null) { AddItem("Attach/Scroll View", false, Attach, typeof(UIScrollView)); NGUIContextMenu.AddSeparator("Attach/"); } } else if (target.collider == null) { AddItem("Attach/Box Collider", false, AttachCollider, null); NGUIContextMenu.AddSeparator("Attach/"); } bool header = false; UIScrollView scrollView = NGUITools.FindInParents<UIScrollView>(target); if (scrollView != null) { if (scrollView.GetComponentInChildren<UICenterOnChild>() == null) { AddItem("Attach/Center Scroll View on Child", false, Attach, typeof(UICenterOnChild)); header = true; } } if (target.collider != null) { if (scrollView != null) { if (target.GetComponent<UIDragScrollView>() == null) { AddItem("Attach/Drag Scroll View", false, Attach, typeof(UIDragScrollView)); header = true; } if (target.GetComponent<UICenterOnClick>() == null && NGUITools.FindInParents<UICenterOnChild>(target) != null) { AddItem("Attach/Center Scroll View on Click", false, Attach, typeof(UICenterOnClick)); header = true; } } if (header) NGUIContextMenu.AddSeparator("Attach/"); AddItem("Attach/Button Script", false, Attach, typeof(UIButton)); AddItem("Attach/Toggle Script", false, Attach, typeof(UIToggle)); AddItem("Attach/Slider Script", false, Attach, typeof(UISlider)); AddItem("Attach/Scroll Bar Script", false, Attach, typeof(UIScrollBar)); AddItem("Attach/Progress Bar Script", false, Attach, typeof(UISlider)); AddItem("Attach/Popup List Script", false, Attach, typeof(UIPopupList)); AddItem("Attach/Input Field Script", false, Attach, typeof(UIInput)); NGUIContextMenu.AddSeparator("Attach/"); if (target.GetComponent<UIDragResize>() == null) AddItem("Attach/Drag Resize Script", false, Attach, typeof(UIDragResize)); if (target.GetComponent<UIDragScrollView>() == null) { for (int i = 0; i < UIPanel.list.size; ++i) { UIPanel pan = UIPanel.list[i]; if (pan.clipping == UIDrawCall.Clipping.None) continue; UIScrollView dr = pan.GetComponent<UIScrollView>(); if (dr == null) continue; AddItem("Attach/Drag Scroll View", false, delegate(object obj) { target.AddComponent<UIDragScrollView>().scrollView = dr; }, null); header = true; break; } } AddItem("Attach/Key Binding Script", false, Attach, typeof(UIKeyBinding)); if (target.GetComponent<UIKeyNavigation>() == null) AddItem("Attach/Key Navigation Script", false, Attach, typeof(UIKeyNavigation)); NGUIContextMenu.AddSeparator("Attach/"); AddItem("Attach/Play Tween Script", false, Attach, typeof(UIPlayTween)); AddItem("Attach/Play Animation Script", false, Attach, typeof(UIPlayAnimation)); AddItem("Attach/Play Sound Script", false, Attach, typeof(UIPlaySound)); } AddItem("Attach/Property Binding", false, Attach, typeof(PropertyBinding)); if (target.GetComponent<UILocalize>() == null) AddItem("Attach/Localization Script", false, Attach, typeof(UILocalize)); if (widget != null) { AddMissingItem<TweenAlpha>(target, "Tween/Alpha"); AddMissingItem<TweenColor>(target, "Tween/Color"); AddMissingItem<TweenWidth>(target, "Tween/Width"); AddMissingItem<TweenHeight>(target, "Tween/Height"); } else if (target.GetComponent<UIPanel>() != null) { AddMissingItem<TweenAlpha>(target, "Tween/Alpha"); } NGUIContextMenu.AddSeparator("Tween/"); AddMissingItem<TweenPosition>(target, "Tween/Position"); AddMissingItem<TweenRotation>(target, "Tween/Rotation"); AddMissingItem<TweenScale>(target, "Tween/Scale"); AddMissingItem<TweenTransform>(target, "Tween/Transform"); if (target.GetComponent<AudioSource>() != null) AddMissingItem<TweenVolume>(target, "Tween/Volume"); if (target.GetComponent<Camera>() != null) { AddMissingItem<TweenFOV>(target, "Tween/Field of View"); AddMissingItem<TweenOrthoSize>(target, "Tween/Orthographic Size"); } } } /// <summary> /// Helper function that adds a widget collider to the specified object. /// </summary> static void AttachCollider (object obj) { if (Selection.activeGameObject != null) for (int i = 0; i < Selection.gameObjects.Length; ++i) NGUITools.AddWidgetCollider(Selection.gameObjects[i]); } /// <summary> /// Helper function that adds the specified type to all selected game objects. Used with the menu options above. /// </summary> static void Attach (object obj) { if (Selection.activeGameObject == null) return; System.Type type = (System.Type)obj; for (int i = 0; i < Selection.gameObjects.Length; ++i) { GameObject go = Selection.gameObjects[i]; if (go.GetComponent(type) != null) continue; #if !UNITY_3_5 Component cmp = go.AddComponent(type); Undo.RegisterCreatedObjectUndo(cmp, "Attach " + type); #endif } } /// <summary> /// Helper function. /// </summary> static void AddMissingItem<T> (GameObject target, string name) where T : MonoBehaviour { if (target.GetComponent<T>() == null) AddItem(name, false, Attach, typeof(T)); } /// <summary> /// Helper function for menu creation. /// </summary> static void AddChild<T> (object obj) where T : MonoBehaviour { GameObject go = obj as GameObject; T t = NGUITools.AddChild<T>(go); Selection.activeGameObject = t.gameObject; } /// <summary> /// Helper function for menu creation. /// </summary> static void AddPanel (object obj) { GameObject go = obj as GameObject; if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject; UIPanel panel = NGUISettings.AddPanel(go); Selection.activeGameObject = panel.gameObject; } /// <summary> /// Helper function for menu creation. /// </summary> static void AddScrollView (object obj) { GameObject go = obj as GameObject; if (go.GetComponent<UIWidget>() != null) go = go.transform.parent.gameObject; UIPanel panel = NGUISettings.AddPanel(go); panel.clipping = UIDrawCall.Clipping.SoftClip; panel.gameObject.AddComponent<UIScrollView>(); panel.name = "Scroll View"; Selection.activeGameObject = panel.gameObject; } /// <summary> /// Add help options based on the components present on the specified game object. /// </summary> static public void AddHelp (GameObject go, bool addSeparator) { MonoBehaviour[] comps = Selection.activeGameObject.GetComponents<MonoBehaviour>(); bool addedSomething = false; for (int i = 0; i < comps.Length; ++i) { System.Type type = comps[i].GetType(); string url = NGUIHelp.GetHelpURL(type); if (url != null) { if (addSeparator) { addSeparator = false; AddSeparator(""); } AddItem("Help/" + type, false, delegate(object obj) { Application.OpenURL(url); }, null); addedSomething = true; } } if (addedSomething) AddSeparator("Help/"); AddItem("Help/All Topics", false, delegate(object obj) { NGUIHelp.Show(); }, null); } static void OnHelp (object obj) { NGUIHelp.Show(obj); } static void OnMakePixelPerfect (object obj) { NGUITools.MakePixelPerfect(obj as Transform); } static void OnBoxCollider (object obj) { NGUITools.AddWidgetCollider(obj as GameObject); } static void OnDelete (object obj) { GameObject go = obj as GameObject; Selection.activeGameObject = go.transform.parent.gameObject; #if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 NGUITools.Destroy(go); #else Undo.DestroyObjectImmediate(go); #endif } /// <summary> /// Add a new disabled context menu entry. /// </summary> static public void AddDisabledItem (string item) { if (mMenu == null) mMenu = new GenericMenu(); mMenu.AddDisabledItem(new GUIContent(item)); } /// <summary> /// Add a separator to the menu. /// </summary> static public void AddSeparator (string path) { if (mMenu == null) mMenu = new GenericMenu(); // For some weird reason adding separators on OSX causes the entire menu to be disabled. Wtf? if (Application.platform != RuntimePlatform.OSXEditor) mMenu.AddSeparator(path); } /// <summary> /// Show the context menu with all the added items. /// </summary> static public void Show () { if (mMenu != null) { mMenu.ShowAsContext(); mMenu = null; mEntries.Clear(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Monitor.Management { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.Monitor; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ServiceDiagnosticSettingsOperations operations. /// </summary> internal partial class ServiceDiagnosticSettingsOperations : IServiceOperations<MonitorManagementClient>, IServiceDiagnosticSettingsOperations { /// <summary> /// Initializes a new instance of the ServiceDiagnosticSettingsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ServiceDiagnosticSettingsOperations(MonitorManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the MonitorManagementClient /// </summary> public MonitorManagementClient Client { get; private set; } /// <summary> /// Gets the active diagnostic settings for the specified resource. /// **WARNING**: This method will be deprecated in future releases. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> GetWithHttpMessagesAsync(string resourceUri, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Create or update new diagnostic settings for the specified resource. /// **WARNING**: This method will be deprecated in future releases. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='parameters'> /// Parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceUri, ServiceDiagnosticSettingsResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates an existing ServiceDiagnosticSettingsResource. To update other /// fields use the CreateOrUpdate method. **WARNING**: This method will be /// deprecated in future releases. /// </summary> /// <param name='resourceUri'> /// The identifier of the resource. /// </param> /// <param name='serviceDiagnosticSettingsResource'> /// Parameters supplied to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ServiceDiagnosticSettingsResource>> UpdateWithHttpMessagesAsync(string resourceUri, ServiceDiagnosticSettingsResourcePatch serviceDiagnosticSettingsResource, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceUri == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri"); } if (serviceDiagnosticSettingsResource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceDiagnosticSettingsResource"); } string apiVersion = "2016-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceUri", resourceUri); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("serviceDiagnosticSettingsResource", serviceDiagnosticSettingsResource); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/diagnosticSettings/service").ToString(); _url = _url.Replace("{resourceUri}", System.Uri.EscapeDataString(resourceUri)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(serviceDiagnosticSettingsResource != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(serviceDiagnosticSettingsResource, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServiceDiagnosticSettingsResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ServiceDiagnosticSettingsResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace EmployeeRegistration.FormsWeb { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Net.Sockets; using System.Threading; using Orleans.Runtime; namespace Orleans.Messaging { /// <summary> /// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages /// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway. /// /// Note that both sends and receives are synchronous. /// </summary> internal class GatewayConnection : OutgoingMessageSender { private readonly MessageFactory messageFactory; internal bool IsLive { get; private set; } internal ProxiedMessageCenter MsgCenter { get; private set; } private Uri addr; internal Uri Address { get { return addr; } private set { addr = value; Silo = addr.ToSiloAddress(); } } internal SiloAddress Silo { get; private set; } private readonly GatewayClientReceiver receiver; internal Socket Socket { get; private set; } // Shared by the receiver private DateTime lastConnect; internal GatewayConnection(Uri address, ProxiedMessageCenter mc, MessageFactory messageFactory) : base("GatewayClientSender_" + address, mc.MessagingConfiguration, mc.SerializationManager) { this.messageFactory = messageFactory; Address = address; MsgCenter = mc; receiver = new GatewayClientReceiver(this, mc.SerializationManager); lastConnect = new DateTime(); IsLive = true; } public override void Start() { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address); lock (Lockable) { if (State == ThreadState.Running) { return; } Connect(); if (!IsLive) return; // If the Connect succeeded receiver.Start(); base.Start(); } } public override void Stop() { IsLive = false; receiver.Stop(); base.Stop(); DrainQueue(RerouteMessage); MsgCenter.RuntimeClient.BreakOutstandingMessagesToDeadSilo(Silo); Socket s; lock (Lockable) { s = Socket; Socket = null; } if (s == null) return; CloseSocket(s); } // passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect. public void MarkAsDisconnected(Socket socket2Disconnect) { Socket s = null; lock (Lockable) { if (socket2Disconnect == null || Socket == null) return; if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock. { s = Socket; Socket = null; Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, String.Format("Marking gateway at address {0} as Disconnected", Address)); if ( MsgCenter != null && MsgCenter.GatewayManager != null) // We need a refresh... MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot(); } } if (s != null) { CloseSocket(s); } if (socket2Disconnect == s) return; CloseSocket(socket2Disconnect); } public void MarkAsDead() { Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, String.Format("Marking gateway at address {0} as Dead in my client local gateway list.", Address)); MsgCenter.GatewayManager.MarkAsDead(Address); Stop(); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] public void Connect() { if (!MsgCenter.Running) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address); return; } // Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time. // There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one // will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to... // Hopefully the initial "if" statement will prevent that. lock (Lockable) { if (!IsLive) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address); return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed. } for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++) { try { if (Socket != null) { if (Socket.Connected) return; MarkAsDisconnected(Socket); // clean up the socket before reconnecting. } if (lastConnect != new DateTime()) { // We already tried at least once in the past to connect to this GW. // If we are no longer connected to this GW and it is no longer in the list returned // from the GatewayProvider, consider directly this connection dead. if (!MsgCenter.GatewayManager.GetLiveGateways().Contains(Address)) break; // Wait at least ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY before reconnection tries var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect; if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY) { var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt; if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i); Thread.Sleep(wait); } } lastConnect = DateTime.UtcNow; Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); SocketManager.Connect(Socket, Silo.Endpoint, MsgCenter.MessagingConfiguration.OpenConnectionTimeout); NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionOpen(); SocketManager.WriteConnectionPreamble(Socket, MsgCenter.ClientId); // Identifies this client Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i); return; } catch (Exception ex) { Log.Warn(ErrorCode.ProxyClient_CannotConnect, $"Unable to connect to gateway at address {Address} on trial {i} (Exception: {ex.Message})"); MarkAsDisconnected(Socket); } } // Failed too many times -- give up MarkAsDead(); } } protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; } protected override bool PrepareMessageForSend(Message msg) { if (Cts == null) { return false; } // Check to make sure we're not stopped if (Cts.IsCancellationRequested) { // Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead MsgCenter.SendMessage(msg); return false; } if (msg.TargetSilo != null) return true; msg.TargetSilo = Silo; if (msg.TargetGrain.IsSystemTarget) msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo); return true; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error) { error = null; targetSilo = Silo; socketCapture = null; try { if (Socket == null || !Socket.Connected) { Connect(); } socketCapture = Socket; if (socketCapture == null || !socketCapture.Connected) { // Failed to connect -- Connect will have already declared this connection dead, so recycle the message return false; } } catch (Exception) { //No need to log any errors, as we alraedy do it inside Connect(). return false; } return true; } protected override void OnGetSendingSocketFailure(Message msg, string error) { msg.TargetSilo = null; // clear previous destination! MsgCenter.SendMessage(msg); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] protected override void OnMessageSerializationFailure(Message msg, Exception exc) { // we only get here if we failed to serialise the msg (or any other catastrophic failure). // Request msg fails to serialise on the sending silo, so we just enqueue a rejection msg. Log.Warn(ErrorCode.ProxyClient_SerializationError, String.Format("Unexpected error serializing message to gateway {0}.", Address), exc); FailMessage(msg, String.Format("Unexpected error serializing message to gateway {0}. {1}", Address, exc)); if (msg.Direction == Message.Directions.Request || msg.Direction == Message.Directions.OneWay) { return; } // Response msg fails to serialize on the responding silo, so we try to send an error response back. // if we failed sending an original response, turn the response body into an error and reply with it. msg.Result = Message.ResponseTypes.Error; msg.BodyObject = Response.ExceptionResponse(exc); try { MsgCenter.SendMessage(msg); } catch (Exception ex) { // If we still can't serialize, drop the message on the floor Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Unable to serialize message - DROPPING " + msg, ex); msg.ReleaseBodyAndHeaderBuffers(); } } protected override void OnSendFailure(Socket socket, SiloAddress targetSilo) { MarkAsDisconnected(socket); } protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr) { msg.ReleaseBodyAndHeaderBuffers(); if (sendError) { // We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it FailMessage(msg, sendErrorStr); } } protected override void FailMessage(Message msg, string reason) { msg.ReleaseBodyAndHeaderBuffers(); MessagingStatisticsGroup.OnFailedSentMessage(msg); if (MsgCenter.Running && msg.Direction == Message.Directions.Request) { if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); Message error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason); MsgCenter.QueueIncomingMessage(error); } else { Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnDroppedSentMessage(msg); } } private void RerouteMessage(Message msg) { msg.TargetActivation = null; msg.TargetSilo = null; MsgCenter.SendMessage(msg); } private void CloseSocket(Socket socket) { SocketManager.CloseSocket(socket); NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket(); MsgCenter.OnGatewayConnectionClosed(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>CampaignLabel</c> resource.</summary> public sealed partial class CampaignLabelName : gax::IResourceName, sys::IEquatable<CampaignLabelName> { /// <summary>The possible contents of <see cref="CampaignLabelName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </summary> CustomerCampaignLabel = 1, } private static gax::PathTemplate s_customerCampaignLabel = new gax::PathTemplate("customers/{customer_id}/campaignLabels/{campaign_id_label_id}"); /// <summary>Creates a <see cref="CampaignLabelName"/> 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="CampaignLabelName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static CampaignLabelName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CampaignLabelName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CampaignLabelName"/> with the pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CampaignLabelName"/> constructed from the provided ids.</returns> public static CampaignLabelName FromCustomerCampaignLabel(string customerId, string campaignId, string labelId) => new CampaignLabelName(ResourceNameType.CustomerCampaignLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignLabelName"/> with pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignLabelName"/> with pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </returns> public static string Format(string customerId, string campaignId, string labelId) => FormatCustomerCampaignLabel(customerId, campaignId, labelId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CampaignLabelName"/> with pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CampaignLabelName"/> with pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c>. /// </returns> public static string FormatCustomerCampaignLabel(string customerId, string campaignId, string labelId) => s_customerCampaignLabel.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignLabelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="campaignLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CampaignLabelName"/> if successful.</returns> public static CampaignLabelName Parse(string campaignLabelName) => Parse(campaignLabelName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CampaignLabelName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignLabelName">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="CampaignLabelName"/> if successful.</returns> public static CampaignLabelName Parse(string campaignLabelName, bool allowUnparsed) => TryParse(campaignLabelName, allowUnparsed, out CampaignLabelName 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="CampaignLabelName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="campaignLabelName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CampaignLabelName"/>, 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 campaignLabelName, out CampaignLabelName result) => TryParse(campaignLabelName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CampaignLabelName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="campaignLabelName">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="CampaignLabelName"/>, 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 campaignLabelName, bool allowUnparsed, out CampaignLabelName result) { gax::GaxPreconditions.CheckNotNull(campaignLabelName, nameof(campaignLabelName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignLabel.TryParseName(campaignLabelName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignLabel(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(campaignLabelName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private CampaignLabelName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string labelId = null) { Type = type; UnparsedResource = unparsedResourceName; CampaignId = campaignId; CustomerId = customerId; LabelId = labelId; } /// <summary> /// Constructs a new instance of a <see cref="CampaignLabelName"/> class from the component parts of pattern /// <c>customers/{customer_id}/campaignLabels/{campaign_id}~{label_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="labelId">The <c>Label</c> ID. Must not be <c>null</c> or empty.</param> public CampaignLabelName(string customerId, string campaignId, string labelId) : this(ResourceNameType.CustomerCampaignLabel, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), labelId: gax::GaxPreconditions.CheckNotNullOrEmpty(labelId, nameof(labelId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Label</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LabelId { 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.CustomerCampaignLabel: return s_customerCampaignLabel.Expand(CustomerId, $"{CampaignId}~{LabelId}"); 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 CampaignLabelName); /// <inheritdoc/> public bool Equals(CampaignLabelName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CampaignLabelName a, CampaignLabelName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CampaignLabelName a, CampaignLabelName b) => !(a == b); } public partial class CampaignLabel { /// <summary> /// <see cref="CampaignLabelName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal CampaignLabelName ResourceNameAsCampaignLabelName { get => string.IsNullOrEmpty(ResourceName) ? null : CampaignLabelName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } /// <summary><see cref="LabelName"/>-typed view over the <see cref="Label"/> resource name property.</summary> internal LabelName LabelAsLabelName { get => string.IsNullOrEmpty(Label) ? null : LabelName.Parse(Label, allowUnparsed: true); set => Label = value?.ToString() ?? ""; } } }
using J2N.Text; using Lucene.Net.Documents; using NUnit.Framework; using System; using System.Text.RegularExpressions; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using FieldType = FieldType; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using MockTokenizer = Lucene.Net.Analysis.MockTokenizer; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TextField = TextField; [TestFixture] public class TestSloppyPhraseQuery : LuceneTestCase { private static readonly Regex SPACES = new Regex(" +", RegexOptions.Compiled); private const string S_1 = "A A A"; private const string S_2 = "A 1 2 3 A 4 5 6 A"; private static readonly Document DOC_1 = MakeDocument("X " + S_1 + " Y"); private static readonly Document DOC_2 = MakeDocument("X " + S_2 + " Y"); private static readonly Document DOC_3 = MakeDocument("X " + S_1 + " A Y"); private static readonly Document DOC_1_B = MakeDocument("X " + S_1 + " Y N N N N " + S_1 + " Z"); private static readonly Document DOC_2_B = MakeDocument("X " + S_2 + " Y N N N N " + S_2 + " Z"); private static readonly Document DOC_3_B = MakeDocument("X " + S_1 + " A Y N N N N " + S_1 + " A Y"); private static readonly Document DOC_4 = MakeDocument("A A X A X B A X B B A A X B A A"); private static readonly Document DOC_5_3 = MakeDocument("H H H X X X H H H X X X H H H"); private static readonly Document DOC_5_4 = MakeDocument("H H H H"); private static readonly PhraseQuery QUERY_1 = MakePhraseQuery(S_1); private static readonly PhraseQuery QUERY_2 = MakePhraseQuery(S_2); private static readonly PhraseQuery QUERY_4 = MakePhraseQuery("X A A"); private static readonly PhraseQuery QUERY_5_4 = MakePhraseQuery("H H H H"); /// <summary> /// Test DOC_4 and QUERY_4. /// QUERY_4 has a fuzzy (len=1) match to DOC_4, so all slop values > 0 should succeed. /// But only the 3rd sequence of A's in DOC_4 will do. /// </summary> [Test] public virtual void TestDoc4_Query4_All_Slops_Should_match() { for (int slop = 0; slop < 30; slop++) { int numResultsExpected = slop < 1 ? 0 : 1; CheckPhraseQuery(DOC_4, QUERY_4, slop, numResultsExpected); } } /// <summary> /// Test DOC_1 and QUERY_1. /// QUERY_1 has an exact match to DOC_1, so all slop values should succeed. /// Before LUCENE-1310, a slop value of 1 did not succeed. /// </summary> [Test] public virtual void TestDoc1_Query1_All_Slops_Should_match() { for (int slop = 0; slop < 30; slop++) { float freq1 = CheckPhraseQuery(DOC_1, QUERY_1, slop, 1); float freq2 = CheckPhraseQuery(DOC_1_B, QUERY_1, slop, 1); Assert.IsTrue(freq2 > freq1, "slop=" + slop + " freq2=" + freq2 + " should be greater than score1 " + freq1); } } /// <summary> /// Test DOC_2 and QUERY_1. /// 6 should be the minimum slop to make QUERY_1 match DOC_2. /// Before LUCENE-1310, 7 was the minimum. /// </summary> [Test] public virtual void TestDoc2_Query1_Slop_6_or_more_Should_match() { for (int slop = 0; slop < 30; slop++) { int numResultsExpected = slop < 6 ? 0 : 1; float freq1 = CheckPhraseQuery(DOC_2, QUERY_1, slop, numResultsExpected); if (numResultsExpected > 0) { float freq2 = CheckPhraseQuery(DOC_2_B, QUERY_1, slop, 1); Assert.IsTrue(freq2 > freq1, "slop=" + slop + " freq2=" + freq2 + " should be greater than freq1 " + freq1); } } } /// <summary> /// Test DOC_2 and QUERY_2. /// QUERY_2 has an exact match to DOC_2, so all slop values should succeed. /// Before LUCENE-1310, 0 succeeds, 1 through 7 fail, and 8 or greater succeeds. /// </summary> [Test] public virtual void TestDoc2_Query2_All_Slops_Should_match() { for (int slop = 0; slop < 30; slop++) { float freq1 = CheckPhraseQuery(DOC_2, QUERY_2, slop, 1); float freq2 = CheckPhraseQuery(DOC_2_B, QUERY_2, slop, 1); Assert.IsTrue(freq2 > freq1, "slop=" + slop + " freq2=" + freq2 + " should be greater than freq1 " + freq1); } } /// <summary> /// Test DOC_3 and QUERY_1. /// QUERY_1 has an exact match to DOC_3, so all slop values should succeed. /// </summary> [Test] public virtual void TestDoc3_Query1_All_Slops_Should_match() { for (int slop = 0; slop < 30; slop++) { float freq1 = CheckPhraseQuery(DOC_3, QUERY_1, slop, 1); float freq2 = CheckPhraseQuery(DOC_3_B, QUERY_1, slop, 1); Assert.IsTrue(freq2 > freq1, "slop=" + slop + " freq2=" + freq2 + " should be greater than freq1 " + freq1); } } /// <summary> /// LUCENE-3412 </summary> [Test] public virtual void TestDoc5_Query5_Any_Slop_Should_be_consistent() { int nRepeats = 5; for (int slop = 0; slop < 3; slop++) { for (int trial = 0; trial < nRepeats; trial++) { // should steadily always find this one CheckPhraseQuery(DOC_5_4, QUERY_5_4, slop, 1); } for (int trial = 0; trial < nRepeats; trial++) { // should steadily never find this one CheckPhraseQuery(DOC_5_3, QUERY_5_4, slop, 0); } } } private float CheckPhraseQuery(Document doc, PhraseQuery query, int slop, int expectedNumResults) { query.Slop = slop; Directory ramDir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, ramDir, new MockAnalyzer(Random, MockTokenizer.WHITESPACE, false)); writer.AddDocument(doc); IndexReader reader = writer.GetReader(); IndexSearcher searcher = NewSearcher(reader); MaxFreqCollector c = new MaxFreqCollector(); searcher.Search(query, c); Assert.AreEqual(expectedNumResults, c.totalHits, "slop: " + slop + " query: " + query + " doc: " + doc + " Wrong number of hits"); //QueryUtils.Check(query,searcher); writer.Dispose(); reader.Dispose(); ramDir.Dispose(); // returns the max Scorer.Freq() found, because even though norms are omitted, many index stats are different // with these different tokens/distributions/lengths.. otherwise this test is very fragile. return c.max; } private static Document MakeDocument(string docText) { Document doc = new Document(); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.OmitNorms = true; Field f = new Field("f", docText, customType); doc.Add(f); return doc; } private static PhraseQuery MakePhraseQuery(string terms) { PhraseQuery query = new PhraseQuery(); string[] t = SPACES.Split(terms).TrimEnd(); for (int i = 0; i < t.Length; i++) { query.Add(new Term("f", t[i])); } return query; } internal class MaxFreqCollector : ICollector { internal float max; internal int totalHits; internal Scorer scorer; public virtual void SetScorer(Scorer scorer) { this.scorer = scorer; } public virtual void Collect(int doc) { totalHits++; max = Math.Max(max, scorer.Freq); } public virtual void SetNextReader(AtomicReaderContext context) { } public virtual bool AcceptsDocsOutOfOrder => false; } /// <summary> /// checks that no scores or freqs are infinite </summary> private void AssertSaneScoring(PhraseQuery pq, IndexSearcher searcher) { searcher.Search(pq, new CollectorAnonymousInnerClassHelper(this)); QueryUtils.Check( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, pq, searcher); } private class CollectorAnonymousInnerClassHelper : ICollector { private readonly TestSloppyPhraseQuery outerInstance; public CollectorAnonymousInnerClassHelper(TestSloppyPhraseQuery outerInstance) { this.outerInstance = outerInstance; } internal Scorer scorer; public virtual void SetScorer(Scorer scorer) { this.scorer = scorer; } public virtual void Collect(int doc) { Assert.IsFalse(float.IsInfinity(scorer.Freq)); Assert.IsFalse(float.IsInfinity(scorer.GetScore())); } public virtual void SetNextReader(AtomicReaderContext context) { // do nothing } public virtual bool AcceptsDocsOutOfOrder => false; } // LUCENE-3215 [Test] public virtual void TestSlopWithHoles() { Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.OmitNorms = true; Field f = new Field("lyrics", "", customType); Document doc = new Document(); doc.Add(f); f.SetStringValue("drug drug"); iw.AddDocument(doc); f.SetStringValue("drug druggy drug"); iw.AddDocument(doc); f.SetStringValue("drug druggy druggy drug"); iw.AddDocument(doc); f.SetStringValue("drug druggy drug druggy drug"); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); PhraseQuery pq = new PhraseQuery(); // "drug the drug"~1 pq.Add(new Term("lyrics", "drug"), 1); pq.Add(new Term("lyrics", "drug"), 4); pq.Slop = 0; Assert.AreEqual(0, @is.Search(pq, 4).TotalHits); pq.Slop = 1; Assert.AreEqual(3, @is.Search(pq, 4).TotalHits); pq.Slop = 2; Assert.AreEqual(4, @is.Search(pq, 4).TotalHits); ir.Dispose(); dir.Dispose(); } // LUCENE-3215 [Test] public virtual void TestInfiniteFreq1() { string document = "drug druggy drug drug drug"; Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewField("lyrics", document, new FieldType(TextField.TYPE_NOT_STORED))); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); PhraseQuery pq = new PhraseQuery(); // "drug the drug"~1 pq.Add(new Term("lyrics", "drug"), 1); pq.Add(new Term("lyrics", "drug"), 3); pq.Slop = 1; AssertSaneScoring(pq, @is); ir.Dispose(); dir.Dispose(); } // LUCENE-3215 [Test] public virtual void TestInfiniteFreq2() { string document = "So much fun to be had in my head " + "No more sunshine " + "So much fun just lying in my bed " + "No more sunshine " + "I can't face the sunlight and the dirt outside " + "Wanna stay in 666 where this darkness don't lie " + "Drug drug druggy " + "Got a feeling sweet like honey " + "Drug drug druggy " + "Need sensation like my baby " + "Show me your scars you're so aware " + "I'm not barbaric I just care " + "Drug drug drug " + "I need a reflection to prove I exist " + "No more sunshine " + "I am a victim of designer blitz " + "No more sunshine " + "Dance like a robot when you're chained at the knee " + "The C.I.A say you're all they'll ever need " + "Drug drug druggy " + "Got a feeling sweet like honey " + "Drug drug druggy " + "Need sensation like my baby " + "Snort your lines you're so aware " + "I'm not barbaric I just care " + "Drug drug druggy " + "Got a feeling sweet like honey " + "Drug drug druggy " + "Need sensation like my baby"; Directory dir = NewDirectory(); RandomIndexWriter iw = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewField("lyrics", document, new FieldType(TextField.TYPE_NOT_STORED))); iw.AddDocument(doc); IndexReader ir = iw.GetReader(); iw.Dispose(); IndexSearcher @is = NewSearcher(ir); PhraseQuery pq = new PhraseQuery(); // "drug the drug"~5 pq.Add(new Term("lyrics", "drug"), 1); pq.Add(new Term("lyrics", "drug"), 3); pq.Slop = 5; AssertSaneScoring(pq, @is); ir.Dispose(); dir.Dispose(); } } }
using System; using System.IO; using SharpChannels.Core.Contracts; using SharpChannels.Core.Messages; using SharpChannels.Core.Messages.System; using SharpChannels.Core.Security; using SharpChannels.Core.Serialization; using SharpChannels.Core.Serialization.System; namespace SharpChannels.Core.Channels { public abstract class ChannelBase : IChannel { private readonly object _readLock = new object(); private readonly object _writeLock = new object(); private bool _isHandShaken; private bool _isDisposed; protected abstract void CloseInternal(); private Stream _wrappedStream; private readonly Lazy<BinaryMessageWriter> _binaryMessageWriter; private readonly Lazy<BinaryMessageReader> _binaryMessageReader; protected abstract Stream GetStream(); protected virtual ISecurityWrapper SecurityWrapper => null; protected int MaxMessageLength { get; set; } public IMessageSerializer Serializer { get; protected set; } protected void RequestHandshake() { ThrowIfHandshaken(); var handshake = new Handshake(); if (!handshake.Request(this)) { CloseInternal(); throw new ProtocolException("Invalid handshake response", ProtocolErrorCode.InvalidHandshakeResponse); } _isHandShaken = true; } protected void ResponseHandshake() { ThrowIfHandshaken(); var handshake = new Handshake(); if (!handshake.Response(this)) { CloseInternal(); throw new ProtocolException("Invalid handshake request", ProtocolErrorCode.InvalidHandshakeRequest); } _isHandShaken = true; } private void ThrowIfHandshaken() { Enforce.State.FitsTo(!_isHandShaken, "Already handshaken"); } protected ChannelBase() { _binaryMessageWriter = new Lazy<BinaryMessageWriter>(() => new BinaryMessageWriter(GetWrappedStream())); _binaryMessageReader = new Lazy<BinaryMessageReader>(() => new BinaryMessageReader(GetWrappedStream())); } private Stream GetWrappedStream() { if (_wrappedStream == null) { var stream = GetStream(); _wrappedStream = SecurityWrapper == null ? stream : SecurityWrapper.Wrap(stream); } return _wrappedStream; } public abstract IEndpointData EndpointData { get; } protected abstract void OpenTransport(); public void Open() { Enforce.NotDisposed(this, _isDisposed); Enforce.State.FitsTo(!IsOpened, "Already opened"); OpenTransport(); RequestHandshake(); } public void Close() { Enforce.NotDisposed(this, _isDisposed); try { Send(EndSessionMessage.Instance, new EndSessionSerializer()); } catch (DataTransferException ex) when(ex.Code == DataTransferErrorCode.ChannelClosed) { } if(IsOpened) CloseInternal(); } public abstract bool IsOpened { get; } public string Name { get; set; } public void Send(IMessage message) { Send(message, Serializer); } private void WriteBinaryMessage(IBinaryMessageData binaryMessage) { try { lock (_writeLock) { _binaryMessageWriter.Value.Write(binaryMessage); } } catch (IOException ex) { ThrowChannelClosedIfNeeded(ex); CloseInternal(); throw; } } public void Send(IMessage message, IMessageSerializer serializer) { Enforce.NotDisposed(this, _isDisposed); Enforce.State.FitsTo(IsOpened, "Fail to send via closed channel"); var binaryMessage = serializer.Serialize(message); WriteBinaryMessage(binaryMessage); } public IMessage Receive() { return Receive(Serializer); } private void ThrowChannelClosedIfNeeded(Exception ex) { if (!IsOpened) throw new DataTransferException("Message channel is unexpectedly closed by the opposite side", DataTransferErrorCode.ChannelClosed, ex); } private void CheckMessageLength(int length) { if(length > MaxMessageLength) throw new ProtocolException($"Message is too long. Allowed {MaxMessageLength} bytes but {length} found", ProtocolErrorCode.MessageTooLong); } private IBinaryMessageData ReadBinaryMessage() { try { lock (_readLock) { return _binaryMessageReader.Value.Read(CheckMessageLength); } } catch (IOException ex) { ThrowChannelClosedIfNeeded(ex); CloseInternal(); throw; } } public IMessage Receive(IMessageSerializer serializer) { Enforce.NotDisposed(this, _isDisposed); Enforce.State.FitsTo(IsOpened, "Failed to receive message using closed channel"); var binaryMessage = ReadBinaryMessage(); try { switch (binaryMessage.Type) { case MessageType.EndSession: new EndSessionSerializer().Deserialize(binaryMessage); CloseInternal(); return null; case MessageType.User: if (!_isHandShaken) throw new ProtocolException("Handshake required", ProtocolErrorCode.HandshakeRequired); return serializer.Deserialize(binaryMessage); case MessageType.HandshakeRequest: case MessageType.HandshakeResponse: if (_isHandShaken) throw new ProtocolException("Unexpected message type", ProtocolErrorCode.UnexpectedMessageType); return serializer.Deserialize(binaryMessage); default: throw new ProtocolException("Unknown message type", ProtocolErrorCode.UnknownMessageType); } } catch { if (IsOpened) CloseInternal(); throw; } } protected virtual void Dispose(bool disposing) { _isDisposed = true; } public void Dispose() { if(_isDisposed) return; Dispose(true); GC.SuppressFinalize(this); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Compute { using System; using System.Collections.Generic; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Resource; using NUnit.Framework; /// <summary> /// Test for task and job adapter. /// </summary> public class FailoverTaskSelfTest : AbstractTaskTest { /** */ static volatile string _gridName; /** */ static volatile int _cnt; /// <summary> /// Constructor. /// </summary> public FailoverTaskSelfTest() : base(false) { } /// <summary> /// Constructor. /// </summary> /// <param name="fork">Fork flag.</param> protected FailoverTaskSelfTest(bool fork) : base(fork) { } /// <summary> /// Test for GridComputeJobFailoverException. /// </summary> [Test] public void TestClosureFailoverException() { for (int i = 0; i < 20; i++) { int res = Grid1.GetCompute().Call(new TestClosure()); Assert.AreEqual(2, res); Cleanup(); } } /// <summary> /// Test for GridComputeJobFailoverException with serializable job. /// </summary> [Test] public void TestTaskAdapterFailoverExceptionSerializable() { TestTaskAdapterFailoverException(true); } /// <summary> /// Test for GridComputeJobFailoverException with binary job. /// </summary> [Test] public void TestTaskAdapterFailoverExceptionBinarizable() { TestTaskAdapterFailoverException(false); } /// <summary> /// Test for GridComputeJobFailoverException. /// </summary> private void TestTaskAdapterFailoverException(bool serializable) { int res = Grid1.GetCompute().Execute(new TestTask(), new Tuple<bool, bool>(serializable, true)); Assert.AreEqual(2, res); Cleanup(); res = Grid1.GetCompute().Execute(new TestTask(), new Tuple<bool, bool>(serializable, false)); Assert.AreEqual(2, res); } /// <summary> /// Cleanup. /// </summary> [TearDown] public void Cleanup() { _cnt = 0; _gridName = null; } /** <inheritDoc /> */ override protected void GetBinaryTypeConfigurations(ICollection<BinaryTypeConfiguration> portTypeCfgs) { portTypeCfgs.Add(new BinaryTypeConfiguration(typeof(TestBinarizableJob))); } /// <summary> /// Test task. /// </summary> public class TestTask : ComputeTaskAdapter<Tuple<bool, bool>, int, int> { /** <inheritDoc /> */ override public IDictionary<IComputeJob<int>, IClusterNode> Map(IList<IClusterNode> subgrid, Tuple<bool, bool> arg) { Assert.AreEqual(2, subgrid.Count); Tuple<bool, bool> t = arg; bool serializable = t.Item1; bool local = t.Item2; IDictionary<IComputeJob<int>, IClusterNode> jobs = new Dictionary<IComputeJob<int>, IClusterNode>(); IComputeJob<int> job; if (serializable) job = new TestSerializableJob(); else job = new TestBinarizableJob(); foreach (IClusterNode node in subgrid) { bool add = local ? node.IsLocal : !node.IsLocal; if (add) { jobs.Add(job, node); break; } } Assert.AreEqual(1, jobs.Count); return jobs; } /** <inheritDoc /> */ override public int Reduce(IList<IComputeJobResult<int>> results) { Assert.AreEqual(1, results.Count); return results[0].Data; } } /// <summary> /// /// </summary> [Serializable] class TestClosure : IComputeFunc<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Invoke() { return FailoverJob(_grid); } } /// <summary> /// /// </summary> [Serializable] class TestSerializableJob : IComputeJob<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Execute() { return FailoverJob(_grid); } /** <inheritDoc /> */ public void Cancel() { // No-op. } } /// <summary> /// /// </summary> class TestBinarizableJob : IComputeJob<int> { [InstanceResource] private readonly IIgnite _grid = null; /** <inheritDoc /> */ public int Execute() { return FailoverJob(_grid); } public void Cancel() { // No-op. } } /// <summary> /// Throws GridComputeJobFailoverException on first call. /// </summary> private static int FailoverJob(IIgnite grid) { Assert.NotNull(grid); _cnt++; if (_gridName == null) { _gridName = grid.Name; throw new ComputeJobFailoverException("Test error."); } Assert.AreNotEqual(_gridName, grid.Name); return _cnt; } } }
namespace PrimWorkshop { partial class frmBrowser { /// <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() { GlacialComponents.Controls.GLColumn glColumn1 = new GlacialComponents.Controls.GLColumn(); GlacialComponents.Controls.GLColumn glColumn2 = new GlacialComponents.Controls.GLColumn(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.glControl = new Tao.Platform.Windows.SimpleOpenGlControl(); this.panel1 = new System.Windows.Forms.Panel(); this.txtPass = new System.Windows.Forms.TextBox(); this.txtLast = new System.Windows.Forms.TextBox(); this.txtFirst = new System.Windows.Forms.TextBox(); this.cmdLogin = new System.Windows.Forms.Button(); this.lstDownloads = new GlacialComponents.Controls.GlacialList(); this.progPrims = new System.Windows.Forms.ProgressBar(); this.lblPrims = new System.Windows.Forms.Label(); this.cboServer = new System.Windows.Forms.ComboBox(); this.panel2 = new System.Windows.Forms.Panel(); this.txtSim = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.txtX = new System.Windows.Forms.TextBox(); this.txtY = new System.Windows.Forms.TextBox(); this.txtZ = new System.Windows.Forms.TextBox(); this.cmdTeleport = new System.Windows.Forms.Button(); this.tableLayoutPanel1.SuspendLayout(); this.panel1.SuspendLayout(); this.panel2.SuspendLayout(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.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.tableLayoutPanel1.ColumnCount = 3; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 130F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 175F)); this.tableLayoutPanel1.Controls.Add(this.glControl, 0, 0); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.lstDownloads, 0, 3); this.tableLayoutPanel1.Controls.Add(this.progPrims, 1, 1); this.tableLayoutPanel1.Controls.Add(this.lblPrims, 0, 1); this.tableLayoutPanel1.Controls.Add(this.panel2, 2, 0); this.tableLayoutPanel1.Location = new System.Drawing.Point(1, 1); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 4; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 45F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 120F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(799, 612); this.tableLayoutPanel1.TabIndex = 0; // // glControl // this.glControl.AccumBits = ((byte)(0)); this.glControl.AutoCheckErrors = false; this.glControl.AutoFinish = false; this.glControl.AutoMakeCurrent = true; this.glControl.AutoSwapBuffers = true; this.glControl.BackColor = System.Drawing.Color.Black; this.glControl.ColorBits = ((byte)(32)); this.tableLayoutPanel1.SetColumnSpan(this.glControl, 2); this.glControl.DepthBits = ((byte)(16)); this.glControl.Dock = System.Windows.Forms.DockStyle.Fill; this.glControl.Location = new System.Drawing.Point(3, 3); this.glControl.Name = "glControl"; this.glControl.Size = new System.Drawing.Size(618, 411); this.glControl.StencilBits = ((byte)(0)); this.glControl.TabIndex = 7; this.glControl.TabStop = false; this.glControl.MouseMove += new System.Windows.Forms.MouseEventHandler(this.glControl_MouseMove); this.glControl.MouseClick += new System.Windows.Forms.MouseEventHandler(this.glControl_MouseClick); this.glControl.MouseDown += new System.Windows.Forms.MouseEventHandler(this.glControl_MouseDown); this.glControl.Resize += new System.EventHandler(this.glControl_Resize); this.glControl.MouseUp += new System.Windows.Forms.MouseEventHandler(this.glControl_MouseUp); // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.SetColumnSpan(this.panel1, 2); this.panel1.Controls.Add(this.cboServer); this.panel1.Controls.Add(this.txtPass); this.panel1.Controls.Add(this.txtLast); this.panel1.Controls.Add(this.txtFirst); this.panel1.Controls.Add(this.cmdLogin); this.panel1.Location = new System.Drawing.Point(3, 450); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(618, 39); this.panel1.TabIndex = 8; // // txtPass // this.txtPass.Location = new System.Drawing.Point(215, 11); this.txtPass.Name = "txtPass"; this.txtPass.Size = new System.Drawing.Size(100, 20); this.txtPass.TabIndex = 2; this.txtPass.UseSystemPasswordChar = true; this.txtPass.Enter += new System.EventHandler(this.txtLogin_Enter); // // txtLast // this.txtLast.Location = new System.Drawing.Point(109, 11); this.txtLast.Name = "txtLast"; this.txtLast.Size = new System.Drawing.Size(100, 20); this.txtLast.TabIndex = 1; this.txtLast.Enter += new System.EventHandler(this.txtLogin_Enter); // // txtFirst // this.txtFirst.Location = new System.Drawing.Point(3, 11); this.txtFirst.Name = "txtFirst"; this.txtFirst.Size = new System.Drawing.Size(100, 20); this.txtFirst.TabIndex = 0; this.txtFirst.Enter += new System.EventHandler(this.txtLogin_Enter); // // cmdLogin // this.cmdLogin.Location = new System.Drawing.Point(321, 9); this.cmdLogin.Name = "cmdLogin"; this.cmdLogin.Size = new System.Drawing.Size(75, 23); this.cmdLogin.TabIndex = 3; this.cmdLogin.Text = "Login"; this.cmdLogin.UseVisualStyleBackColor = true; this.cmdLogin.Click += new System.EventHandler(this.cmdLogin_Click); // // lstDownloads // this.lstDownloads.AllowColumnResize = true; this.lstDownloads.AllowMultiselect = false; this.lstDownloads.AlternateBackground = System.Drawing.Color.DarkGreen; this.lstDownloads.AlternatingColors = false; this.lstDownloads.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.lstDownloads.AutoHeight = true; this.lstDownloads.BackColor = System.Drawing.SystemColors.ControlLightLight; this.lstDownloads.BackgroundStretchToFit = true; glColumn1.ActivatedEmbeddedType = GlacialComponents.Controls.GLActivatedEmbeddedTypes.None; glColumn1.CheckBoxes = false; glColumn1.ImageIndex = -1; glColumn1.Name = "colTextureID"; glColumn1.NumericSort = false; glColumn1.Text = "Texture ID"; glColumn1.TextAlignment = System.Drawing.ContentAlignment.MiddleLeft; glColumn1.Width = 220; glColumn2.ActivatedEmbeddedType = GlacialComponents.Controls.GLActivatedEmbeddedTypes.None; glColumn2.CheckBoxes = false; glColumn2.ImageIndex = -1; glColumn2.Name = "colProgress"; glColumn2.NumericSort = false; glColumn2.Text = "Download Progress"; glColumn2.TextAlignment = System.Drawing.ContentAlignment.MiddleLeft; glColumn2.Width = 220; this.lstDownloads.Columns.AddRange(new GlacialComponents.Controls.GLColumn[] { glColumn1, glColumn2}); this.tableLayoutPanel1.SetColumnSpan(this.lstDownloads, 2); this.lstDownloads.ControlStyle = GlacialComponents.Controls.GLControlStyles.Normal; this.lstDownloads.FullRowSelect = true; this.lstDownloads.GridColor = System.Drawing.Color.LightGray; this.lstDownloads.GridLines = GlacialComponents.Controls.GLGridLines.gridBoth; this.lstDownloads.GridLineStyle = GlacialComponents.Controls.GLGridLineStyles.gridSolid; this.lstDownloads.GridTypes = GlacialComponents.Controls.GLGridTypes.gridOnExists; this.lstDownloads.HeaderHeight = 22; this.lstDownloads.HeaderVisible = true; this.lstDownloads.HeaderWordWrap = false; this.lstDownloads.HotColumnTracking = false; this.lstDownloads.HotItemTracking = false; this.lstDownloads.HotTrackingColor = System.Drawing.Color.LightGray; this.lstDownloads.HoverEvents = false; this.lstDownloads.HoverTime = 1; this.lstDownloads.ImageList = null; this.lstDownloads.ItemHeight = 17; this.lstDownloads.ItemWordWrap = false; this.lstDownloads.Location = new System.Drawing.Point(3, 495); this.lstDownloads.Name = "lstDownloads"; this.lstDownloads.Selectable = true; this.lstDownloads.SelectedTextColor = System.Drawing.Color.White; this.lstDownloads.SelectionColor = System.Drawing.Color.DarkBlue; this.lstDownloads.ShowBorder = true; this.lstDownloads.ShowFocusRect = false; this.lstDownloads.Size = new System.Drawing.Size(618, 114); this.lstDownloads.SortType = GlacialComponents.Controls.SortTypes.InsertionSort; this.lstDownloads.SuperFlatHeaderColor = System.Drawing.Color.White; this.lstDownloads.TabIndex = 9; this.lstDownloads.Text = "Texture Downloads"; // // progPrims // this.progPrims.Dock = System.Windows.Forms.DockStyle.Fill; this.progPrims.Location = new System.Drawing.Point(133, 420); this.progPrims.Name = "progPrims"; this.progPrims.Size = new System.Drawing.Size(488, 24); this.progPrims.TabIndex = 10; // // lblPrims // this.lblPrims.Anchor = System.Windows.Forms.AnchorStyles.Left; this.lblPrims.AutoSize = true; this.lblPrims.Location = new System.Drawing.Point(3, 425); this.lblPrims.Name = "lblPrims"; this.lblPrims.Size = new System.Drawing.Size(61, 13); this.lblPrims.TabIndex = 11; this.lblPrims.Text = "Prims: 0 / 0"; // // cboServer // this.cboServer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cboServer.FormattingEnabled = true; this.cboServer.Location = new System.Drawing.Point(405, 11); this.cboServer.Name = "cboServer"; this.cboServer.Size = new System.Drawing.Size(204, 21); this.cboServer.TabIndex = 4; // // panel2 // this.panel2.Controls.Add(this.cmdTeleport); this.panel2.Controls.Add(this.txtZ); this.panel2.Controls.Add(this.txtY); this.panel2.Controls.Add(this.txtX); this.panel2.Controls.Add(this.label5); this.panel2.Controls.Add(this.label4); this.panel2.Controls.Add(this.label3); this.panel2.Controls.Add(this.label2); this.panel2.Controls.Add(this.txtSim); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(627, 3); this.panel2.Name = "panel2"; this.tableLayoutPanel1.SetRowSpan(this.panel2, 4); this.panel2.Size = new System.Drawing.Size(169, 606); this.panel2.TabIndex = 12; // // txtSim // this.txtSim.Location = new System.Drawing.Point(36, 8); this.txtSim.Name = "txtSim"; this.txtSim.Size = new System.Drawing.Size(126, 20); this.txtSim.TabIndex = 1; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 11); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(27, 13); this.label2.TabIndex = 2; this.label2.Text = "Sim:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(5, 37); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(17, 13); this.label3.TabIndex = 3; this.label3.Text = "X:"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(58, 37); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(17, 13); this.label4.TabIndex = 4; this.label4.Text = "Y:"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(112, 37); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(17, 13); this.label5.TabIndex = 5; this.label5.Text = "Z:"; // // txtX // this.txtX.Location = new System.Drawing.Point(24, 34); this.txtX.MaxLength = 3; this.txtX.Name = "txtX"; this.txtX.Size = new System.Drawing.Size(30, 20); this.txtX.TabIndex = 6; this.txtX.Text = "128"; // // txtY // this.txtY.Location = new System.Drawing.Point(78, 34); this.txtY.MaxLength = 3; this.txtY.Name = "txtY"; this.txtY.Size = new System.Drawing.Size(30, 20); this.txtY.TabIndex = 7; this.txtY.Text = "128"; // // txtZ // this.txtZ.Location = new System.Drawing.Point(132, 34); this.txtZ.MaxLength = 3; this.txtZ.Name = "txtZ"; this.txtZ.Size = new System.Drawing.Size(30, 20); this.txtZ.TabIndex = 8; this.txtZ.Text = "0"; // // cmdTeleport // this.cmdTeleport.Enabled = false; this.cmdTeleport.Location = new System.Drawing.Point(87, 60); this.cmdTeleport.Name = "cmdTeleport"; this.cmdTeleport.Size = new System.Drawing.Size(75, 23); this.cmdTeleport.TabIndex = 9; this.cmdTeleport.Text = "Teleport"; this.cmdTeleport.UseVisualStyleBackColor = true; this.cmdTeleport.Click += new System.EventHandler(this.cmdTeleport_Click); // // frmBrowser // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 612); this.Controls.Add(this.tableLayoutPanel1); this.Name = "frmBrowser"; this.Text = "World Browser"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmBrowser_FormClosing); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private Tao.Platform.Windows.SimpleOpenGlControl glControl; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TextBox txtPass; private System.Windows.Forms.TextBox txtLast; private System.Windows.Forms.TextBox txtFirst; private System.Windows.Forms.Button cmdLogin; private GlacialComponents.Controls.GlacialList lstDownloads; private System.Windows.Forms.ProgressBar progPrims; private System.Windows.Forms.Label lblPrims; private System.Windows.Forms.ComboBox cboServer; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.TextBox txtZ; private System.Windows.Forms.TextBox txtY; private System.Windows.Forms.TextBox txtX; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txtSim; private System.Windows.Forms.Button cmdTeleport; } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.IO; using Jovian.Communication; namespace Jovian.Server { public class UserModel { public string Name; public List<object> Buffer; public UserModel(string s) { Name = s; Buffer = new List<object>(); } } public class Address { public string App; public string Service; public string Dir; public string ID; public Address(string key) { App = ""; Service = ""; Dir = ""; ID = ""; string[] x = key.Split(new char[] { '/' }); if (x.Length > 0) { App = x[0]; if (x.Length > 1) { Service = x[1]; if (x.Length > 2) { ID = x[x.Length - 1]; for (int k = 2; k < x.Length - 1; k++) { if (k > 2) Dir += x[k]; Dir += x[k]; } } } } } public string KeyInApp() { string x = Service.ToLower(); if (Dir.Length > 0) x += "/" + Dir.ToLower(); x += "/" + ID; return x; } } public class ResourceLock { public string Key; public UserModel WhoOwns; } public class ServerModel : IChannel { private SortedList<string, UserModel> Users; private SortedList<string, ResourceLock> Locks; private TCPServer Server; Jovian.Data.ApplicationSet DATA; #region The Basic Operations private void Load() { DATA = new Jovian.Data.ApplicationSet(); if (!File.Exists("apps.xml")) return; StreamReader sr = new StreamReader("apps.xml"); string xml = sr.ReadToEnd(); sr.Close(); DATA = Jovian.Data.Jovian_Data.BuildObjectTable(xmljr.XmlJrDom.Read(xml, null), null).LookUpObject(1) as Jovian.Data.ApplicationSet; } public void Backup() { try { string aM = ("0" + DateTime.Now.Month);aM = aM.Substring(aM.Length - 2); string aD = ("0" + DateTime.Now.Day);aD = aD.Substring(aD.Length - 2); string aH = ("0" + DateTime.Now.Hour);aH = aH.Substring(aH.Length - 2); string aMi = ("0" + DateTime.Now.Minute);aMi = aMi.Substring(aMi.Length - 2); string aMs = ("000" + DateTime.Now.Millisecond);aMs = aMs.Substring(aMs.Length - 4); string STAMP = "backups\\" + DateTime.Now.Year + aM + aD; string CODE = STAMP + "\\" + aH + aMi + aMs; if (!Directory.Exists("backups")) Directory.CreateDirectory("backups"); if (!Directory.Exists(STAMP)) Directory.CreateDirectory(STAMP); xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); DATA.WriteXML(writ); StreamWriter sw = new StreamWriter(CODE + "_apps.xml"); sw.Write(writ.GetXML()); sw.Flush(); sw.Close(); } catch(Exception EX) { string zztop = EX.ToString(); } } private void Save() { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); DATA.WriteXML(writ); StreamWriter sw = new StreamWriter("apps.xml"); sw.Write(writ.GetXML()); sw.Flush(); sw.Close(); } public void Start(int Port) { Load(); Users = new SortedList<string, UserModel>(); Locks = new SortedList<string, ResourceLock>(); Server = new TCPServer(this); Server.Start(Port); } public void Shutdown() { Save(); Server.Stop(); } #endregion #region Communication and File System private void Broadcast(object o) { foreach (UserModel um in Users.Values) { um.Buffer.Add(o); } } private void OnNewApplication(UserModel um, packet_NewApplication pna) { Backup(); Broadcast(new packet_UserMessage("Registry", um.Name + " has created a new application named " + pna.name)); Jovian.Data.Application A = new Jovian.Data.Application(); A.Name = pna.name; int k = 1; foreach (Jovian.Data.Application p in DATA._Applications) k = System.Math.Max(k, p.UniqueCode + 1); A.UniqueCode = k; DATA._Applications = Jovian.Data.Manipulation<Jovian.Data.Application>.ExtendByOne(DATA._Applications, A); Broadcast(new packet_RegistryPush(pna.name)); } private void Lock(UserModel um, string key) { if (IsLocked(key)) return; ResourceLock rl = new ResourceLock(); rl.Key = key; rl.WhoOwns = um; Locks.Add(key, rl); } private void Unlock(UserModel um, string key) { if (IsLocked(key)) Locks.Remove(key); } private bool IsLocked(string key) { return Locks.ContainsKey(key); } private Jovian.Data.Application GetApplication(string name) { foreach (Jovian.Data.Application A in DATA._Applications) { if (A.Name.ToLower().Equals(name.ToLower())) { A.Dirty = true; return A; } } return null; } private string ServiceByObject(Jovian.Data.IdentifiedObject obj) { if (obj is Data.TextFile) return (obj as Data.TextFile).Service; if (obj is Data.DataObject) return "data objects"; if (obj is Data.Layer) { if ((obj as Data.Layer).IsVisualEncoder) { return "visual encoders"; } return "layers"; } return "unk"; } private string GetKey(Jovian.Data.IdentifiedObject obj) { string x = "" + obj.Service + ""; if (obj.Directory.Length > 0) x += "/" + obj.Directory.ToLower(); x += "/" + obj._ID.ToLower(); return x; } private Jovian.Data.IdentifiedObject FindAndMaybeMerge(Jovian.Data.Application App, string key, Jovian.Data.IdentifiedObject obj, bool Merge) { Jovian.Data.IdentifiedObject[] IOARR = App._Registry; for (int k = 0; k < IOARR.Length; k++) { Jovian.Data.IdentifiedObject io = IOARR[k]; string io_key = GetKey(io); if (io_key.Equals(key)) { if (Merge) { //Console.WriteLine("Overwriting"); IOARR[k] = obj; if (obj == null) { App._Registry = Jovian.Data.Manipulation<Jovian.Data.IdentifiedObject>.FilterNull(App._Registry); Broadcast(new packet_RegistryDelete(App.Name.ToLower() + "/" + key)); } else { obj.Service = ServiceByObject(obj); packet_RegistryRename prr = new packet_RegistryRename(App.Name.ToLower() + "/" + key, App.Name.ToLower() + "/" + GetKey(obj)); if (!prr.keyFrom.Equals(prr.keyTo)) Broadcast(prr); } } return io; } } if (Merge && obj != null) { App._Registry = Data.Manipulation<Jovian.Data.IdentifiedObject>.ExtendByOne(IOARR, obj); Broadcast(new packet_RegistryPush(App.Name.ToLower() + "/" + GetKey(obj))); } return null; } private string FixDirectory(string x) { string d = x; while (d.Length > 0 && d[0] == '/') d = d.Substring(1); while (d.Length > 0 && d[d.Length - 1] == '/') d = d.Substring(0, d.Length - 1); return d; } private bool WriteObject(UserModel um, Jovian.Data.Application App, Address Addr, Jovian.Data.IdentifiedObject obj, bool create) { Backup(); obj.Service = obj.Service.ToLower().Trim(); obj.Directory = FixDirectory(obj.Directory.ToLower().Trim()); obj._ID = obj.ID.ToLower().Trim(); string LookingKey = Addr.KeyInApp(); if (create) { Jovian.Data.IdentifiedObject ioz = FindAndMaybeMerge(App, GetKey(obj), obj, false); //Console.WriteLine("WriteO:Create " + ioz + ":" + GetKey(obj)); if (ioz != null) { //Console.WriteLine("Duplicate Key On Creation"); return false; } } FindAndMaybeMerge(App, LookingKey, obj, true); /* if() { FindAndMaybeMerge(App, LookingKey, obj, true); return true; } */ return true; } private void OnSave(UserModel um, packet_Save ps) { Address A = new Address(ps.key); Jovian.Data.Application App = GetApplication(A.App); if (App == null) return; if (ps.release) { // Console.WriteLine("releasing lock"); Unlock(um, ps.key); } Jovian.Data.IdentifiedObject io = Jovian.Data.Jovian_Data.BuildObjectTable(xmljr.XmlJrDom.Read(ps.xml, null), null).LookUpObject(1) as Jovian.Data.IdentifiedObject; if (A.Service.Equals("state model")) { Data.TextFile tf = io as Jovian.Data.TextFile; App.Model = tf._Contents.Trim(); return; } if (A.Service.Equals("linking")) { Data.TextFile tf = io as Jovian.Data.TextFile; App.Linking = tf._Contents.Trim(); return; } if (!WriteObject(um, App, A, io, ps.create)) { um.Buffer.Add(new packet_UserMessage("Error", A.KeyInApp() + " could not be created")); } } private void OnCheckout(UserModel um, packet_CheckOut pco) { Address A = new Address(pco.key); Jovian.Data.Application App = GetApplication(A.App); if (App == null) return; App._Name = App._Name.ToLower(); // can check out if (IsLocked(pco.key)) { um.Buffer.Add(new packet_UserMessage("Key Master", Locks[pco.key].WhoOwns.Name + " has a lock on " + pco.key)); Locks[pco.key].WhoOwns.Buffer.Add(new packet_UserMessage("Key Master", um.Name + " is requesting a lock on " + pco.key)); return; } // Console.WriteLine("obtaining lock"); Lock(um, pco.key); if (A.Service.Equals("state model")) { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); Data.TextFile tf = new Jovian.Data.TextFile(); //tf._Contents = App. tf._Contents = App.Model; tf._Service = "state model"; tf.WriteXML(writ); um.Buffer.Add(new packet_Deliver(pco.key, writ.GetXML())); return; } if (A.Service.Equals("linking")) { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); Data.TextFile tf = new Jovian.Data.TextFile(); //tf._Contents = App. tf._Contents = App.Linking; tf._Service = "linking"; tf.WriteXML(writ); um.Buffer.Add(new packet_Deliver(pco.key, writ.GetXML())); return; } Jovian.Data.IdentifiedObject io = FindAndMaybeMerge(App, A.KeyInApp(), null, false); if (io != null) { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); io.WriteXML(writ); um.Buffer.Add(new packet_Deliver(pco.key, writ.GetXML())); } else { Unlock(um, pco.key); } } public void DeleteApplication(string app) { Backup(); Broadcast(new packet_RegistryDeleteApp(app)); for (int k = 0; k < DATA._Applications.Length; k++) { if (DATA._Applications[k].Name.ToLower().Equals(app)) { xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); DATA._Applications[k].WriteXML(writ); if(!Directory.Exists("backups")) Directory.CreateDirectory("backups"); if(!Directory.Exists("backups\\deletes")) Directory.CreateDirectory("backups\\deletes"); string aM = ("0" + DateTime.Now.Month);aM = aM.Substring(aM.Length - 2); string aD = ("0" + DateTime.Now.Day);aD = aD.Substring(aD.Length - 2); string aH = ("0" + DateTime.Now.Hour);aH = aH.Substring(aH.Length - 2); string aMi = ("0" + DateTime.Now.Minute);aMi = aMi.Substring(aMi.Length - 2); string aMs = ("000" + DateTime.Now.Millisecond);aMs = aMs.Substring(aMs.Length - 4); string STAMP = app + "_" + DateTime.Now.Year + aM + aD + aH + aMi + aMs; StreamWriter sw = new StreamWriter("backups\\deletes\\" + STAMP + ".xml"); sw.Write(writ.GetXML()); sw.Flush(); sw.Close(); DATA._Applications[k] = null; } } DATA._Applications = Jovian.Data.Manipulation<Jovian.Data.Application>.FilterNull(DATA._Applications); } private void OnImport(UserModel um, packet_ImportApp ia) { if(GetApplication(ia.App)!=null) return; Jovian.Data.Application a = Jovian.Data.Jovian_Data.BuildObjectTable(xmljr.XmlJrDom.Read(ia.XML, null), null).LookUpObject(1) as Jovian.Data.Application; a.Name = ia.App; if(a==null) return; Backup(); DATA._Applications = Jovian.Data.Manipulation<Jovian.Data.Application>.ExtendByOne(DATA._Applications, a); BroadCastApplication(a); } private void OnExport(UserModel um, string app) { Jovian.Data.Application a = GetApplication(app); if(a==null) return; xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); a.WriteXML(writ); packet_ExportedApp PE = new packet_ExportedApp(); PE.App = app; PE.XML = writ.GetXML(); um.Buffer.Add(PE); } private void OnDelete(UserModel um, packet_RegistryDelete pd) { Address A = new Address(pd.key); Jovian.Data.Application App = GetApplication(A.App); if (App == null) return; App._Name = App._Name.ToLower(); if (pd.key.Equals(A.App)) { bool locked = false; foreach (ResourceLock rl in Locks.Values) { if (rl.Key.Substring(0,A.App.Length).ToLower().Equals(A.App)) { locked = true; um.Buffer.Add(new packet_UserMessage("Registry", "Application:" + pd.key + " is being edited by " + rl.WhoOwns.Name)); } } if(!locked) { DeleteApplication(A.App); Broadcast( new packet_UserMessage("Registry", "Application:" + pd.key + " has been slain")); } } else { Jovian.Data.IdentifiedObject io = FindAndMaybeMerge(App, A.KeyInApp(), null, true); } } private void OnRegistryRename(UserModel um, packet_RegistryRename prr) { Address A = new Address(prr.keyFrom); Address A2 = new Address(prr.keyTo); if (IsLocked(prr.keyFrom)) { um.Buffer.Add(new packet_UserMessage("Key Master", prr.keyFrom + " is locked (can not rename)")); return; } Jovian.Data.Application App = GetApplication(A.App); if (App == null) return; App._Name = App._Name.ToLower(); if (prr.keyFrom.Equals(A.App)) { if (!prr.keyFrom.Equals(prr.keyTo)) { bool locked = false; foreach (ResourceLock rl in Locks.Values) { if (rl.Key.Substring(0,A.App.Length).ToLower().Equals(A.App)) { locked = true; um.Buffer.Add(new packet_UserMessage("Registry", "Application:" + A.App + " is being edited by " + rl.WhoOwns.Name)); } } if (!locked) { string X = prr.keyTo.Split(new char[] { '/' })[0].Trim().ToLower(); if (X.Length < 2) { um.Buffer.Add(new packet_UserMessage("Registry", "Could not rename (too small)")); return; } foreach (Jovian.Data.Application Az in DATA._Applications) { if (Az.Name.Equals(X)) { um.Buffer.Add(new packet_UserMessage("Registry", "Could not rename")); return; } } if(!Directory.Exists("apps\\" + X)) Directory.CreateDirectory("apps\\" + X); if(!Directory.Exists("apps\\" + X + "\\images")) Directory.CreateDirectory("apps\\" + X + "\\images"); if (Directory.Exists("apps\\" + App.Name + "\\images")) { string[] F = Directory.GetFiles("apps\\" + App.Name + "\\images"); if (F != null) { if (F.Length > 0) { foreach (string f in F) { string f2 = f.Replace("apps\\" + App.Name + "\\images", "apps\\" + X + "\\images"); if (!File.Exists(f2)) File.Copy(f, f2); } } } } App.Name = X; Broadcast(new packet_RegistryRename(prr.keyFrom, App.Name)); } } return; } Jovian.Data.IdentifiedObject io = FindAndMaybeMerge(App, A.KeyInApp(), null, false); Jovian.Data.IdentifiedObject io2 = FindAndMaybeMerge(App, A2.KeyInApp(), null, false); if (io2 != null) { um.Buffer.Add(new packet_UserMessage("Renamer", prr.keyFrom + " => " + prr.keyTo + " can not be done.")); return; } if (io != null && io2 == null) { A2.Dir = FixDirectory(A2.Dir).Trim().ToLower(); A2.ID = A2.ID.Trim().ToLower(); io._Directory = A2.Dir; io._ID = A2.ID; A2.Service = ServiceByObject(io); string oldKey = A.App + "/" + GetKey(io); string newKey = A.App + "/" + A2.KeyInApp(); // Console.WriteLine("From: " + prr.keyFrom + " => " + newKey); // Console.WriteLine("--" + GetKey(io)); if (!prr.keyFrom.Equals(newKey)) Broadcast(new packet_RegistryRename(prr.keyFrom, newKey)); } } private void BroadCastApplication(Jovian.Data.Application A) { Broadcast(new packet_RegistryPush(A.Name)); foreach (Data.IdentifiedObject io in A.Registry) { string keySuffix = io.Directory; if (keySuffix.Length > 0) keySuffix += "/"; string key = A.Name + "/" + ServiceByObject(io) + "/" + keySuffix + io.ID; Broadcast(new packet_RegistryPush(key)); } } private void DumpRegistry(UserModel um) { for (int k = 0; k < DATA._Applications.Length; k++) { string App = DATA._Applications[k].Name; um.Buffer.Add(new packet_RegistryPush(App)); foreach (Data.IdentifiedObject io in DATA._Applications[k]._Registry) { string keySuffix = io.Directory; if (keySuffix.Length > 0) keySuffix += "/"; string key = App + "/" + ServiceByObject(io) + "/" + keySuffix + io.ID; um.Buffer.Add(new packet_RegistryPush(key)); } } } #endregion // if (obj is packet_Search) { OnSearch(um, obj as packet_Search); } private void OnSearch(UserModel um, packet_Search ps) { um.Buffer.Add(new packet_UserMessage("Search","Start[" + ps.Param + "]")); foreach(Jovian.Data.Application App in DATA._Applications) { if (ps.App.Equals("*") || App.Name.Equals(ps.Param)) { foreach (Jovian.Data.IdentifiedObject io in App._Registry) { string src = ""; if (io is Jovian.Data.TextFile) { src = (io as Jovian.Data.TextFile)._Contents; } if (io is Jovian.Data.DataObject) { src = (io as Jovian.Data.DataObject)._SqlRead; } if (io is Jovian.Data.Layer) { Jovian.Data.Layer L = (io as Jovian.Data.Layer); foreach (Jovian.Data.Control C in L.Controls) { if (C is Jovian.Data.Button) { src += (C as Jovian.Data.Button).InnerCode; src += (C as Jovian.Data.Button)._StyleActivated; src += (C as Jovian.Data.Button)._StyleDisabled; } if (C is Jovian.Data.TextPanel) src += (C as Jovian.Data.TextPanel).InnerCode; if (C is Jovian.Data.StyledControl) src += (C as Jovian.Data.LayerPanel)._StyleNormal; } } if (src.IndexOf(ps.Param) >= 0) { um.Buffer.Add(new packet_UserMessage("Search", App._Name + "/" + io._Service + "/" + io._Directory + "/" + io._ID + "")); } } } } um.Buffer.Add(new packet_UserMessage("Search","End[" + ps.Param + "]")); } private void OnDirty() { List<Jovian.Data.Application> apps = new List<Jovian.Data.Application>(); int k = 1; foreach (Jovian.Data.Application A in DATA._Applications) { A.UniqueCode = A.UniqueCode = k; k++; apps.Add(A); A.Dirty = true; } apps.Sort(new cmpAPP()); k = 0; foreach (Jovian.Data.Application a in apps) { DATA._Applications[k] = a; k++; } } class cmpAPP : IComparer<Jovian.Data.Application> { public int Compare(Jovian.Data.Application x, Jovian.Data.Application y) { return String.Compare(x.Name, y.Name); } } private void OnCompile(UserModel um, packet_Complie pc) { Backup(); if(pc.Optimize) Broadcast( new packet_UserMessage("Compiler", um.Name + " has started compiling [RELEASE]")); else Broadcast( new packet_UserMessage("Compiler", um.Name + " has started compiling [DEBUG]")); if (pc.Optimize) { OnDirty(); foreach (Jovian.Data.Application a in DATA._Applications) a._ReleaseVersion++; } xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null); DATA.WriteXML(writ); Jovian.Data.ApplicationSet CLONE = Jovian.Data.Jovian_Data.BuildObjectTable(xmljr.XmlJrDom.Read(writ.GetXML(), null), null).LookUpObject(1) as Jovian.Data.ApplicationSet; SortedDictionary<string, Compiler.CompilerExport> exports = new SortedDictionary<string,Jovian.Compiler.CompilerExport>(); foreach(Jovian.Data.Application A in CLONE._Applications) { if (A.Dirty) { try { exports.Add(A.Name, Jovian.Compiler.Master.BuildApplication(A, CLONE._Applications)); Broadcast( new packet_UserMessage("Compiler", "" + A.Name + " (" + A.Version + ") built")); } catch (Exception ez) { Broadcast( new packet_UserMessage("Compiler", "" + A.Name + " (" + A.Version + ") failed:" + ez.ToString() )); } } } if (!Directory.Exists("apps")) Directory.CreateDirectory("apps"); StreamWriter JSr = new StreamWriter("apps/registry.js"); JSr.WriteLine("AppRegistry = {"); StreamWriter PHPr = new StreamWriter("apps/registry.php"); bool First = true; foreach (Jovian.Data.Application A in DATA._Applications) { Jovian.Compiler.Master.BuildRegistryEntry(JSr, PHPr, A, First); if (A.Dirty) { if(exports.ContainsKey(A.Name)) { Compiler.CompilerExport ce = exports[A.Name]; if (ce != null) { A.CascadePool = new Jovian.Data.ExportedCSS[ce.Classes.Keys.Count]; int k = 0; foreach (string x in ce.Classes.Keys) { A.CascadePool[k] = new Jovian.Data.ExportedCSS(); A.CascadePool[k]._Style = x; A.CascadePool[k]._OutputName = ce.AppName + "_" + (ce.Classes[x]).ToString("X").ToLower();; k++; } } } A.Version++; } First = false; A.Dirty = false; } JSr.WriteLine(); JSr.WriteLine("};"); JSr.Flush(); JSr.Close(); PHPr.Flush(); PHPr.Close(); } private void OnGetCSS(UserModel um, string app) { Jovian.Data.Application A = GetApplication(app); if (A == null) return; string css = ""; string pcss = ""; foreach (Jovian.Data.IdentifiedObject io in A._Registry) { if (io is Jovian.Data.TextFile) { Jovian.Data.TextFile tf = io as Jovian.Data.TextFile; if (tf.Service.Equals("css")) { css += tf._Contents; } if (tf.Service.Equals("parametric css")) { pcss += tf.Contents; } } } um.Buffer.Add(new packet_DeliverCSS(app, css, pcss)); } private void OnImageTransit(UserModel um, packet_ImageTransit it) { if (!Directory.Exists("apps\\" + it.App + "\\images")) Directory.CreateDirectory("apps\\" + it.App + "\\images"); it.bmp.Save("apps\\" + it.App + "\\images\\" + it.Filename); } private void OnImageCheck(UserModel um, packet_ImageCheck ic) { string x = Compiler.ImagePath.GetPath(ic.App, ic.Filename); if (x.Length > 0) { System.Drawing.Bitmap B1 = new System.Drawing.Bitmap(x); packet_ImageInformation ii = new packet_ImageInformation(ic.App,ic.Filename,B1.Width,B1.Height); B1.Dispose(); um.Buffer.Add(ii); } } public bool Deploying = false; private void OnPackaging(UserModel um) { if (Deploying) { um.Buffer.Add(new packet_UserMessage("Deploy!", "Sorry, already deploying")); return; } Deploying = true; /* Build the Deployment Script for Application -> When this script runs, a batch file will be created */ StreamWriter sw = new StreamWriter("apps/build.bat"); sw.WriteLine("@del *.tar"); foreach (Jovian.Data.Application A in DATA._Applications) { sw.WriteLine("@cd " + A.Name); sw.WriteLine("@tar -cvf ..\\" + A.Name + ".tar exe.js lang-*.js *.php *.css Z"); sw.WriteLine("@cd .."); } sw.WriteLine("@mkdir __apps__"); sw.WriteLine("@cd __apps__"); sw.WriteLine("@mkdir apps"); sw.WriteLine("@move ..\\*.tar apps"); sw.WriteLine("@copy ..\\*.inc apps"); sw.WriteLine("@copy ..\\*.php apps"); sw.WriteLine("@copy ..\\*.js apps"); sw.WriteLine("@copy ..\\*.css apps"); sw.WriteLine("@cd apps"); foreach (Jovian.Data.Application A in DATA._Applications) { sw.WriteLine("@mkdir " + A.Name); sw.WriteLine("@cd " + A.Name); sw.WriteLine("@tar -xvf ..\\" + A.Name + ".tar"); sw.WriteLine("@del ..\\" + A.Name + ".tar"); sw.WriteLine("@cd .."); } sw.WriteLine("@cd .."); sw.WriteLine("del ..\\..\\_staging\\apps.tar"); sw.WriteLine("@tar -cvf ..\\..\\_staging\\apps.tar apps"); sw.WriteLine("@cd .."); sw.WriteLine("@del /Q /F /S __apps__"); sw.WriteLine("@rmdir /Q /S __apps__"); sw.WriteLine("@cd ..\\deploy"); sw.WriteLine("@tar -xvf apps.tar"); sw.WriteLine("@del apps.tar"); sw.WriteLine("@cd ..\\apps"); sw.Flush(); sw.Close(); sw = new StreamWriter("BuildDeploy.bat"); sw.WriteLine("del FULLDEPLOY.tar"); sw.WriteLine("mkdir _staging"); sw.WriteLine("cd apps"); sw.WriteLine("call build.bat"); sw.WriteLine("cd .."); sw.WriteLine("del build_*.js"); sw.WriteLine("cd kernel"); sw.WriteLine("call build.bat"); sw.WriteLine("cd .."); sw.WriteLine("cd controls"); sw.WriteLine("call build.bat"); sw.WriteLine("cd .."); sw.WriteLine("cd _staging"); sw.WriteLine("tar -xvf apps.tar"); sw.WriteLine("del apps.tar"); sw.WriteLine("@copy ..\\*.inc ."); sw.WriteLine("@copy ..\\*.php ."); sw.WriteLine("@copy ..\\*.js ."); sw.WriteLine("@copy ..\\*.css ."); sw.WriteLine("del ..\\FULLDEPLOY.tar"); sw.WriteLine("tar -cvf ../FULLDEPLOY.tar *.*"); sw.Flush(); sw.Close(); /* sw.WriteLine("del ../deploy.tar"); sw.WriteLine("tar -cvf ../deploy.tar *.tar spicy.bat"); foreach (Jovian.Data.Application A in DATA._Applications) { sw.WriteLine("del " + A.Name + ".tar"); } sx.Flush(); sx.Close(); */ Thread t = new Thread(new ParameterizedThreadStart(DeployIT)); t.Start(this); } public static void DeployIT(object o) { ServerModel sm = o as ServerModel; try { System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "DeployIT"; proc.StartInfo.Arguments = ""; proc.Start(); proc.WaitForExit(); } catch (Exception er) { throw er; } sm.Deploying = false; } public void doBusinessWizard(UserModel um, packet_BusinessWiz bw) { Jovian.Data.Application App = GetApplication(bw.App); if (App == null) return; string aM = ("0" + DateTime.Now.Month);aM = aM.Substring(aM.Length - 2); string aD = ("0" + DateTime.Now.Day);aD = aD.Substring(aD.Length - 2); string aH = ("0" + DateTime.Now.Hour);aH = aH.Substring(aH.Length - 2); string aMi = ("0" + DateTime.Now.Minute);aMi = aMi.Substring(aMi.Length - 2); string aMs = ("000" + DateTime.Now.Millisecond);aMs = aMs.Substring(aMs.Length - 4); string STAMP = "" + DateTime.Now.Year + aM + aD + aH + aMi + aMs; StringWriter _JS = new StringWriter(); StringWriter _BL = new StringWriter(); bw.Name = bw.Name.ToLower().Trim(); if (new Compiler.BusinessWizard(App.Name.Trim().ToLower() + "{" + App._Model + "}", bw.Group, bw.Commands, _JS, _BL, bw.Name).run()) { Jovian.Data.TextFile js = new Jovian.Data.TextFile(); js._Service = "javascript"; js._ID = bw.Name; js._Contents = _JS.ToString(); js._Directory = ""; Jovian.Data.TextFile bz = new Jovian.Data.TextFile(); bz._Service = "business logic"; bz._ID = bw.Name; bz._Contents = _BL.ToString(); bz._Directory = ""; App._Registry = Data.Manipulation<Jovian.Data.IdentifiedObject>.ExtendByOne(App._Registry, js); Broadcast(new packet_RegistryPush(App.Name.ToLower() + "/" + GetKey(js))); App._Registry = Data.Manipulation<Jovian.Data.IdentifiedObject>.ExtendByOne(App._Registry, bz); Broadcast(new packet_RegistryPush(App.Name.ToLower() + "/" + GetKey(bz))); } } public void doLayerWizard(UserModel um, packet_LayerWiz lw) { Jovian.Data.Application App = GetApplication(lw.App); if (App == null) return; Jovian.Data.Layer L = new Jovian.Data.Layer(); Jovian.Data.IdentifiedObject io = new Jovian.Data.IdentifiedObject(); L._Directory = ""; string aM = ("0" + DateTime.Now.Month);aM = aM.Substring(aM.Length - 2); string aD = ("0" + DateTime.Now.Day);aD = aD.Substring(aD.Length - 2); string aH = ("0" + DateTime.Now.Hour);aH = aH.Substring(aH.Length - 2); string aMi = ("0" + DateTime.Now.Minute);aMi = aMi.Substring(aMi.Length - 2); string aMs = ("000" + DateTime.Now.Millisecond);aMs = aMs.Substring(aMs.Length - 4); string STAMP = "" + DateTime.Now.Year + aM + aD + aH + aMi + aMs; L._ID = "auto_" + lw.Group + "_" + STAMP; L.Service = "layers"; L.Width = 800; L.Height = 800; if (new Jovian.Compiler.LayerWizard(App.Name.Trim().ToLower() + "{" + App._Model + "}",L, lw.Group, lw.Commands).run()) { //Jovian.Data.IdentifiedObject io = Jovian.Data.Jovian_Data.BuildObjectTable(xmljr.XmlJrDom.Read(ps.xml, null), null).LookUpObject(1) as Jovian.Data.IdentifiedObject; App._Registry = Data.Manipulation<Jovian.Data.IdentifiedObject>.ExtendByOne(App._Registry, L); Broadcast(new packet_RegistryPush(App.Name.ToLower() + "/" + GetKey(L))); } } void IChannel.OnObject(IClient from, object obj) { if (!(from is TCPClient)) return; TCPClient client = from as TCPClient; try { UserModel um = null; if (obj is packet_UserLogin) { packet_UserLogin p = obj as packet_UserLogin; um = new UserModel(p.username); um.Buffer.Add(new packet_UserMessage("Jove", "Welcome to Jove3")); //Broadcast(new packet_UserMessage("Jove",p.username + ", DISCIPLE OF JEFF, has entered our domain")); int March = 0; while (Users.ContainsKey(um.Name + "(" + March + ")")) { March++; } um.Name += "(" + March + ")"; Users.Add(um.Name, um); DumpRegistry(um); client.setData(um); } um = client.getData() as UserModel; if (um == null) return; try { // process the object if (!(obj is packet_UserPing)) { //Console.WriteLine("Server Got: " + obj.ToString()); //System.Windows.Forms.MessageBox.Show(":" + obj.ToString()); } if (obj is packet_CheckOut) OnCheckout(um, obj as packet_CheckOut); if (obj is packet_RegistryDelete) OnDelete(um, obj as packet_RegistryDelete); if (obj is packet_Save) OnSave(um, obj as packet_Save); if (obj is packet_RegistryRename) OnRegistryRename(um, obj as packet_RegistryRename); if (obj is packet_NewApplication) OnNewApplication(um, obj as packet_NewApplication); if (obj is packet_Message) { Broadcast(new packet_UserMessage(um.Name, (obj as packet_Message).msg)); } if (obj is packet_Complie) { OnCompile(um, obj as packet_Complie); } if (obj is packet_Search) { OnSearch(um, obj as packet_Search); } if (obj is packet_GetCSS) { OnGetCSS(um, (obj as packet_GetCSS).app); } if (obj is packet_ImageTransit) { OnImageTransit(um, (obj as packet_ImageTransit)); } if (obj is packet_ImageCheck) { OnImageCheck(um, (obj as packet_ImageCheck)); } if (obj is packet_Dirty) { OnDirty(); } if (obj is packet_InitPackage) { OnPackaging(um); } if (obj is packet_ExportAppRequest) { OnExport(um, (obj as packet_ExportAppRequest).App); } if (obj is packet_ImportApp) { OnImport(um, obj as packet_ImportApp); } if (obj is packet_DumpReq) { DumpRegistry(um); } if (obj is packet_LayerWiz) { doLayerWizard(um, obj as packet_LayerWiz); } if (obj is packet_BusinessWiz) { doBusinessWizard(um, obj as packet_BusinessWiz); } } catch (Exception err) { Broadcast(new packet_UserMessage("Router", " I have failed: " + err.ToString())); } if (um.Buffer.Count > 0) { List<object> ToSend = um.Buffer; um.Buffer = new List<object>(); foreach (object o in ToSend) client.WriteObject(o); } } catch (Exception err) { string zztop = err.ToString(); } // throw new Exception("The method or operation is not implemented."); } void IChannel.OnClose(IClient whom) { if (!(whom is TCPClient)) return; TCPClient client = whom as TCPClient; UserModel um = client.getData() as UserModel; if (um == null) return; //Console.WriteLine("Releasing Locks for: " + um.Name); List<string> K = new List<string>(); foreach (ResourceLock rl in Locks.Values) { if (rl.WhoOwns == um) { Broadcast(new packet_UserMessage("Locksmith", rl.Key + " was released due to dead client (" + um.Name + ")")); K.Add(rl.Key); } } foreach (string x in K) { Unlock(um, x); } Users.Remove(um.Name); } void IChannel.OnConnect(IClient whom) { if (!(whom is TCPClient)) return; TCPClient client = whom as TCPClient; //Console.WriteLine("New client"); // throw new Exception("The method or operation is not implemented."); } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// An offer to sell an item\u2014for example, an offer to sell a product, the DVD of a movie, or tickets to an event. /// </summary> public class Offer_Core : TypeCore, IIntangible { public Offer_Core() { this._TypeId = 189; this._Id = "Offer"; this._Schema_Org_Url = "http://schema.org/Offer"; string label = ""; GetLabel(out label, "Offer", typeof(Offer_Core)); this._Label = label; this._Ancestors = new int[]{266,138}; this._SubTypes = new int[]{12}; this._SuperTypes = new int[]{138}; this._Properties = new int[]{67,108,143,229,10,25,119,122,165,166,168,199,204}; } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The availability of this item\u2014for example In stock, Out of stock, Pre-order, etc. /// </summary> private Availability_Core availability; public Availability_Core Availability { get { return availability; } set { availability = value; SetPropertyInstance(availability); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// The condition of the item for sale\u2014for example New, Refurbished, Used, etc. /// </summary> private ItemCondition_Core itemCondition; public ItemCondition_Core ItemCondition { get { return itemCondition; } set { itemCondition = value; SetPropertyInstance(itemCondition); } } /// <summary> /// The item being sold. /// </summary> private ItemOffered_Core itemOffered; public ItemOffered_Core ItemOffered { get { return itemOffered; } set { itemOffered = value; SetPropertyInstance(itemOffered); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The offer price of the product. /// </summary> private Price_Core price; public Price_Core Price { get { return price; } set { price = value; SetPropertyInstance(price); } } /// <summary> /// The currency (in 3-letter <a href=\http://en.wikipedia.org/wiki/ISO_4217\>ISO 4217 format</a>) of the offer price. /// </summary> private PriceCurrency_Core priceCurrency; public PriceCurrency_Core PriceCurrency { get { return priceCurrency; } set { priceCurrency = value; SetPropertyInstance(priceCurrency); } } /// <summary> /// The date after which the price is no longer available. /// </summary> private PriceValidUntil_Core priceValidUntil; public PriceValidUntil_Core PriceValidUntil { get { return priceValidUntil; } set { priceValidUntil = value; SetPropertyInstance(priceValidUntil); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The seller of the product. /// </summary> private Seller_Core seller; public Seller_Core Seller { get { return seller; } set { seller = value; SetPropertyInstance(seller); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// 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.CodeAnalysis; using System.Diagnostics.Contracts; namespace System.Globalization { /*=================================JapaneseCalendar========================== ** ** JapaneseCalendar is based on Gregorian calendar. The month and day values are the same as ** Gregorian calendar. However, the year value is an offset to the Gregorian ** year based on the era. ** ** This system is adopted by Emperor Meiji in 1868. The year value is counted based on the reign of an emperor, ** and the era begins on the day an emperor ascends the throne and continues until his death. ** The era changes at 12:00AM. ** ** For example, the current era is Heisei. It started on 1989/1/8 A.D. Therefore, Gregorian year 1989 is also Heisei 1st. ** 1989/1/8 A.D. is also Heisei 1st 1/8. ** ** Any date in the year during which era is changed can be reckoned in either era. For example, ** 1989/1/1 can be 1/1 Heisei 1st year or 1/1 Showa 64th year. ** ** Note: ** The DateTime can be represented by the JapaneseCalendar are limited to two factors: ** 1. The min value and max value of DateTime class. ** 2. The available era information. ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1868/09/08 9999/12/31 ** Japanese Meiji 01/01 Heisei 8011/12/31 ============================================================================*/ [Serializable] public partial class JapaneseCalendar : Calendar { internal static readonly DateTime calendarMinValue = new DateTime(1868, 9, 8); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // // Using a field initializer rather than a static constructor so that the whole class can be lazy // init. internal static volatile EraInfo[] japaneseEraInfo; // // Read our era info // // m_EraInfo must be listed in reverse chronological order. The most recent era // should be the first element. // That is, m_EraInfo[0] contains the most recent era. // // We know about 4 built-in eras, however users may add additional era(s) from the // registry, by adding values to HKLM\SYSTEM\CurrentControlSet\Control\Nls\Calendars\Japanese\Eras // we don't read the registry and instead we call WinRT to get the needed informatio // // Registry values look like: // yyyy.mm.dd=era_abbrev_english_englishabbrev // // Where yyyy.mm.dd is the registry value name, and also the date of the era start. // yyyy, mm, and dd are the year, month & day the era begins (4, 2 & 2 digits long) // era is the Japanese Era name // abbrev is the Abbreviated Japanese Era Name // english is the English name for the Era (unused) // englishabbrev is the Abbreviated English name for the era. // . is a delimiter, but the value of . doesn't matter. // '_' marks the space between the japanese era name, japanese abbreviated era name // english name, and abbreviated english names. // internal static EraInfo[] GetEraInfo() { // See if we need to build it if (japaneseEraInfo == null) { japaneseEraInfo = GetJapaneseEras(); // See if we have to use the built-in eras if (japaneseEraInfo == null) { // We know about some built-in ranges EraInfo[] defaultEraRanges = new EraInfo[4]; defaultEraRanges[0] = new EraInfo(4, 1989, 1, 8, 1988, 1, GregorianCalendar.MaxYear - 1988, "\x5e73\x6210", "\x5e73", "H"); // era #4 start year/month/day, yearOffset, minEraYear defaultEraRanges[1] = new EraInfo(3, 1926, 12, 25, 1925, 1, 1989 - 1925, "\x662d\x548c", "\x662d", "S"); // era #3,start year/month/day, yearOffset, minEraYear defaultEraRanges[2] = new EraInfo(2, 1912, 7, 30, 1911, 1, 1926 - 1911, "\x5927\x6b63", "\x5927", "T"); // era #2,start year/month/day, yearOffset, minEraYear defaultEraRanges[3] = new EraInfo(1, 1868, 1, 1, 1867, 1, 1912 - 1867, "\x660e\x6cbb", "\x660e", "M"); // era #1,start year/month/day, yearOffset, minEraYear // Remember the ranges we built japaneseEraInfo = defaultEraRanges; } } // return the era we found/made return japaneseEraInfo; } internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of JapaneseCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new JapaneseCalendar(); } return (s_defaultInstance); } public JapaneseCalendar() { try { new CultureInfo("ja-JP"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().ToString(), e); } helper = new GregorianCalendarHelper(this, GetEraInfo()); } internal override CalendarId ID { get { return CalendarId.JAPAN; } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } /*=================================GetDaysInMonth========================== **Action: Returns the number of days in the month given by the year and month arguments. **Returns: The number of days in the given month. **Arguments: ** year The year in Japanese calendar. ** month The month ** era The Japanese era value. **Exceptions ** ArgumentException If month is less than 1 or greater * than 12. ============================================================================*/ public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } /*=================================GetEra========================== **Action: Get the era value of the specified time. **Returns: The era value for the specified time. **Arguments: ** time the specified date time. **Exceptions: ArgumentOutOfRangeException if time is out of the valid era ranges. ============================================================================*/ public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } // For Japanese calendar, four digit year is not used. Few emperors will live for more than one hundred years. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, helper.MaxYear)); } return (year); } public override int[] Eras { get { return (helper.Eras); } } // // Return the various era strings // Note: The arrays are backwards of the eras // internal static String[] EraNames() { EraInfo[] eras = GetEraInfo(); String[] eraNames = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. eraNames[i] = eras[eras.Length - i - 1].eraName; } return eraNames; } internal static String[] AbbrevEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasAbbrev = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasAbbrev[i] = eras[eras.Length - i - 1].abbrevEraName; } return erasAbbrev; } internal static String[] EnglishEraNames() { EraInfo[] eras = GetEraInfo(); String[] erasEnglish = new String[eras.Length]; for (int i = 0; i < eras.Length; i++) { // Strings are in chronological order, eras are backwards order. erasEnglish[i] = eras[eras.Length - i - 1].englishEraName; } return erasEnglish; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; internal override bool IsValidYear(int year, int era) { return helper.IsValidYear(year, era); } public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.LogicalTree; using Avalonia.UnitTests; using Avalonia.VisualTree; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests.Presenters { /// <summary> /// Tests for ContentControls that are hosted in a control template. /// </summary> public class ContentPresenterTests_InTemplate { [Fact] public void Should_Register_With_Host_When_TemplatedParent_Set() { var host = new Mock<IContentPresenterHost>(); var target = new ContentPresenter(); target.SetValue(Control.TemplatedParentProperty, host.Object); host.Verify(x => x.RegisterContentPresenter(target)); } [Fact] public void Setting_Content_To_Control_Should_Set_Child() { var (target, _) = CreateTarget(); var child = new Border(); target.Content = child; Assert.Equal(child, target.Child); } [Fact] public void Setting_Content_To_Control_Should_Update_Logical_Tree() { var (target, parent) = CreateTarget(); var child = new Border(); target.Content = child; Assert.Equal(parent, child.GetLogicalParent()); Assert.Equal(new[] { child }, parent.GetLogicalChildren()); } [Fact] public void Setting_Content_To_Control_Should_Update_Visual_Tree() { var (target, _) = CreateTarget(); var child = new Border(); target.Content = child; Assert.Equal(target, child.GetVisualParent()); Assert.Equal(new[] { child }, target.GetVisualChildren()); } [Fact] public void Setting_Content_To_String_Should_Create_TextBlock() { var (target, _) = CreateTarget(); target.Content = "Foo"; Assert.IsType<TextBlock>(target.Child); Assert.Equal("Foo", ((TextBlock)target.Child).Text); } [Fact] public void Setting_Content_To_String_Should_Update_Logical_Tree() { var (target, parent) = CreateTarget(); target.Content = "Foo"; var child = target.Child; Assert.Equal(parent, child.GetLogicalParent()); Assert.Equal(new[] { child }, parent.GetLogicalChildren()); } [Fact] public void Setting_Content_To_String_Should_Update_Visual_Tree() { var (target, _) = CreateTarget(); target.Content = "Foo"; var child = target.Child; Assert.Equal(target, child.GetVisualParent()); Assert.Equal(new[] { child }, target.GetVisualChildren()); } [Fact] public void Clearing_Control_Content_Should_Update_Logical_Tree() { var (target, _) = CreateTarget(); var child = new Border(); target.Content = child; target.Content = null; Assert.Null(child.GetLogicalParent()); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Clearing_Control_Content_Should_Update_Visual_Tree() { var (target, _) = CreateTarget(); var child = new Border(); target.Content = child; target.Content = null; Assert.Null(child.GetVisualParent()); Assert.Empty(target.GetVisualChildren()); } [Fact] public void Control_Content_Should_Not_Be_NameScope() { var (target, _) = CreateTarget(); target.Content = new TextBlock(); Assert.IsType<TextBlock>(target.Child); Assert.Null(NameScope.GetNameScope((Control)target.Child)); } [Fact] public void Assigning_Control_To_Content_Should_Not_Set_DataContext() { var (target, _) = CreateTarget(); target.Content = new Border(); Assert.False(target.IsSet(Control.DataContextProperty)); } [Fact] public void Assigning_NonControl_To_Content_Should_Set_DataContext_On_UpdateChild() { var (target, _) = CreateTarget(); target.Content = "foo"; Assert.Equal("foo", target.DataContext); } [Fact] public void Should_Use_ContentTemplate_If_Specified() { var (target, _) = CreateTarget(); target.ContentTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()); target.Content = "Foo"; Assert.IsType<Canvas>(target.Child); } [Fact] public void Should_Update_If_ContentTemplate_Changed() { var (target, _) = CreateTarget(); target.Content = "Foo"; Assert.IsType<TextBlock>(target.Child); target.ContentTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()); Assert.IsType<Canvas>(target.Child); target.ContentTemplate = null; Assert.IsType<TextBlock>(target.Child); } [Fact] public void Assigning_Control_To_Content_After_NonControl_Should_Clear_DataContext() { var (target, _) = CreateTarget(); target.Content = "foo"; Assert.True(target.IsSet(Control.DataContextProperty)); target.Content = new Border(); Assert.False(target.IsSet(Control.DataContextProperty)); } [Fact] public void Recycles_DataTemplate() { var (target, _) = CreateTarget(); target.DataTemplates.Add(new FuncDataTemplate<string>((_, __) => new Border(), true)); target.Content = "foo"; var control = target.Child; Assert.IsType<Border>(control); target.Content = "bar"; Assert.Same(control, target.Child); } [Fact] public void Detects_DataTemplate_Doesnt_Match_And_Doesnt_Recycle() { var (target, _) = CreateTarget(); target.DataTemplates.Add(new FuncDataTemplate<string>(x => x == "foo", _ => new Border(), true)); target.Content = "foo"; var control = target.Child; Assert.IsType<Border>(control); target.Content = "bar"; Assert.IsType<TextBlock>(target.Child); } [Fact] public void Detects_DataTemplate_Doesnt_Support_Recycling() { var (target, _) = CreateTarget(); target.DataTemplates.Add(new FuncDataTemplate<string>((_, __) => new Border(), false)); target.Content = "foo"; var control = target.Child; Assert.IsType<Border>(control); target.Content = "bar"; Assert.NotSame(control, target.Child); } [Fact] public void Reevaluates_DataTemplates_When_Recycling() { var (target, _) = CreateTarget(); target.DataTemplates.Add(new FuncDataTemplate<string>(x => x == "bar", _ => new Canvas(), true)); target.DataTemplates.Add(new FuncDataTemplate<string>((_, __) => new Border(), true)); target.Content = "foo"; var control = target.Child; Assert.IsType<Border>(control); target.Content = "bar"; Assert.IsType<Canvas>(target.Child); } [Fact] public void Should_Not_Bind_Old_Child_To_New_DataContext() { // Test for issue #1099. var textBlock = new TextBlock { [!TextBlock.TextProperty] = new Binding(), }; var (target, host) = CreateTarget(); host.DataTemplates.Add(new FuncDataTemplate<string>((_, __) => textBlock)); host.DataTemplates.Add(new FuncDataTemplate<int>((_, __) => new Canvas())); target.Content = "foo"; Assert.Same(textBlock, target.Child); textBlock.PropertyChanged += (s, e) => { Assert.NotEqual(e.NewValue, "42"); }; target.Content = 42; } [Fact] public void Should_Not_Bind_Child_To_Wrong_DataContext_When_Removing() { // Test for issue #2823 var canvas = new Canvas(); var (target, host) = CreateTarget(); var viewModel = new TestViewModel { Content = "foo" }; var dataContexts = new List<object>(); target.Bind(ContentPresenter.ContentProperty, (IBinding)new TemplateBinding(ContentControl.ContentProperty)); canvas.GetObservable(ContentPresenter.DataContextProperty).Subscribe(x => dataContexts.Add(x)); host.DataTemplates.Add(new FuncDataTemplate<string>((_, __) => canvas)); host.Bind(ContentControl.ContentProperty, new Binding(nameof(TestViewModel.Content))); host.DataContext = viewModel; Assert.Same(canvas, target.Child); viewModel.Content = 42; Assert.Equal(new object[] { null, "foo", null, }, dataContexts); } [Fact] public void Should_Set_InheritanceParent_Even_When_LogicalParent_Is_Already_Set() { var logicalParent = new Canvas(); var child = new TextBlock(); var (target, host) = CreateTarget(); ((ISetLogicalParent)child).SetParent(logicalParent); target.Content = child; Assert.Same(logicalParent, child.Parent); // InheritanceParent is exposed via StylingParent. Assert.Same(target, ((IStyledElement)child).StylingParent); } [Fact] public void Should_Reset_InheritanceParent_When_Child_Removed() { var logicalParent = new Canvas(); var child = new TextBlock(); var (target, _) = CreateTarget(); ((ISetLogicalParent)child).SetParent(logicalParent); target.Content = child; target.Content = null; // InheritanceParent is exposed via StylingParent. Assert.Same(logicalParent, ((IStyledElement)child).StylingParent); } [Fact] public void Should_Clear_Host_When_Host_Template_Cleared() { var (target, host) = CreateTarget(); Assert.Same(host, target.Host); host.Template = null; host.ApplyTemplate(); Assert.Null(target.Host); } (ContentPresenter presenter, ContentControl templatedParent) CreateTarget() { var templatedParent = new ContentControl { Template = new FuncControlTemplate<ContentControl>((_, s) => new ContentPresenter { Name = "PART_ContentPresenter", }.RegisterInNameScope(s)), }; var root = new TestRoot { Child = templatedParent }; templatedParent.ApplyTemplate(); return ((ContentPresenter)templatedParent.Presenter, templatedParent); } private class TestContentControl : ContentControl { public IControl Child { get; set; } } private class TestViewModel : INotifyPropertyChanged { private object _content; public object Content { get => _content; set { if (_content != value) { _content = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Content))); } } } public event PropertyChangedEventHandler PropertyChanged; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // 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.Diagnostics; using Gallio.Framework.Data; using Gallio.Model; using Gallio.Common.Reflection; using System.Collections.Generic; namespace Gallio.Framework.Pattern { /// <summary> /// Declares that a method represents a test. /// </summary> /// <remarks> /// <para> /// Subclasses of this attribute can control what happens with the method. /// </para> /// <para> /// At most one attribute of this type may appear on any given method. /// </para> /// <para> /// A test method has a timeout of 10 minutes by default. /// </para> /// </remarks> /// <seealso cref="TestMethodDecoratorPatternAttribute"/> [AttributeUsage(PatternAttributeTargets.TestMethod, AllowMultiple=false, Inherited=true)] public abstract class TestMethodPatternAttribute : PatternAttribute { /// <summary> /// Gets or sets a number that defines an ordering for the test with respect to its siblings. /// </summary> /// <remarks> /// <para> /// Unless compelled otherwise by test dependencies, tests with a lower order number than /// their siblings will run before those siblings and tests with the same order number /// as their siblings with run in an arbitrary sequence with respect to those siblings. /// </para> /// </remarks> /// <value>The test execution order with respect to siblings, initially zero.</value> public int Order { get; set; } /// <inheritdoc /> public override bool IsPrimary { get { return true; } } /// <inheritdoc /> public override IList<TestPart> GetTestParts(IPatternEvaluator evaluator, ICodeElementInfo codeElement) { return new[] { new TestPart() { IsTestCase = true } }; } /// <inheritdoc /> public override void Consume(IPatternScope containingScope, ICodeElementInfo codeElement, bool skipChildren) { //TODO: Review: Issue 762: Shouldn't the base method be invoked here? //base.Consume(containingScope, codeElement, skipChildren); IMethodInfo method = codeElement as IMethodInfo; Validate(containingScope, method); IPatternScope methodScope = containingScope.CreateChildTestScope(method.Name, method); methodScope.TestBuilder.Kind = TestKinds.Test; methodScope.TestBuilder.IsTestCase = true; methodScope.TestBuilder.Order = Order; methodScope.TestBuilder.TimeoutFunc = () => TestAssemblyExecutionParameters.DefaultTestCaseTimeout; InitializeTest(methodScope, method); SetTestSemantics(methodScope.TestBuilder, method); methodScope.TestBuilder.ApplyDeferredActions(); } /// <summary> /// Verifies that the attribute is being used correctly. /// </summary> /// <param name="containingScope">The containing scope.</param> /// <param name="method">The method.</param> /// <exception cref="PatternUsageErrorException">Thrown if the attribute is being used incorrectly.</exception> protected virtual void Validate(IPatternScope containingScope, IMethodInfo method) { if (!containingScope.CanAddChildTest || method == null) ThrowUsageErrorException("This attribute can only be used on a test method within a test type."); if (method.IsAbstract) ThrowUsageErrorException("This attribute cannot be used on an abstract method."); } /// <summary> /// Initializes a test for a method after it has been added to the test model. /// </summary> /// <param name="methodScope">The method scope.</param> /// <param name="method">The method.</param> protected virtual void InitializeTest(IPatternScope methodScope, IMethodInfo method) { string xmlDocumentation = method.GetXmlDocumentation(); if (xmlDocumentation != null) methodScope.TestBuilder.AddMetadata(MetadataKeys.XmlDocumentation, xmlDocumentation); methodScope.Process(method); if (method.IsGenericMethodDefinition) { foreach (IGenericParameterInfo parameter in method.GenericArguments) methodScope.Consume(parameter, false, DefaultGenericParameterPattern); } foreach (IParameterInfo parameter in method.Parameters) methodScope.Consume(parameter, false, DefaultMethodParameterPattern); } /// <summary> /// Applies semantic actions to a test to estalish its runtime behavior. /// </summary> /// <remarks> /// <para> /// This method is called after <see cref="InitializeTest" />. /// </para> /// <para> /// The default behavior for a <see cref="TestMethodPatternAttribute" /> /// is to configure the test actions as follows: /// <list type="bullet"> /// <item><see cref="PatternTestInstanceActions.BeforeTestInstanceChain" />: Set the /// test step name, <see cref="PatternTestInstanceState.TestMethod" /> and /// <see cref="PatternTestInstanceState.TestArguments" /> based on any values bound /// to the test method's generic parameter and method parameter slots.</item> /// <item><see cref="PatternTestInstanceActions.ExecuteTestInstanceChain" />: Invoke the method.</item> /// </list> /// </para> /// <para> /// You can override this method to change the semantics as required. /// </para> /// </remarks> /// <param name="testBuilder">The test builder.</param> /// <param name="method">The test method.</param> protected virtual void SetTestSemantics(ITestBuilder testBuilder, IMethodInfo method) { testBuilder.TestInstanceActions.BeforeTestInstanceChain.After( delegate(PatternTestInstanceState testInstanceState) { MethodInvocationSpec spec = testInstanceState.GetTestMethodInvocationSpec(method); testInstanceState.TestMethod = spec.ResolvedMethod; testInstanceState.TestArguments = spec.ResolvedArguments; if (!testInstanceState.IsReusingPrimaryTestStep) testInstanceState.NameBase = spec.Format(testInstanceState.NameBase, testInstanceState.Formatter); }); testBuilder.TestInstanceActions.ExecuteTestInstanceChain.After(Execute); } /// <summary> /// Executes the test method. /// </summary> /// <remarks> /// <para> /// The default implementation just calls <see cref="PatternTestInstanceState.InvokeTestMethod" /> /// and ignores the result. /// </para> /// </remarks> /// <param name="state">The test instance state, not null.</param> [DebuggerNonUserCode] protected virtual void Execute(PatternTestInstanceState state) { state.InvokeTestMethod(); } /// <summary> /// Gets the default pattern to apply to generic parameters that do not have a primary pattern, or null if none. /// </summary> /// <remarks> /// <para> /// The default implementation returns <see cref="TestParameterPatternAttribute.DefaultInstance" />. /// </para> /// </remarks> protected virtual IPattern DefaultGenericParameterPattern { get { return TestParameterPatternAttribute.DefaultInstance; } } /// <summary> /// Gets the default pattern to apply to method parameters that do not have a primary pattern, or null if none. /// </summary> /// <remarks> /// <para> /// The default implementation returns <see cref="TestParameterPatternAttribute.DefaultInstance" />. /// </para> /// </remarks> protected virtual IPattern DefaultMethodParameterPattern { get { return TestParameterPatternAttribute.DefaultInstance; } } } }
// 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.Generic; using System.Drawing.Imaging; using System.Globalization; using System.IO; using System.Diagnostics; using System.Drawing; using System.Reflection; using System.Collections; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; namespace OpenLiveWriter.CoreServices { /// <summary> /// Resource helper class. /// </summary> public sealed class ResourceHelper { /// <summary> /// The bitmap cache. /// </summary> [ThreadStatic] private static Dictionary<string,Bitmap> bitmapCache ; /// <summary> /// The icon cache /// </summary> [ThreadStatic] private static Hashtable iconCache ; /// <summary> /// Initializes a new instance of the ResourceHelper class. /// </summary> private ResourceHelper() { } /// <summary> /// Loads a Bitmap from the calling Assembly's resource stream. /// </summary> /// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param> public static Bitmap LoadAssemblyResourceBitmap(string resource) { return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), null, resource, false); } public static Bitmap LoadAssemblyResourceBitmap(string resource, bool mirror) { return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), null, resource, mirror); } /// <summary> /// Loads a Bitmap from the calling Assembly's resource stream. /// </summary> /// <param name="path">The explicit path to the Bitmap, null to use the default.</param> /// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param> public static Bitmap LoadAssemblyResourceBitmap(string path, string resource) { return LoadAssemblyResourceBitmap(Assembly.GetCallingAssembly(), path, resource, false); } /// <summary> /// Loads a Bitmap from an Assembly's resource stream. /// </summary> /// <param name="assembly">The Assembly to load the Bitmap from.</param> /// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param> public static Bitmap LoadAssemblyResourceBitmap(Assembly assembly, string resource) { return LoadAssemblyResourceBitmap(assembly, null, resource, false) ; } /// <summary> /// Loads a Bitmap from an Assembly's resource stream. /// </summary> /// <param name="assembly">The Assembly to load the Bitmap from.</param> /// <param name="path">The explicit path to the Bitmap, null to use the default.</param> /// <param name="resource">The name of the Bitmap to load (i.e. "Image.png").</param> public static Bitmap LoadAssemblyResourceBitmap(Assembly assembly, string path, string resource, bool mirror) { // If a path was not specified, default to using the name of the assembly. if (path == null) path = assembly.GetName().Name; // Format the schema resource name that we will load from the assembly. string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", path, resource); string key = String.Format(CultureInfo.InvariantCulture, "{0},{1}", resourceName, mirror); // Get the bitmap. Bitmap bitmap; lock (typeof(ResourceHelper)) { // Initialize the bitmap cache if necessary if (bitmapCache == null) bitmapCache = new Dictionary<string, Bitmap>() ; // Locate the resource name in the bitmap cache. If found, return it. if (!bitmapCache.TryGetValue(key, out bitmap)) { // Get a stream on the resource. If this fails, null will be returned. This means // that we could not find the resource in the assembly. using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { if (stream != null) { // Load the bitmap. // Bitmaps require their underlying streams to remain open // for as long as their bitmaps are in use. We don't want to hold open the // resource stream though, so copy it to a memory stream. bitmap = new Bitmap(StreamHelper.CopyToMemoryStream(stream)); if (BidiHelper.IsRightToLeft && mirror) { Bitmap temp = BidiHelper.Mirror(bitmap); bitmap.Dispose(); bitmap = temp; } } // Cache the bitmap. bitmapCache.Add(key, bitmap); } } // Done! return bitmap; } } /// <summary> /// Loads a Bitmap embedded in Images.resx. /// </summary> /// <param name="resource">The name of the Bitmap to load (i.e. "InsertPhotoAlbum_SmallImage").</param> public static Bitmap LoadBitmap(string resource) { // Get the bitmap. Bitmap bitmap; lock (typeof(ResourceHelper)) { // Initialize the bitmap cache if necessary if (bitmapCache == null) bitmapCache = new Dictionary<string, Bitmap>(); // Locate the resource name in the bitmap cache. If found, return it. if (!bitmapCache.TryGetValue(resource, out bitmap)) { bitmap = Images.ResourceManager.GetObject(resource) as Bitmap; bitmapCache.Add(resource, bitmap); } // Done! return bitmap; } } /// <summary> /// Loads an icon from an assembly resource. /// </summary> /// <param name="path">icon path.</param> /// <returns>Icon, or null if the icon could not be found.</returns> public static Icon LoadAssemblyResourceIcon(string path) { return LoadAssemblyResourceIcon( Assembly.GetCallingAssembly(), path ) ; } /// <summary> /// Loads an icon from an assembly resource. /// </summary> /// <param name="assembly">The assembly that contains the resource.</param> /// <param name="path">icon path.</param> /// <returns>Icon, or null if the icon could not be found.</returns> public static Icon LoadAssemblyResourceIcon(Assembly assembly, string path) { return LoadAssemblyResourceIcon( assembly, path, 0, 0) ; } /// <summary> /// Loads an icon from an assembly resource. /// </summary> /// <param name="path">icon path.</param> /// <returns>Icon, or null if the icon could not be found.</returns> public static Icon LoadAssemblyResourceIcon(string path, int desiredWidth, int desiredHeight) { return LoadAssemblyResourceIcon( Assembly.GetCallingAssembly(), path, desiredWidth, desiredHeight) ; } /// <summary> /// Loads an icon from an assembly resource. /// </summary> /// <param name="path">icon path.</param> /// <returns>Icon, or null if the icon could not be found.</returns> private static Icon LoadAssemblyResourceIcon(Assembly callingAssembly, string path, int desiredWidth, int desiredHeight) { // Get the calling assembly and its name. AssemblyName callingAssemblyName = callingAssembly.GetName(); // Format the schema resource name that we will load from the calling assembly. string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", callingAssemblyName.Name, path); string resourceNameKey = String.Format(CultureInfo.InvariantCulture, "{0}/{1}x{2}", resourceName, desiredWidth, desiredHeight); // Get the icon Icon icon ; lock (typeof(ResourceHelper)) { // Initialize the icon cache if necessary if ( iconCache == null ) iconCache = new Hashtable() ; // Get a stream on the resource. If this fails, null will be returned. This means // If we have the icon cached, return it. icon = (Icon)iconCache[resourceNameKey]; if (icon != null) return icon; // that we could not find the resource in the caller's assembly. Throw an exception. using (Stream stream = callingAssembly.GetManifestResourceStream(resourceName)) { if (stream == null) return null; // Load the icon // Unlike Bitmaps, icons don't need their streams to remain open if (desiredWidth > 0 && desiredHeight > 0) icon = new Icon(stream, desiredWidth, desiredHeight); else icon = new Icon(stream); } // Cache the icon iconCache[resourceNameKey] = icon; } // Done! return icon; } /// <summary> /// Saves an assembly resource to a file /// </summary> /// <param name="resourcePath">path to resource within assembly</param> /// <param name="filePath">full path to file to save</param> public static void SaveAssemblyResourceToFile(string resourcePath, string targetFilePath) { // Format the schema resource name that we will load from the assembly. Assembly assembly = Assembly.GetCallingAssembly() ; string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, resourcePath); // transfer the resource into the file stream using ( Stream fileStream = new FileStream( targetFilePath, FileMode.Create ) ) { // Load stream and transfer it to the target stream using ( Stream resourceStream = assembly.GetManifestResourceStream( resourceName) ) { StreamHelper.Transfer( resourceStream, fileStream ) ; } } } /// <summary> /// Saves an assembly resource to a stream /// </summary> /// <param name="resourcePath">path to resource within assembly</param> /// <param name="targetStream">target stream to save to</param> public static void SaveAssemblyResourceToStream(string resourcePath, Stream targetStream) { // Format the schema resource name that we will load from the assembly. Assembly assembly = Assembly.GetCallingAssembly() ; string resourceName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", assembly.GetName().Name, resourcePath); // Load stream and transfer it to the target stream using ( Stream resourceStream = assembly.GetManifestResourceStream( resourceName) ) { StreamHelper.Transfer( resourceStream, targetStream ) ; } } } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; namespace EventStore.BufferManagement { /// <summary> /// A manager to handle buffers for the socket connections /// </summary> /// <remarks> /// When used in an async call a buffer is pinned. Large numbers of pinned buffers /// cause problem with the GC (in particular it causes heap fragmentation). /// This class maintains a set of large segments and gives clients pieces of these /// segments that they can use for their buffers. The alternative to this would be to /// create many small arrays which it then maintained. This methodology should be slightly /// better than the many small array methodology because in creating only a few very /// large objects it will force these objects to be placed on the LOH. Since the /// objects are on the LOH they are at this time not subject to compacting which would /// require an update of all GC roots as would be the case with lots of smaller arrays /// that were in the normal heap. /// </remarks> public class BufferManager { private const int TrialsCount = 100; private static BufferManager _defaultBufferManager; private readonly int _segmentChunks; private readonly int _chunkSize; private readonly int _segmentSize; private readonly bool _allowedToCreateMemory; private readonly Common.Concurrent.ConcurrentStack<ArraySegment<byte>> _buffers = new Common.Concurrent.ConcurrentStack<ArraySegment<byte>>(); private readonly List<byte[]> _segments; private readonly object _creatingNewSegmentLock = new object(); /// <summary> /// Gets the default buffer manager /// </summary> /// <remarks>You should only be using this method if you don't want to manage buffers on your own.</remarks> /// <value>The default buffer manager.</value> public static BufferManager Default { get { //default to 1024 1kb buffers if people don't want to manage it on their own; if (_defaultBufferManager == null) _defaultBufferManager = new BufferManager(1024, 1024, 1); return _defaultBufferManager; } } /// <summary> /// Sets the default buffer manager. /// </summary> /// <param name="manager">The new default buffer manager.</param> public static void SetDefaultBufferManager(BufferManager manager) { if (manager == null) throw new ArgumentNullException("manager"); _defaultBufferManager = manager; } public int ChunkSize { get { return _chunkSize; } } public int SegmentsCount { get { return _segments.Count; } } public int SegmentChunksCount { get { return _segmentChunks; } } /// <summary> /// The current number of buffers available /// </summary> public int AvailableBuffers { get { return _buffers.Count; } //do we really care about volatility here? } /// <summary> /// The total size of all buffers /// </summary> public int TotalBufferSize { get { return _segments.Count * _segmentSize; } //do we really care about volatility here? } /// <summary> /// Constructs a new <see cref="BufferManager"></see> object /// </summary> /// <param name="segmentChunks">The number of chunks to create per segment</param> /// <param name="chunkSize">The size of a chunk in bytes</param> public BufferManager(int segmentChunks, int chunkSize) : this(segmentChunks, chunkSize, 1) { } /// <summary> /// Constructs a new <see cref="BufferManager"></see> object /// </summary> /// <param name="segmentChunks">The number of chunks to create per segment</param> /// <param name="chunkSize">The size of a chunk in bytes</param> /// <param name="initialSegments">The initial number of segments to create</param> public BufferManager(int segmentChunks, int chunkSize, int initialSegments) : this(segmentChunks, chunkSize, initialSegments, true) { } /// <summary> /// Constructs a new <see cref="BufferManager"></see> object /// </summary> /// <param name="segmentChunks">The number of chunks to create per segment</param> /// <param name="chunkSize">The size of a chunk in bytes</param> /// <param name="initialSegments">The initial number of segments to create</param> /// <param name="allowedToCreateMemory">If false when empty and checkout is called an exception will be thrown</param> public BufferManager(int segmentChunks, int chunkSize, int initialSegments, bool allowedToCreateMemory) { if (segmentChunks <= 0) throw new ArgumentException("segmentChunks"); if (chunkSize <= 0) throw new ArgumentException("chunkSize"); if (initialSegments < 0) throw new ArgumentException("initialSegments"); _segmentChunks = segmentChunks; _chunkSize = chunkSize; _segmentSize = _segmentChunks * _chunkSize; _segments = new List<byte[]>(); _allowedToCreateMemory = true; for (int i = 0; i < initialSegments; i++) { CreateNewSegment(true); } _allowedToCreateMemory = allowedToCreateMemory; } /// <summary> /// Creates a new segment, makes buffers available /// </summary> private void CreateNewSegment(bool forceCreation) { if (!_allowedToCreateMemory) throw new UnableToCreateMemoryException(); lock (_creatingNewSegmentLock) { if (!forceCreation && _buffers.Count > _segmentChunks / 2) return; var bytes = new byte[_segmentSize]; _segments.Add(bytes); for (int i = 0; i < _segmentChunks; i++) { var chunk = new ArraySegment<byte>(bytes, i * _chunkSize, _chunkSize); _buffers.Push(chunk); } Console.WriteLine("Segments count: {0}, buffers count: {1}, should be when full: {2}", _segments.Count, _buffers.Count, _segments.Count * _segmentChunks); } } /// <summary> /// Checks out a buffer from the manager /// </summary> /// <remarks> /// It is the client's responsibility to return the buffer to the manager by /// calling <see cref="CheckIn"></see> on the buffer /// </remarks> /// <returns>A <see cref="ArraySegment{T}"></see> that can be used as a buffer</returns> public ArraySegment<byte> CheckOut() { int trial = 0; while (trial < TrialsCount) { ArraySegment<byte> result; if (_buffers.TryPop(out result)) return result; CreateNewSegment(false); trial++; } throw new UnableToAllocateBufferException(); } /// <summary> /// Checks out a buffer from the manager /// </summary> /// <remarks> /// It is the client's responsibility to return the buffer to the manger by /// calling <see cref="CheckIn"></see> on the buffer /// </remarks> /// <returns>A <see cref="ArraySegment{T}"></see> that can be used as a buffer</returns> public IEnumerable<ArraySegment<byte>> CheckOut(int toGet) { var result = new ArraySegment<byte>[toGet]; var count = 0; var totalReceived = 0; while (count < TrialsCount) { ArraySegment<byte> piece; while (totalReceived < toGet) { if (!_buffers.TryPop(out piece)) break; result[totalReceived] = piece; ++totalReceived; } if (totalReceived == toGet) return result; CreateNewSegment(false); count++; } throw new UnableToAllocateBufferException(); } /// <summary> /// Returns a buffer to the control of the manager /// </summary> /// <remarks> /// It is the client's responsibility to return the buffer to the manger by /// calling <see cref="CheckIn"></see> on the buffer /// </remarks> /// <param name="buffer">The <see cref="ArraySegment{T}"></see> to return to the cache</param> public void CheckIn(ArraySegment<byte> buffer) { CheckBuffer(buffer); _buffers.Push(buffer); } /// <summary> /// Returns a set of buffers to the control of the manager /// </summary> /// <remarks> /// It is the client's responsibility to return the buffer to the manger by /// calling <see cref="CheckIn"></see> on the buffer /// </remarks> /// <param name="buffersToReturn">The <see cref="ArraySegment{T}"></see> to return to the cache</param> public void CheckIn(IEnumerable<ArraySegment<byte>> buffersToReturn) { if (buffersToReturn == null) throw new ArgumentNullException("buffersToReturn"); foreach (var buf in buffersToReturn) { CheckBuffer(buf); _buffers.Push(buf); } } //[Conditional("DEBUG")] private void CheckBuffer(ArraySegment<byte> buffer) { if (buffer.Array == null || buffer.Count == 0 || buffer.Array.Length < buffer.Offset + buffer.Count) throw new Exception("Attempt to checking invalid buffer"); if (buffer.Count != _chunkSize) throw new ArgumentException("Buffer was not of the same chunk size as the buffer manager", "buffer"); } } }
using UnityEngine; using System.Collections; public class TapDemo : MonoBehaviour { public ParticleSystem Indicator; public Transform shortTapObj; public Transform longTapObj; public Transform doubleTapObj; public Transform chargeObj; public TextMesh chargeTextMesh; public Transform dragObj1; public TextMesh dragTextMesh1; public Transform dragObj2; public TextMesh dragTextMesh2; // Use this for initialization void Start () { } void OnEnable(){ //these events are obsolete, replaced by onMultiTapE, but it's still usable //IT_Gesture.onShortTapE += OnShortTap; //IT_Gesture.onDoubleTapE += OnDoubleTap; IT_Gesture.onMultiTapE += this.OnMultiTap; IT_Gesture.onLongTapE += this.OnLongTap; IT_Gesture.onChargingE += this.OnCharging; IT_Gesture.onChargeEndE += this.OnChargeEnd; IT_Gesture.onDraggingStartE += this.OnDraggingStart; IT_Gesture.onDraggingE += this.OnDragging; IT_Gesture.onDraggingEndE += this.OnDraggingEnd; } void OnDisable(){ //these events are obsolete, replaced by onMultiTapE, but it's still usable //IT_Gesture.onShortTapE -= OnShortTap; //IT_Gesture.onDoubleTapE -= OnDoubleTap; IT_Gesture.onMultiTapE -= this.OnMultiTap; IT_Gesture.onLongTapE -= this.OnLongTap; IT_Gesture.onChargingE -= this.OnCharging; IT_Gesture.onChargeEndE -= this.OnChargeEnd; IT_Gesture.onDraggingStartE -= this.OnDraggingStart; IT_Gesture.onDraggingE -= this.OnDragging; IT_Gesture.onDraggingEndE -= this.OnDraggingEnd; } //called when a multi-Tap event is detected void OnMultiTap(Tap tap){ //do a raycast base on the position of the tap Ray ray = Camera.main.ScreenPointToRay(tap.pos); RaycastHit hit; if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ //if the tap lands on the shortTapObj, then shows the effect. if(hit.collider.transform== this.shortTapObj){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.shortTapObj.position; this.Indicator.startColor= this.GetRandomColor(); //emit a set number of particle this.Indicator.Emit(30); } //if the tap lands on the doubleTapObj else if(hit.collider.transform== this.doubleTapObj){ //check to make sure if the tap count matches if(tap.count==2){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.doubleTapObj.position; this.Indicator.startColor= this.GetRandomColor(); //emit a set number of particle this.Indicator.Emit(30); } } } } //called when a long tap event is ended void OnLongTap(Tap tap){ //do a raycast base on the position of the tap Ray ray = Camera.main.ScreenPointToRay(tap.pos); RaycastHit hit; //if the tap lands on the longTapObj if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ if(hit.collider.transform== this.longTapObj){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.longTapObj.position; this.Indicator.startColor= this.GetRandomColor(); //emit a set number of particle this.Indicator.Emit(30); } } } //called when a double tap event is ended //this event is used for onDoubleTapE in v1.0, it's still now applicabl void OnDoubleTap(Vector2 pos){ Ray ray = Camera.main.ScreenPointToRay(pos); RaycastHit hit; if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ if(hit.collider.transform== this.doubleTapObj){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.doubleTapObj.position; this.Indicator.startColor= this.GetRandomColor(); //emit a set number of particle this.Indicator.Emit(30); } } } //called when a charging event is detected void OnCharging(ChargedInfo cInfo){ Ray ray = Camera.main.ScreenPointToRay(cInfo.pos); RaycastHit hit; //use raycast at the cursor position to detect the object if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ if(hit.collider.transform== this.chargeObj){ //display the charged percentage on screen this.chargeTextMesh.text="Charging "+(cInfo.percent*100).ToString("f1")+"%"; } } } //called when a charge event is ended void OnChargeEnd(ChargedInfo cInfo){ Ray ray = Camera.main.ScreenPointToRay(cInfo.pos); RaycastHit hit; //use raycast at the cursor position to detect the object if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ if(hit.collider.transform== this.chargeObj){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.chargeObj.position; this.Indicator.startColor= this.GetRandomColor(); //adjust the indicator speed with respect to the charged percent this.Indicator.startSpeed=1+3*cInfo.percent; //emit a set number of particles with respect to the charged percent this.Indicator.Emit((int)(10+cInfo.percent*75f)); //reset the particle speed, since it's shared by other event this.StartCoroutine(this.ResumeSpeed()); } } this.chargeTextMesh.text="HoldToCharge"; } //reset the particle emission speed of the indicator IEnumerator ResumeSpeed(){ yield return new WaitForSeconds(this.Indicator.startLifetime); this.Indicator.startSpeed=2; } void Update(){ //Debug.Log(currentDragIndex+" "+dragByMouse); } /* bool cursorOnUIFlag=false; void OnDraggingStart(DragInfo dragInfo){ if(IsCursorOnUI(dragInfo.pos)){ cursorOnUIFlag=false; return; } cursorOnUIFlag=true; } void OnDraggingEnd(DragInfo dragInfo){ if(!cursorOnUIFlag) return; if(IsCursorOnUI(dragInfo.pos)) return; //insert custom code } */ private Vector3 dragOffset1; private Vector3 dragOffset2; private int currentDragIndex1=-1; private int currentDragIndex2=-1; void OnDraggingStart(DragInfo dragInfo){ //currentDragIndex=dragInfo.index; //if(currentDragIndex==-1){ Ray ray = Camera.main.ScreenPointToRay(dragInfo.pos); RaycastHit hit; //use raycast at the cursor position to detect the object if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ //if the drag started on dragObj1 if(hit.collider.transform== this.dragObj1){ Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragOffset1= this.dragObj1.position-p; //change the scale of dragObj1, give the user some visual feedback this.dragObj1.localScale*=1.1f; //latch dragObj1 to the cursor, based on the index this.Obj1ToCursor(dragInfo); this.currentDragIndex1=dragInfo.index; } //if the drag started on dragObj2 else if(hit.collider.transform== this.dragObj2){ Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragOffset2= this.dragObj2.position-p; //change the scale of dragObj2, give the user some visual feedback this.dragObj2.localScale*=1.1f; //latch dragObj2 to the cursor, based on the index this.Obj2ToCursor(dragInfo); this.currentDragIndex2=dragInfo.index; } } //} } //triggered on a single-finger/mouse dragging event is on-going void OnDragging(DragInfo dragInfo){ //if the dragInfo index matches dragIndex1, call function to position dragObj1 accordingly if(dragInfo.index== this.currentDragIndex1){ this.Obj1ToCursor(dragInfo); } //if the dragInfo index matches dragIndex2, call function to position dragObj2 accordingly else if(dragInfo.index== this.currentDragIndex2){ this.Obj2ToCursor(dragInfo); } } //assign dragObj1 to the dragInfo position, and display the appropriate tooltip void Obj1ToCursor(DragInfo dragInfo){ //~ LayerMask layer=~(1<<dragObj1.gameObject.layer); //~ Ray ray = Camera.main.ScreenPointToRay (dragInfo.pos); //~ RaycastHit hit; //~ if (Physics.Raycast (ray, out hit, Mathf.Infinity, layer)) { //~ dragObj1.position=hit.point; //~ } Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragObj1.position=p+ this.dragOffset1; if(dragInfo.isMouse){ this.dragTextMesh1.text="Dragging with mouse"+(dragInfo.index+1); } else{ this.dragTextMesh1.text="Dragging with finger"+(dragInfo.index+1); } } //assign dragObj2 to the dragInfo position, and display the appropriate tooltip void Obj2ToCursor(DragInfo dragInfo){ Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragObj2.position=p+ this.dragOffset2; if(dragInfo.isMouse){ this.dragTextMesh2.text="Dragging with mouse"+(dragInfo.index+1); } else{ this.dragTextMesh2.text="Dragging with finger"+(dragInfo.index+1); } } void OnDraggingEnd(DragInfo dragInfo){ //drop the dragObj being drag by this particular cursor if(dragInfo.index== this.currentDragIndex1){ this.currentDragIndex1=-1; this.dragObj1.localScale*=10f/11f; Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragObj1.position=p+ this.dragOffset1; this.dragTextMesh1.text="DragMe"; } else if(dragInfo.index== this.currentDragIndex2){ this.currentDragIndex2=-1; this.dragObj2.localScale*=10f/11f; Vector3 p=Camera.main.ScreenToWorldPoint(new Vector3(dragInfo.pos.x, dragInfo.pos.y, 30)); this.dragObj2.position=p+ this.dragOffset2; this.dragTextMesh2.text="DragMe"; } } //return a random color when called private Color GetRandomColor(){ return new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f)); } private bool instruction=false; void OnGUI(){ if(!this.instruction){ if(GUI.Button(new Rect(10, 55, 130, 35), "Instruction On")){ this.instruction=true; } } else{ if(GUI.Button(new Rect(10, 55, 130, 35), "Instruction Off")){ this.instruction=false; } GUI.Box(new Rect(10, 100, 200, 65), ""); GUI.Label(new Rect(15, 105, 190, 65), "interact with each object using the interaction stated on top of each of them"); } } //************************************************************************************************// //following function is used in v1.0 and is now obsolete //called when a short tap event is ended //this event is used for onShortTapE in v1.0, it's still now applicable void OnShortTap(Vector2 pos){ Ray ray = Camera.main.ScreenPointToRay(pos); RaycastHit hit; if(Physics.Raycast(ray, out hit, Mathf.Infinity)){ if(hit.collider.transform== this.shortTapObj){ //place the indicator at the object position and assign a random color to it this.Indicator.transform.position= this.shortTapObj.position; this.Indicator.startColor= this.GetRandomColor(); //emit a set number of particle this.Indicator.Emit(30); } } } }
using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Security.Principal; using Orleans.Runtime; using Orleans.Runtime.Configuration; namespace Orleans.Counter.Control { using System.Collections.Generic; using Orleans.Serialization; using OrleansTelemetryConsumers.Counters; /// <summary> /// Control Orleans Counters - Register or Unregister the Orleans counter set /// </summary> internal class CounterControl { public bool Unregister { get; private set; } public bool BruteForce { get; private set; } public bool NeedRunAsAdministrator { get; private set; } public bool IsRunningAsAdministrator { get; private set; } public bool PauseAtEnd { get; private set; } private static OrleansPerfCounterTelemetryConsumer perfCounterConsumer; public CounterControl() { // Check user is Administrator and has granted UAC elevation permission to run this app var userIdent = WindowsIdentity.GetCurrent(); var userPrincipal = new WindowsPrincipal(userIdent); IsRunningAsAdministrator = userPrincipal.IsInRole(WindowsBuiltInRole.Administrator); perfCounterConsumer = new OrleansPerfCounterTelemetryConsumer(); } public void PrintUsage() { using (var usageStr = new StringWriter()) { usageStr.WriteLine(typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe {command}"); usageStr.WriteLine("Where commands are:"); usageStr.WriteLine(" /? or /help = Display usage info"); usageStr.WriteLine(" /r or /register = Register Windows performance counters for Orleans [default]"); usageStr.WriteLine(" /u or /unregister = Unregister Windows performance counters for Orleans"); usageStr.WriteLine(" /f or /force = Use brute force, if necessary"); usageStr.WriteLine(" /pause = Pause for user key press after operation"); ConsoleText.WriteUsage(usageStr.ToString()); } } public bool ParseArguments(string[] args) { bool ok = true; NeedRunAsAdministrator = true; Unregister = false; foreach (var arg in args) { if (arg.StartsWith("/") || arg.StartsWith("-")) { var a = arg.ToLowerInvariant().Substring(1); switch (a) { case "r": case "register": Unregister = false; break; case "u": case "unregister": Unregister = true; break; case "f": case "force": BruteForce = true; break; case "pause": PauseAtEnd = true; break; case "?": case "help": NeedRunAsAdministrator = false; ok = false; break; default: NeedRunAsAdministrator = false; ok = false; break; } } else { ConsoleText.WriteError("Unrecognised command line option: " + arg); ok = false; } } return ok; } public int Run() { if (NeedRunAsAdministrator && !IsRunningAsAdministrator) { ConsoleText.WriteError("Need to be running in Administrator role to perform the requested operations."); return 1; } SerializationManager.InitializeForTesting(); InitConsoleLogging(); try { if (Unregister) { ConsoleText.WriteStatus("Unregistering Orleans performance counters with Windows"); UnregisterWindowsPerfCounters(this.BruteForce); } else { ConsoleText.WriteStatus("Registering Orleans performance counters with Windows"); RegisterWindowsPerfCounters(true); // Always reinitialize counter registrations, even if already existed } ConsoleText.WriteStatus("Operation completed successfully."); return 0; } catch (Exception exc) { ConsoleText.WriteError("Error running " + typeof(CounterControl).GetTypeInfo().Assembly.GetName().Name + ".exe", exc); if (!BruteForce) return 2; ConsoleText.WriteStatus("Ignoring error due to brute-force mode"); return 0; } } /// <summary> /// Initialize log infrastrtucture for Orleans runtime sub-components /// </summary> private static void InitConsoleLogging() { Trace.Listeners.Clear(); var cfg = new NodeConfiguration { TraceFilePattern = null, TraceToConsole = false }; LogManager.Initialize(cfg); //TODO: Move it to use the APM APIs //var logWriter = new LogWriterToConsole(true, true); // Use compact console output & no timestamps / log message metadata //LogManager.LogConsumers.Add(logWriter); } /// <summary> /// Create the set of Orleans counters, if they do not already exist /// </summary> /// <param name="useBruteForce">Use brute force, if necessary</param> /// <remarks>Note: Program needs to be running as Administrator to be able to register Windows perf counters.</remarks> private static void RegisterWindowsPerfCounters(bool useBruteForce) { try { if (OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable()) { if (!useBruteForce) { ConsoleText.WriteStatus("Orleans counters are already registered -- Use brute-force mode to re-initialize"); return; } // Delete any old perf counters UnregisterWindowsPerfCounters(true); } if (GrainTypeManager.Instance == null) { var loader = new SiloAssemblyLoader(new Dictionary<string, SearchOption>()); var typeManager = new GrainTypeManager(false, null, loader); // We shouldn't need GrainFactory in this case GrainTypeManager.Instance.Start(false); } // Register perf counters perfCounterConsumer.InstallCounters(); if (OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable()) ConsoleText.WriteStatus("Orleans counters registered successfully"); else ConsoleText.WriteError("Orleans counters are NOT registered"); } catch (Exception exc) { ConsoleText.WriteError("Error registering Orleans counters - {0}" + exc); throw; } } /// <summary> /// Remove the set of Orleans counters, if they already exist /// </summary> /// <param name="useBruteForce">Use brute force, if necessary</param> /// <remarks>Note: Program needs to be running as Administrator to be able to unregister Windows perf counters.</remarks> private static void UnregisterWindowsPerfCounters(bool useBruteForce) { if (!OrleansPerfCounterTelemetryConsumer.AreWindowsPerfCountersAvailable()) { ConsoleText.WriteStatus("Orleans counters are already unregistered"); return; } // Delete any old perf counters try { perfCounterConsumer.DeleteCounters(); } catch (Exception exc) { ConsoleText.WriteError("Error deleting old Orleans counters - {0}" + exc); if (useBruteForce) ConsoleText.WriteStatus("Ignoring error deleting Orleans counters due to brute-force mode"); else throw; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using Xunit; public class DuplexChannelFactoryTest { [Fact] public static void CreateChannel_EndpointAddress_Null_Throws() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; EndpointAddress remoteAddress = null; DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, remoteAddress); try { Assert.Throws<InvalidOperationException>(() => { factory.Open(); factory.CreateChannel(); }); } finally { factory.Abort(); } } [Fact] public static void CreateChannel_InvalidEndpointAddress_AsString_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<UriFormatException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "invalid"); }); } [Fact] public static void CreateChannel_EmptyEndpointAddress_AsString_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<UriFormatException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, string.Empty); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_ExpectedNetTcpScheme_HttpScheme_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; Assert.Throws<ArgumentException>("via", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://not-the-right-scheme"); factory.CreateChannel(); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_ExpectedNetTcpScheme_InvalidScheme_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; Assert.Throws<ArgumentException>("via", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "qwerty://not-the-right-scheme"); factory.CreateChannel(); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_BasicHttpBinding_Throws_InvalidOperation() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); // Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it. var exception = Assert.Throws<InvalidOperationException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://basichttp-not-duplex"); factory.CreateChannel(); }); Assert.True(exception.Message.Contains("BasicHttpBinding"), string.Format("InvalidOperationException exception string should contain 'BasicHttpBinding'. Actual message:\r\n" + exception.ToString())); } [Fact] public static void CreateChannel_Address_NullString_ThrowsArgumentNull() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<ArgumentNullException>("uri", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (string)null); }); } [Fact] public static void CreateChannel_Address_NullEndpointAddress_ThrowsArgumentNull() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (EndpointAddress)null); Assert.Throws<InvalidOperationException>(() => { factory.CreateChannel(); }); } [Fact] public static void CreateChannel_Using_NetTcpBinding_Defaults() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint"); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); IWcfDuplexService proxy = factory.CreateChannel(); Assert.NotNull(proxy); } [Fact] public static void CreateChannel_Using_NetTcp_NoSecurity() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint"); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); factory.CreateChannel(); } [Fact] public static void CreateChannel_Using_Http_NoSecurity() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetHttpBinding(BasicHttpSecurityMode.None); EndpointAddress endpoint = new EndpointAddress(FakeAddress.HttpAddress); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); factory.CreateChannel(); } [Fact] public static void CreateChannel_Of_IDuplexChannel_Using_NetTcpBinding_Creates_Unique_Instances() { DuplexChannelFactory<IWcfDuplexService> factory = null; DuplexChannelFactory<IWcfDuplexService> factory2 = null; IWcfDuplexService channel = null; IWcfDuplexService channel2 = null; WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); try { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress endpointAddress = new EndpointAddress(FakeAddress.TcpAddress); // Create the channel factory for the request-reply message exchange pattern. factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); factory2 = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); // Create the channel. channel = factory.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IDuplexChannel))); channel2 = factory2.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel2.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel2.GetType(), typeof(IDuplexChannel))); // Validate ToString() string toStringResult = channel.ToString(); string toStringExpected = "IWcfDuplexService"; Assert.Equal<string>(toStringExpected, toStringResult); // Validate Equals() Assert.StrictEqual<IWcfDuplexService>(channel, channel); // Validate Equals(other channel) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, channel2); // Validate Equals("other") negative Assert.NotStrictEqual<object>(channel, "other"); // Validate Equals(null) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, null); } finally { if (factory != null) { factory.Close(); } if (factory2 != null) { factory2.Close(); } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Adxstudio.Xrm.Web.UI; using Adxstudio.Xrm.Web.UI.CrmEntityListView; using Adxstudio.Xrm.Web.UI.JsonConfiguration; using Adxstudio.Xrm.Web.UI.WebForms; using Microsoft.Xrm.Sdk; using Newtonsoft.Json; using GridMetadata = Adxstudio.Xrm.Web.UI.JsonConfiguration.GridMetadata; namespace Adxstudio.Xrm.Web.Mvc.Liquid { public class EntityListDrop : EntityDrop { private readonly Lazy<string> _createUrl; private readonly Lazy<string> _createLabel; private readonly Lazy<string> _detailUrl; private readonly Lazy<string> _detailLabel; private readonly Lazy<string> _emptyListText; private readonly Lazy<string> _filterApplyLabel; private readonly Lazy<string> _getDataUrl; private readonly Lazy<GridMetadataDrop> _gridMetadata; private readonly Lazy<int> _languageCode; private readonly Lazy<string> _layouts; private readonly Lazy<string> _modalFormTemplateUrl; private readonly Lazy<string> _searchPlaceholder; private readonly Lazy<string> _searchTooltip; private readonly Lazy<EntityListViewDrop[]> _views; public EntityListDrop(IPortalLiquidContext portalLiquidContext, Entity entityList, Lazy<string> getDataUrl, Lazy<string> modalFormTemplateUrl, Lazy<string> createUrl, Lazy<string> detailUrl, Lazy<int> languageCode) : base(portalLiquidContext, entityList) { if (getDataUrl == null) throw new ArgumentNullException("getDataUrl"); if (createUrl == null) throw new ArgumentNullException("createUrl"); if (detailUrl == null) throw new ArgumentNullException("detailUrl"); if (languageCode == null) throw new ArgumentNullException("languageCode"); if (modalFormTemplateUrl == null) throw new ArgumentNullException("modalFormTemplateUrl"); _createUrl = createUrl; _detailUrl = detailUrl; _getDataUrl = getDataUrl; _languageCode = languageCode; _modalFormTemplateUrl = modalFormTemplateUrl; EntityLogicalName = entityList.GetAttributeValue<string>("adx_entityname"); PrimaryKeyName = entityList.GetAttributeValue<string>("adx_primarykeyname"); DetailIdParameter = entityList.GetAttributeValue<string>("adx_idquerystringparametername"); EnableEntityPermissions = entityList.GetAttributeValue<bool?>("adx_entitypermissionsenabled").GetValueOrDefault(false); FilterPortalUserAttributeName = entityList.GetAttributeValue<string>("adx_filterportaluser"); FilterAccountAttributeName = entityList.GetAttributeValue<string>("adx_filteraccount"); FilterWebsiteAttributeName = entityList.GetAttributeValue<string>("adx_filterwebsite"); FilterEnabled = entityList.GetAttributeValue<bool?>("adx_filter_enabled").GetValueOrDefault(false); FilterDefinition = entityList.GetAttributeValue<string>("adx_filter_definition"); PageSize = entityList.GetAttributeValue<int?>("adx_pagesize"); SearchEnabled = entityList.GetAttributeValue<bool?>("adx_searchenabled").GetValueOrDefault(false); var gridMetadataJson = entityList.GetAttributeValue<string>("adx_settings"); if (!string.IsNullOrWhiteSpace(gridMetadataJson)) { try { GridMetadataConfiguration = JsonConvert.DeserializeObject<GridMetadata>(gridMetadataJson, new JsonSerializerSettings { ContractResolver = JsonConfigurationContractResolver.Instance, TypeNameHandling = TypeNameHandling.Objects, Converters = new List<JsonConverter> { new GuidConverter() }, Binder = new ActionSerializationBinder() }); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString()); } } var viewMetadataJson = entityList.GetAttributeValue<string>("adx_views"); if (!string.IsNullOrWhiteSpace(gridMetadataJson)) { try { ViewMetadataConfiguration = JsonConvert.DeserializeObject<ViewMetadata>(viewMetadataJson, new JsonSerializerSettings { ContractResolver = JsonConfigurationContractResolver.Instance, TypeNameHandling = TypeNameHandling.Objects, Binder = new ActionSerializationBinder(), Converters = new List<JsonConverter> { new GuidConverter() } }); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, e.ToString()); } } var filterOrientation = entityList.GetAttributeValue<OptionSetValue>("adx_filter_orientation"); if (filterOrientation != null) { if (Enum.IsDefined(typeof(FilterConfiguration.FilterOrientation), filterOrientation.Value)) { IsFilterVertical = (FilterConfiguration.FilterOrientation)filterOrientation.Value == FilterConfiguration.FilterOrientation.Vertical; } } _gridMetadata = new Lazy<GridMetadataDrop>(() => new GridMetadataDrop(portalLiquidContext, GridMetadataConfiguration, LanguageCode)); _views = new Lazy<EntityListViewDrop[]>(GetViews, LazyThreadSafetyMode.None); _layouts = new Lazy<string>(() => GetLayouts(entityList), LazyThreadSafetyMode.None); _createLabel = CreateLazyLocalizedString("adx_createbuttonlabel"); _detailLabel = CreateLazyLocalizedString("adx_detailsbuttonlabel"); _emptyListText = CreateLazyLocalizedString("adx_emptylisttext"); _searchPlaceholder = CreateLazyLocalizedString("adx_searchplaceholdertext"); _searchTooltip = CreateLazyLocalizedString("adx_searchtooltiptext"); _filterApplyLabel = CreateLazyLocalizedString("adx_filter_applybuttonlabel"); } public bool CreateEnabled { get { return CreateUrl != null; } } public string CreateLabel { get { return _createLabel.Value; } } public string CreateUrl { get { return _createUrl.Value; } } public bool DetailEnabled { get { return DetailUrl != null && !string.IsNullOrEmpty(DetailIdParameter); } } public string DetailIdParameter { get; private set; } public string DetailLabel { get { return _detailLabel.Value; } } public string DetailUrl { get { return _detailUrl.Value; } } public string EmptyListText { get { return _emptyListText.Value; } } public bool EnableEntityPermissions { get; private set; } public string EntityLogicalName { get; private set; } public string FilterAccountAttributeName { get; private set; } public string FilterApplyLabel { get { return _filterApplyLabel.Value; } } public string FilterDefinition { get; private set; } public bool FilterEnabled { get; private set; } public bool IsFilterVertical { get; private set; } public string FilterPortalUserAttributeName { get; private set; } public string FilterWebsiteAttributeName { get; private set; } public string GetDataUrl { get { return _getDataUrl.Value; } } public GridMetadataDrop GridMetadata { get { return _gridMetadata.Value; } } public int LanguageCode { get { return _languageCode.Value; } } public string Layouts { get { return _layouts.Value; } } public string ModalFormTemplateUrl { get { return _modalFormTemplateUrl.Value; } } public int? PageSize { get; private set; } public string PrimaryKeyName { get; private set; } public bool SearchEnabled { get; private set; } public string SearchPlaceholder { get { return _searchPlaceholder.Value; } } public string SearchTooltip { get { return _searchTooltip.Value; } } public IEnumerable<EntityListViewDrop> Views { get { return _views.Value; } } public Guid? DefaultViewId { get { return Views.Any() ? new Guid?(Views.First().ViewId) : null; } } internal GridMetadata GridMetadataConfiguration { get; private set; } internal ViewMetadata ViewMetadataConfiguration { get; private set; } private Lazy<string> CreateLazyLocalizedString(string attributeLogicalName) { return new Lazy<string>(() => { var data = Entity.GetAttributeValue<string>(attributeLogicalName); var localized = Localization.GetLocalizedString(data, LanguageCode); return string.IsNullOrEmpty(localized) ? null : localized; }, LazyThreadSafetyMode.None); } private string GetLayouts(Entity entityList) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Getting Entity List For: {0}, entityId: {1}", entityList.LogicalName, entityList.Id)); var viewConfigurations = GetEntityViews() .Select( view => new ViewConfiguration(PortalViewContext.CreatePortalContext(), PortalViewContext.CreateServiceContext(), entityList, EntityLogicalName, PrimaryKeyName, view.Id, GridMetadataConfiguration, PortalViewContext.PortalName, LanguageCode, EnableEntityPermissions, "page", "filter", "query", "sort", "My", 20, "mf", null, null, null, null, null, view.DisplayName)) .ToList(); var layouts = viewConfigurations.Select(c => { try { return new ViewLayout(c, null, PortalViewContext.PortalName, LanguageCode, false, (c.ItemActionLinks != null && c.ItemActionLinks.Any())); } catch (SavedQueryNotFoundException ex) { ADXTrace.Instance.TraceWarning(TraceCategory.Application, ex.Message); return null; } }).Where(l => l != null); return JsonConvert.SerializeObject(layouts); } private EntityView[] GetEntityViews() { if (ViewMetadataConfiguration == null) { return (Entity.GetAttributeValue<string>("adx_view") ?? string.Empty).Split(',').Select(e => { Guid parsed; return Guid.TryParse(e.Trim(), out parsed) ? new Guid?(parsed) : null; }).Where(e => e.HasValue).Select(e => { try { return new EntityView(PortalViewContext.CreateServiceContext(), e.Value, LanguageCode); } catch { return null; } }).ToArray(); } return ViewMetadataConfiguration.Views.Select( e => new EntityView(PortalViewContext.CreateServiceContext(), e.ViewId, LanguageCode, e.DisplayName != null ? Localization.GetLocalizedString(e.DisplayName, LanguageCode) : null)).ToArray(); } private EntityListViewDrop[] GetViews() { if (ViewMetadataConfiguration == null) { return (Entity.GetAttributeValue<string>("adx_view") ?? string.Empty).Split(',').Select(e => { Guid parsed; return Guid.TryParse(e.Trim(), out parsed) ? new Guid?(parsed) : null; }).Where(e => e.HasValue).Select(e => { try { return new EntityView(PortalViewContext.CreateServiceContext(), e.Value, LanguageCode); } catch { return null; } }).Where(e => e != null).Select(e => new EntityListViewDrop(this, e)).ToArray(); } return ViewMetadataConfiguration.Views.Select(e => { try { return new EntityView(PortalViewContext.CreateServiceContext(), e.ViewId, LanguageCode, e.DisplayName != null ? Localization.GetLocalizedString(e.DisplayName, LanguageCode) : null); } catch { return null; } }).Where(e => e != null).Select(e => new EntityListViewDrop(this, e)).ToArray(); } } }
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; namespace Northwind{ /// <summary> /// Strongly-typed collection for the CustomerAndSuppliersByCity class. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCityCollection : ReadOnlyList<CustomerAndSuppliersByCity, CustomerAndSuppliersByCityCollection> { public CustomerAndSuppliersByCityCollection() {} } /// <summary> /// This is Read-only wrapper class for the Customer and Suppliers by City view. /// </summary> [Serializable] public partial class CustomerAndSuppliersByCity : ReadOnlyRecord<CustomerAndSuppliersByCity>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor 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("Customer and Suppliers by City", TableType.View, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = false; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarContactName = new TableSchema.TableColumn(schema); colvarContactName.ColumnName = "ContactName"; colvarContactName.DataType = DbType.String; colvarContactName.MaxLength = 30; colvarContactName.AutoIncrement = false; colvarContactName.IsNullable = true; colvarContactName.IsPrimaryKey = false; colvarContactName.IsForeignKey = false; colvarContactName.IsReadOnly = false; schema.Columns.Add(colvarContactName); TableSchema.TableColumn colvarRelationship = new TableSchema.TableColumn(schema); colvarRelationship.ColumnName = "Relationship"; colvarRelationship.DataType = DbType.AnsiString; colvarRelationship.MaxLength = 9; colvarRelationship.AutoIncrement = false; colvarRelationship.IsNullable = false; colvarRelationship.IsPrimaryKey = false; colvarRelationship.IsForeignKey = false; colvarRelationship.IsReadOnly = false; schema.Columns.Add(colvarRelationship); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("Customer and Suppliers by City",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public CustomerAndSuppliersByCity() { SetSQLProps(); SetDefaults(); MarkNew(); } public CustomerAndSuppliersByCity(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public CustomerAndSuppliersByCity(object keyID) { SetSQLProps(); LoadByKey(keyID); } public CustomerAndSuppliersByCity(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>("CompanyName"); } set { SetColumnValue("CompanyName", value); } } [XmlAttribute("ContactName")] [Bindable(true)] public string ContactName { get { return GetColumnValue<string>("ContactName"); } set { SetColumnValue("ContactName", value); } } [XmlAttribute("Relationship")] [Bindable(true)] public string Relationship { get { return GetColumnValue<string>("Relationship"); } set { SetColumnValue("Relationship", value); } } #endregion #region Columns Struct public struct Columns { public static string City = @"City"; public static string CompanyName = @"CompanyName"; public static string ContactName = @"ContactName"; public static string Relationship = @"Relationship"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// MvxPictureChooserTask.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using System; using System.IO; using System.Threading.Tasks; using Windows.Foundation; using Windows.Graphics.Imaging; using Windows.Media.Capture; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.UI.Core; using Windows.UI.Xaml.Media.Imaging; namespace MvvmCross.Plugins.PictureChooser.WindowsStore { public class MvxPictureChooserTask : IMvxPictureChooserTask { public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { TakePictureCommon(StorageFileFromDisk, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); } public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { TakePictureCommon(StorageFileFromCamera, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); } public Task<Stream> ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality) { var task = new TaskCompletionSource<Stream>(); ChoosePictureFromLibrary(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null)); return task.Task; } public Task<Stream> TakePicture(int maxPixelDimension, int percentQuality) { var task = new TaskCompletionSource<Stream>(); TakePicture(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null)); return task.Task; } public void ContinueFileOpenPicker(object args) { } private void TakePictureCommon(Func<Task<StorageFile>> storageFile, int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher; dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () => { await Process(storageFile, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); }); } private async Task Process(Func<Task<StorageFile>> storageFile, int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { var file = await storageFile(); if (file == null) { assumeCancelled(); return; } var rawFileStream = await file.OpenAsync(FileAccessMode.Read); var resizedStream = await ResizeJpegStreamAsync(maxPixelDimension, percentQuality, rawFileStream); pictureAvailable(resizedStream.AsStreamForRead()); } private static async Task<StorageFile> StorageFileFromCamera() { var dialog = new CameraCaptureUI(); var file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo); return file; } private static async Task<StorageFile> StorageFileFromDisk() { var filePicker = new FileOpenPicker(); filePicker.FileTypeFilter.Add(".jpg"); filePicker.FileTypeFilter.Add(".jpeg"); filePicker.ViewMode = PickerViewMode.Thumbnail; filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; //filePicker.SettingsIdentifier = "picker1"; //filePicker.CommitButtonText = "Open"; return await filePicker.PickSingleFileAsync(); } private async Task<IRandomAccessStream> ResizeJpegStreamAsyncRubbish(int maxPixelDimension, int percentQuality, IRandomAccessStream input) { BitmapDecoder decoder = await BitmapDecoder.CreateAsync(input); // create a new stream and encoder for the new image var ras = new InMemoryRandomAccessStream(); var enc = await BitmapEncoder.CreateForTranscodingAsync(ras, decoder); int targetHeight; int targetWidth; MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, (int)decoder.PixelWidth, (int)decoder.PixelHeight, out targetWidth, out targetHeight); enc.BitmapTransform.ScaledHeight = (uint)targetHeight; enc.BitmapTransform.ScaledWidth = (uint)targetWidth; // write out to the stream await enc.FlushAsync(); return ras; } private async Task<IRandomAccessStream> ResizeJpegStreamAsync(int maxPixelDimension, int percentQuality, IRandomAccessStream input) { var decoder = await BitmapDecoder.CreateAsync(input); int targetHeight; int targetWidth; MvxPictureDimensionHelper.TargetWidthAndHeight(maxPixelDimension, (int)decoder.PixelWidth, (int)decoder.PixelHeight, out targetWidth, out targetHeight); var transform = new BitmapTransform() { ScaledHeight = (uint)targetHeight, ScaledWidth = (uint)targetWidth }; var pixelData = await decoder.GetPixelDataAsync( BitmapPixelFormat.Rgba8, BitmapAlphaMode.Straight, transform, ExifOrientationMode.RespectExifOrientation, ColorManagementMode.DoNotColorManage); var destinationStream = new InMemoryRandomAccessStream(); var bitmapPropertiesSet = new BitmapPropertySet(); bitmapPropertiesSet.Add("ImageQuality", new BitmapTypedValue(((double) percentQuality)/100.0, PropertyType.Single)); var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, destinationStream, bitmapPropertiesSet); encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, (uint)targetWidth, (uint)targetHeight, decoder.DpiX, decoder.DpiY, pixelData.DetachPixelData()); await encoder.FlushAsync(); destinationStream.Seek(0L); return destinationStream; } /* #region IMvxCombinedPictureChooserTask Members public void ChooseOrTakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { // note - do not set PixelHeight = maxPixelDimension, PixelWidth = maxPixelDimension here - as that would create square cropping var chooser = new PhotoChooserTask {ShowCamera = true}; ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); } #endregion #region IMvxPictureChooserTask Members public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { // note - do not set PixelHeight = maxPixelDimension, PixelWidth = maxPixelDimension here - as that would create square cropping var chooser = new PhotoChooserTask {ShowCamera = false}; ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); } public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { var chooser = new CameraCaptureTask {}; ChoosePictureCommon(chooser, maxPixelDimension, percentQuality, pictureAvailable, assumeCancelled); } #endregion public void ChoosePictureCommon(ChooserBase<PhotoResult> chooser, int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable, Action assumeCancelled) { var dialog = new CameraCaptureUI(); // Define the aspect ratio for the photo var aspectRatio = new Size(16, 9); dialog.PhotoSettings.CroppedAspectRatio = aspectRatio; // Perform a photo capture and return the file object var file = dialog.CaptureFileAsync(CameraCaptureUIMode.Photo).Await(); // Physically save the image to local storage var bitmapImage = new BitmapImage(); using (IRandomAccessStream fileStream = file.OpenAsync(FileAccessMode.Read).Await()) { bitmapImage.SetSource(fileStream); } chooser.Completed += (sender, args) => { if (args.ChosenPhoto != null) { ResizeThenCallOnMainThread(maxPixelDimension, percentQuality, args.ChosenPhoto, pictureAvailable); } else assumeCancelled(); }; DoWithInvalidOperationProtection(chooser.Show); } private void ResizeThenCallOnMainThread(int maxPixelDimension, int percentQuality, Stream input, Action<Stream> success) { ResizeJpegStream(maxPixelDimension, percentQuality, input, (stream) => CallAsync(stream, success)); } private void ResizeJpegStream(int maxPixelDimension, int percentQuality, Stream input, Action<Stream> success) { var bitmap = new BitmapImage(); bitmap.SetSource(input); var writeable = new WriteableBitmap(bitmap); var ratio = 1.0; if (writeable.PixelWidth > writeable.PixelHeight) ratio = (maxPixelDimension)/((double) writeable.PixelWidth); else ratio = (maxPixelDimension)/((double) writeable.PixelHeight); var targetWidth = (int) Math.Round(ratio*writeable.PixelWidth); var targetHeight = (int) Math.Round(ratio*writeable.PixelHeight); // not - important - we do *not* use using here - disposing of memoryStream is someone else's problem var memoryStream = new MemoryStream(); writeable.SaveJpeg(memoryStream, targetWidth, targetHeight, 0, percentQuality); memoryStream.Seek(0L, SeekOrigin.Begin); success(memoryStream); } private void CallAsync(Stream input, Action<Stream> success) { Dispatcher.RequestMainThreadAction(() => success(input)); } */ } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { /// <summary> /// Most methods of this class are synchronized since they might be called both /// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory. /// </summary> internal class GrainDirectoryHandoffManager { private const int HANDOFF_CHUNK_SIZE = 500; private readonly LocalGrainDirectory localDirectory; private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap; private readonly List<SiloAddress> silosHoldingMyPartition; private readonly Dictionary<SiloAddress, Task> lastPromise; private readonly Logger logger; internal GrainDirectoryHandoffManager(LocalGrainDirectory localDirectory, GlobalConfiguration config) { logger = LogManager.GetLogger(this.GetType().FullName); this.localDirectory = localDirectory; directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>(); silosHoldingMyPartition = new List<SiloAddress>(); lastPromise = new Dictionary<SiloAddress, Task>(); } internal List<ActivationAddress> GetHandedOffInfo(GrainId grain) { lock (this) { foreach (var partition in directoryPartitionsMap.Values) { var result = partition.LookUpGrain(grain); if (result.Addresses != null) return result.Addresses; } } return null; } private async Task HandoffMyPartitionUponStop(Dictionary<GrainId, IGrainInfo> batchUpdate, bool isFullCopy) { if (batchUpdate.Count == 0 || silosHoldingMyPartition.Count == 0) { if (logger.IsVerbose) logger.Verbose((isFullCopy ? "FULL" : "DELTA") + " handoff finished with empty delta (nothing to send)"); return; } if (logger.IsVerbose) logger.Verbose("Sending {0} items to my {1}: (ring status is {2})", batchUpdate.Count, silosHoldingMyPartition.ToStrings(), localDirectory.RingStatusToString()); var tasks = new List<Task>(); var n = 0; var chunk = new Dictionary<GrainId, IGrainInfo>(); // Note that batchUpdate will not change while this method is executing foreach (var pair in batchUpdate) { chunk[pair.Key] = pair.Value; n++; if ((n % HANDOFF_CHUNK_SIZE != 0) && (n != batchUpdate.Count)) { // If we haven't filled in a chunk yet, keep looping. continue; } foreach (SiloAddress silo in silosHoldingMyPartition) { SiloAddress captureSilo = silo; Dictionary<GrainId, IGrainInfo> captureChunk = chunk; bool captureIsFullCopy = isFullCopy; if (logger.IsVerbose) logger.Verbose("Sending handed off partition to " + captureSilo); Task pendingRequest; if (lastPromise.TryGetValue(captureSilo, out pendingRequest)) { try { await pendingRequest; } catch (Exception) { } } Task task = localDirectory.Scheduler.RunOrQueueTask( () => localDirectory.GetDirectoryReference(captureSilo).AcceptHandoffPartition( localDirectory.MyAddress, captureChunk, captureIsFullCopy), localDirectory.RemGrainDirectory.SchedulingContext); lastPromise[captureSilo] = task; tasks.Add(task); } // We need to use a new Dictionary because the call to AcceptHandoffPartition, which reads the current Dictionary, // happens asynchronously (and typically after some delay). chunk = new Dictionary<GrainId, IGrainInfo>(); // This is a quick temporary solution. We send a full copy by sending one chunk as a full copy and follow-on chunks as deltas. // Obviously, this will really mess up if there's a failure after the first chunk but before the others are sent, since on a // full copy receive the follower dumps all old data and replaces it with the new full copy. // On the other hand, over time things should correct themselves, and of course, losing directory data isn't necessarily catastrophic. isFullCopy = false; } await Task.WhenAll(tasks); } internal void ProcessSiloRemoveEvent(SiloAddress removedSilo) { lock (this) { if (logger.IsVerbose) logger.Verbose("Processing silo remove event for " + removedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I hold this silo's copy) // (if yes, adjust local and/or handoffed directory partitions) if (!directoryPartitionsMap.ContainsKey(removedSilo)) return; // at least one predcessor should exist, which is me SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0]; if (localDirectory.MyAddress.Equals(predecessor)) { if (logger.IsVerbose) logger.Verbose("Merging my partition with the copy of silo " + removedSilo); // now I am responsible for this directory part localDirectory.DirectoryPartition.Merge(directoryPartitionsMap[removedSilo]); // no need to send our new partition to all others, as they // will realize the change and combine their copies without any additional communication (see below) } else { if (logger.IsVerbose) logger.Verbose("Merging partition of " + predecessor + " with the copy of silo " + removedSilo); // adjust copy for the predecessor of the failed silo directoryPartitionsMap[predecessor].Merge(directoryPartitionsMap[removedSilo]); } if (logger.IsVerbose) logger.Verbose("Removed copied partition of silo " + removedSilo); directoryPartitionsMap.Remove(removedSilo); } } internal void ProcessSiloStoppingEvent() { lock (this) { ProcessSiloStoppingEvent_Impl(); } } private async void ProcessSiloStoppingEvent_Impl() { if (logger.IsVerbose) logger.Verbose("Processing silo stopping event"); // Select our nearest predecessor to receive our hand-off, since that's the silo that will wind up owning our partition (assuming // that it doesn't also fail and that no other silo joins during the transition period). if (silosHoldingMyPartition.Count == 0) { silosHoldingMyPartition.AddRange(localDirectory.FindPredecessors(localDirectory.MyAddress, 1)); } // take a copy of the current directory partition Dictionary<GrainId, IGrainInfo> batchUpdate = localDirectory.DirectoryPartition.GetItems(); try { await HandoffMyPartitionUponStop(batchUpdate, true); localDirectory.MarkStopPreparationCompleted(); } catch (Exception exc) { localDirectory.MarkStopPreparationFailed(exc); } } internal void ProcessSiloAddEvent(SiloAddress addedSilo) { lock (this) { if (logger.IsVerbose) logger.Verbose("Processing silo add event for " + addedSilo); // Reset our follower list to take the changes into account ResetFollowers(); // check if this is one of our successors (i.e., if I should hold this silo's copy) // (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one) // NOTE: We need to move part of our local directory to the new silo if it is an immediate successor. List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1); if (!successors.Contains(addedSilo)) return; // check if this is an immediate successor if (successors[0].Equals(addedSilo)) { // split my local directory and send to my new immediate successor his share if (logger.IsVerbose) logger.Verbose("Splitting my partition between me and " + addedSilo); GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split( grain => { var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !localDirectory.MyAddress.Equals(s); }, false); List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true); List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false); if (splitPartListSingle.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListSingle, singleActivation:true); splitPartListSingle.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } if (splitPartListMulti.Count > 0) { if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListMulti.Count + " entries to " + addedSilo); localDirectory.Scheduler.QueueTask(async () => { await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListMulti, singleActivation:false); splitPartListMulti.ForEach( activationAddress => localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain)); }, localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } } else { // adjust partitions by splitting them accordingly between new and old silos SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0]; if (!directoryPartitionsMap.ContainsKey(predecessorOfNewSilo)) { // we should have the partition of the predcessor of our new successor logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo); } else { if (logger.IsVerbose) logger.Verbose("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo); GrainDirectoryPartition splitPart = directoryPartitionsMap[predecessorOfNewSilo].Split( grain => { // Need to review the 2nd line condition. var s = localDirectory.CalculateTargetSilo(grain); return (s != null) && !predecessorOfNewSilo.Equals(s); }, true); directoryPartitionsMap[addedSilo] = splitPart; } } // remove partition of one of the old successors that we do not need to now SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key; if (oldSuccessor == null) return; if (logger.IsVerbose) logger.Verbose("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)"); directoryPartitionsMap.Remove(oldSuccessor); } } internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy) { if (logger.IsVerbose) logger.Verbose("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source); if (!directoryPartitionsMap.ContainsKey(source)) { if (!isFullCopy) { logger.Warn(ErrorCode.DirectoryUnexpectedDelta, String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}", source, localDirectory.Membership.GetApproximateSiloStatus(source), localDirectory.Membership.GetApproximateSiloStatuses(true).Count)); } directoryPartitionsMap[source] = new GrainDirectoryPartition(); } if (isFullCopy) { directoryPartitionsMap[source].Set(partition); } else { directoryPartitionsMap[source].Update(partition); } } internal void RemoveHandoffPartition(SiloAddress source) { if (logger.IsVerbose) logger.Verbose("Got request to unregister directory partition copy from " + source); directoryPartitionsMap.Remove(source); } private void ResetFollowers() { var copyList = silosHoldingMyPartition.ToList(); foreach (var follower in copyList) { RemoveOldFollower(follower); } } private void RemoveOldFollower(SiloAddress silo) { if (logger.IsVerbose) logger.Verbose("Removing my copy from silo " + silo); // release this old copy, as we have got a new one silosHoldingMyPartition.Remove(silo); localDirectory.Scheduler.QueueTask(() => localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress), localDirectory.RemGrainDirectory.SchedulingContext).Ignore(); } } }
// (c) Copyright Esri, 2010 - 2016 // This source is subject to the Apache 2.0 License. // Please see http://www.apache.org/licenses/LICENSE-2.0.html for details. // All other rights reserved. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Resources; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geoprocessing; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.OSM.OSMClassExtension; namespace ESRI.ArcGIS.OSM.GeoProcessing { [Guid("f1c4f01d-bf2c-4f2b-b8fa-8b9b701ee160")] [ClassInterface(ClassInterfaceType.None)] [ProgId("OSMEditor.OSMGPWayLoader")] public class OSMGPWayLoader : ESRI.ArcGIS.Geoprocessing.IGPFunction2 { string m_DisplayName = String.Empty; ResourceManager resourceManager = null; OSMGPFactory osmGPFactory = null; public OSMGPWayLoader() { resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly); osmGPFactory = new OSMGPFactory(); } #region "IGPFunction2 Implementations" public ESRI.ArcGIS.esriSystem.UID DialogCLSID { get { return default(ESRI.ArcGIS.esriSystem.UID); } } public string DisplayName { get { if (String.IsNullOrEmpty(m_DisplayName)) { m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_WayLoaderName).DisplayName; } return m_DisplayName; } } public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); OSMToolHelper osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IGPParameter osmFileParameter = paramvalues.get_Element(0) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; IGPParameter osmLineFeatureClassParameter = paramvalues.get_Element(4) as IGPParameter; IGPValue osmLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmLineFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmLineFeatureClass = null; IGPParameter tagLineCollectionParameter = paramvalues.get_Element(2) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List<String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length - 1], storageKeyword, "", "", lineTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } IGPParameter osmPolygonFeatureClassParameter = paramvalues.get_Element(5) as IGPParameter; IGPValue osmPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPolygonFeatureClassParameter) as IGPValue; workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmPolygonFeatureClass = null; IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(3) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List<String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List<string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length - 1], storageKeyword, "", "", polygonTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); ComReleaser.ReleaseCOMObject(osmLineFeatureClass); IGPParameter osmPointFeatureClassParameter = paramvalues.get_Element(1) as IGPParameter; IGPValue osmPointFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmPointFeatureClassParameter) as IGPValue; string[] gdbComponents = new string[polygonFCNameElements.Length - 1]; System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1); string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents); osmToolHelper.smallLoadOSMWay(osmFileLocationString.GetAsText(), osmPointFeatureClassGPValue.GetAsText(), fileGDBLocation, lineFCNameElements[lineFCNameElements.Length - 1], polygonFCNameElements[polygonFCNameElements.Length - 1], lineTagstoExtract, polygonTagstoExtract); } public ESRI.ArcGIS.esriSystem.IName FullName { get { IName fullName = null; if (osmGPFactory != null) { fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_WayLoaderName) as IName; } return fullName; } } public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam) { return null; } public int HelpContext { get { return 0; } } public string HelpFile { get { return String.Empty; } } public bool IsLicensed() { return true; } public string MetadataFile { get { string metadafile = "osmgpwayloader.xml"; try { string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray()); string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation(); string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + languageid[0] + ".xml"; string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml"; if (System.IO.File.Exists(localizedMetaDataFileShort)) { metadafile = localizedMetaDataFileShort; } else if (System.IO.File.Exists(localizedMetaDataFileLong)) { metadafile = localizedMetaDataFileLong; } } catch { } return metadafile; } } public string Name { get { return OSMGPFactory.m_WayLoaderName; } } public ESRI.ArcGIS.esriSystem.IArray ParameterInfo { get { IArray parameters = new ArrayClass(); // input osm file containing the ways IGPParameterEdit3 osmWayFileParameter = new GPParameterClass() as IGPParameterEdit3; osmWayFileParameter.DataType = new DEFileTypeClass(); osmWayFileParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; osmWayFileParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_osmfile_desc"); osmWayFileParameter.Name = "in_osmWayFile"; osmWayFileParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; // input feature class containing the points IGPParameterEdit3 osmPointFeatureClassParameter = new GPParameterClass() as IGPParameterEdit3; osmPointFeatureClassParameter.DataType = new DEFeatureClassTypeClass(); osmPointFeatureClassParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; osmPointFeatureClassParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_osmpointFeatureClass_desc"); osmPointFeatureClassParameter.Name = "in_osmPointFC"; osmPointFeatureClassParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; IGPFeatureClassDomain osmPointFeatureClassDomain = new GPFeatureClassDomainClass(); osmPointFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple); osmPointFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint); osmPointFeatureClassParameter.Domain = osmPointFeatureClassDomain as IGPDomain; // field multi parameter IGPParameterEdit3 loadLineFieldsParameter = new GPParameterClass() as IGPParameterEdit3; IGPDataType fieldNameDataType = new GPStringTypeClass(); IGPMultiValue fieldNameMultiValue = new GPMultiValueClass(); fieldNameMultiValue.MemberDataType = fieldNameDataType; IGPMultiValueType fieldNameDataType2 = new GPMultiValueTypeClass(); fieldNameDataType2.MemberDataType = fieldNameDataType; loadLineFieldsParameter.Name = "in_polyline_fieldNames"; loadLineFieldsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_lineFieldNames_desc"); loadLineFieldsParameter.Category = resourceManager.GetString("GPTools_OSMGPMultiLoader_schemaCategory_desc"); loadLineFieldsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional; loadLineFieldsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; loadLineFieldsParameter.DataType = (IGPDataType)fieldNameDataType2; loadLineFieldsParameter.Value = (IGPValue)fieldNameMultiValue; IGPParameterEdit3 loadPolygonFieldsParameter = new GPParameterClass() as IGPParameterEdit3; loadPolygonFieldsParameter.Name = "in_polygon_fieldNames"; loadPolygonFieldsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_polygonFieldNames_desc"); loadPolygonFieldsParameter.Category = resourceManager.GetString("GPTools_OSMGPMultiLoader_schemaCategory_desc"); loadPolygonFieldsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeOptional; loadPolygonFieldsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionInput; loadPolygonFieldsParameter.DataType = (IGPDataType)fieldNameDataType2; loadPolygonFieldsParameter.Value = (IGPValue)fieldNameMultiValue; IGPParameterEdit3 osmLinesParameter = new GPParameterClass() as IGPParameterEdit3; osmLinesParameter.DataType = new DEFeatureClassTypeClass(); osmLinesParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; osmLinesParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; osmLinesParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_osmLines_desc"); osmLinesParameter.Name = "out_osmWayLines"; IGPFeatureClassDomain osmLineFeatureClassDomain = new GPFeatureClassDomainClass(); osmLineFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple); osmLineFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline); osmLinesParameter.Domain = osmLineFeatureClassDomain as IGPDomain; IGPParameterEdit3 osmPolygonsParameter = new GPParameterClass() as IGPParameterEdit3; osmPolygonsParameter.DataType = new DEFeatureClassTypeClass(); osmPolygonsParameter.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput; osmPolygonsParameter.ParameterType = esriGPParameterType.esriGPParameterTypeRequired; osmPolygonsParameter.DisplayName = resourceManager.GetString("GPTools_OSMGPWayLoader_osmPolygons_desc"); osmPolygonsParameter.Name = "out_osmWayPolygons"; IGPFeatureClassDomain osmPolygonFeatureClassDomain = new GPFeatureClassDomainClass(); osmPolygonFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple); osmPolygonFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon); osmPolygonsParameter.Domain = osmPolygonFeatureClassDomain as IGPDomain; parameters.Add(osmWayFileParameter); parameters.Add(osmPointFeatureClassParameter); parameters.Add(loadLineFieldsParameter); parameters.Add(loadPolygonFieldsParameter); parameters.Add(osmLinesParameter); parameters.Add(osmPolygonsParameter); return parameters; } } public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages) { } public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr) { } public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr) { return default(ESRI.ArcGIS.Geodatabase.IGPMessages); } #endregion } }
/* * [The "BSD license"] * Copyright (c) 2013 Terence Parr * Copyright (c) 2013 Sam Harwell * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Collections.Concurrent; using System.Collections.Generic; using System.Text; using Antlr4.Runtime; using Antlr4.Runtime.Atn; using Antlr4.Runtime.Misc; using Antlr4.Runtime.Sharpen; namespace Antlr4.Runtime.Atn { public abstract class PredictionContext { [NotNull] public static readonly Antlr4.Runtime.Atn.PredictionContext EmptyLocal = EmptyPredictionContext.LocalContext; [NotNull] public static readonly Antlr4.Runtime.Atn.PredictionContext EmptyFull = EmptyPredictionContext.FullContext; public const int EmptyLocalStateKey = int.MinValue; public const int EmptyFullStateKey = int.MaxValue; private const int InitialHash = 1; /// <summary> /// Stores the computed hash code of this /// <see cref="PredictionContext"/> /// . The hash /// code is computed in parts to match the following reference algorithm. /// <pre> /// private int referenceHashCode() { /// int hash = /// <see cref="Antlr4.Runtime.Misc.MurmurHash.Initialize()">MurmurHash.initialize</see> /// ( /// <see cref="InitialHash"/> /// ); /// for (int i = 0; i &lt; /// <see cref="Size()"/> /// ; i++) { /// hash = /// <see cref="Antlr4.Runtime.Misc.MurmurHash.Update(int, int)">MurmurHash.update</see> /// (hash, /// <see cref="GetParent(int)">getParent</see> /// (i)); /// } /// for (int i = 0; i &lt; /// <see cref="Size()"/> /// ; i++) { /// hash = /// <see cref="Antlr4.Runtime.Misc.MurmurHash.Update(int, int)">MurmurHash.update</see> /// (hash, /// <see cref="GetReturnState(int)">getReturnState</see> /// (i)); /// } /// hash = /// <see cref="Antlr4.Runtime.Misc.MurmurHash.Finish(int, int)">MurmurHash.finish</see> /// (hash, 2 * /// <see cref="Size()"/> /// ); /// return hash; /// } /// </pre> /// </summary> private readonly int cachedHashCode; protected internal PredictionContext(int cachedHashCode) { this.cachedHashCode = cachedHashCode; } protected internal static int CalculateEmptyHashCode() { int hash = MurmurHash.Initialize(InitialHash); hash = MurmurHash.Finish(hash, 0); return hash; } protected internal static int CalculateHashCode(Antlr4.Runtime.Atn.PredictionContext parent, int returnState) { int hash = MurmurHash.Initialize(InitialHash); hash = MurmurHash.Update(hash, parent); hash = MurmurHash.Update(hash, returnState); hash = MurmurHash.Finish(hash, 2); return hash; } protected internal static int CalculateHashCode(Antlr4.Runtime.Atn.PredictionContext[] parents, int[] returnStates) { int hash = MurmurHash.Initialize(InitialHash); foreach (Antlr4.Runtime.Atn.PredictionContext parent in parents) { hash = MurmurHash.Update(hash, parent); } foreach (int returnState in returnStates) { hash = MurmurHash.Update(hash, returnState); } hash = MurmurHash.Finish(hash, 2 * parents.Length); return hash; } public abstract int Size { get; } public abstract int GetReturnState(int index); public abstract int FindReturnState(int returnState); [return: NotNull] public abstract Antlr4.Runtime.Atn.PredictionContext GetParent(int index); protected internal abstract Antlr4.Runtime.Atn.PredictionContext AddEmptyContext(); protected internal abstract Antlr4.Runtime.Atn.PredictionContext RemoveEmptyContext(); public static Antlr4.Runtime.Atn.PredictionContext FromRuleContext(ATN atn, RuleContext outerContext) { return FromRuleContext(atn, outerContext, true); } public static Antlr4.Runtime.Atn.PredictionContext FromRuleContext(ATN atn, RuleContext outerContext, bool fullContext) { if (outerContext.IsEmpty) { return fullContext ? EmptyFull : EmptyLocal; } Antlr4.Runtime.Atn.PredictionContext parent; if (outerContext.Parent != null) { parent = Antlr4.Runtime.Atn.PredictionContext.FromRuleContext(atn, outerContext.Parent, fullContext); } else { parent = fullContext ? EmptyFull : EmptyLocal; } ATNState state = atn.states[outerContext.invokingState]; RuleTransition transition = (RuleTransition)state.Transition(0); return parent.GetChild(transition.followState.stateNumber); } private static Antlr4.Runtime.Atn.PredictionContext AddEmptyContext(Antlr4.Runtime.Atn.PredictionContext context) { return context.AddEmptyContext(); } private static Antlr4.Runtime.Atn.PredictionContext RemoveEmptyContext(Antlr4.Runtime.Atn.PredictionContext context) { return context.RemoveEmptyContext(); } public static Antlr4.Runtime.Atn.PredictionContext Join(Antlr4.Runtime.Atn.PredictionContext context0, Antlr4.Runtime.Atn.PredictionContext context1) { return Join(context0, context1, PredictionContextCache.Uncached); } internal static Antlr4.Runtime.Atn.PredictionContext Join(Antlr4.Runtime.Atn.PredictionContext context0, Antlr4.Runtime.Atn.PredictionContext context1, PredictionContextCache contextCache) { if (context0 == context1) { return context0; } if (context0.IsEmpty) { return IsEmptyLocal(context0) ? context0 : AddEmptyContext(context1); } else { if (context1.IsEmpty) { return IsEmptyLocal(context1) ? context1 : AddEmptyContext(context0); } } int context0size = context0.Size; int context1size = context1.Size; if (context0size == 1 && context1size == 1 && context0.GetReturnState(0) == context1.GetReturnState(0)) { Antlr4.Runtime.Atn.PredictionContext merged = contextCache.Join(context0.GetParent(0), context1.GetParent(0)); if (merged == context0.GetParent(0)) { return context0; } else { if (merged == context1.GetParent(0)) { return context1; } else { return merged.GetChild(context0.GetReturnState(0)); } } } int count = 0; Antlr4.Runtime.Atn.PredictionContext[] parentsList = new Antlr4.Runtime.Atn.PredictionContext[context0size + context1size]; int[] returnStatesList = new int[parentsList.Length]; int leftIndex = 0; int rightIndex = 0; bool canReturnLeft = true; bool canReturnRight = true; while (leftIndex < context0size && rightIndex < context1size) { if (context0.GetReturnState(leftIndex) == context1.GetReturnState(rightIndex)) { parentsList[count] = contextCache.Join(context0.GetParent(leftIndex), context1.GetParent(rightIndex)); returnStatesList[count] = context0.GetReturnState(leftIndex); canReturnLeft = canReturnLeft && parentsList[count] == context0.GetParent(leftIndex); canReturnRight = canReturnRight && parentsList[count] == context1.GetParent(rightIndex); leftIndex++; rightIndex++; } else { if (context0.GetReturnState(leftIndex) < context1.GetReturnState(rightIndex)) { parentsList[count] = context0.GetParent(leftIndex); returnStatesList[count] = context0.GetReturnState(leftIndex); canReturnRight = false; leftIndex++; } else { System.Diagnostics.Debug.Assert(context1.GetReturnState(rightIndex) < context0.GetReturnState(leftIndex)); parentsList[count] = context1.GetParent(rightIndex); returnStatesList[count] = context1.GetReturnState(rightIndex); canReturnLeft = false; rightIndex++; } } count++; } while (leftIndex < context0size) { parentsList[count] = context0.GetParent(leftIndex); returnStatesList[count] = context0.GetReturnState(leftIndex); leftIndex++; canReturnRight = false; count++; } while (rightIndex < context1size) { parentsList[count] = context1.GetParent(rightIndex); returnStatesList[count] = context1.GetReturnState(rightIndex); rightIndex++; canReturnLeft = false; count++; } if (canReturnLeft) { return context0; } else { if (canReturnRight) { return context1; } } if (count < parentsList.Length) { parentsList = Arrays.CopyOf(parentsList, count); returnStatesList = Arrays.CopyOf(returnStatesList, count); } if (parentsList.Length == 0) { // if one of them was EMPTY_LOCAL, it would be empty and handled at the beginning of the method return EmptyFull; } else { if (parentsList.Length == 1) { return new SingletonPredictionContext(parentsList[0], returnStatesList[0]); } else { return new ArrayPredictionContext(parentsList, returnStatesList); } } } public static bool IsEmptyLocal(Antlr4.Runtime.Atn.PredictionContext context) { return context == EmptyLocal; } public static Antlr4.Runtime.Atn.PredictionContext GetCachedContext(Antlr4.Runtime.Atn.PredictionContext context, ConcurrentDictionary<Antlr4.Runtime.Atn.PredictionContext, Antlr4.Runtime.Atn.PredictionContext> contextCache, PredictionContext.IdentityHashMap visited) { if (context.IsEmpty) { return context; } Antlr4.Runtime.Atn.PredictionContext existing; if (visited.TryGetValue(context, out existing)) { return existing; } if (contextCache.TryGetValue(context, out existing)) { visited[context] = existing; return existing; } bool changed = false; Antlr4.Runtime.Atn.PredictionContext[] parents = new Antlr4.Runtime.Atn.PredictionContext[context.Size]; for (int i = 0; i < parents.Length; i++) { Antlr4.Runtime.Atn.PredictionContext parent = GetCachedContext(context.GetParent(i), contextCache, visited); if (changed || parent != context.GetParent(i)) { if (!changed) { parents = new Antlr4.Runtime.Atn.PredictionContext[context.Size]; for (int j = 0; j < context.Size; j++) { parents[j] = context.GetParent(j); } changed = true; } parents[i] = parent; } } if (!changed) { existing = contextCache.GetOrAdd(context, context); visited[context] = existing; return context; } // We know parents.length>0 because context.isEmpty() is checked at the beginning of the method. Antlr4.Runtime.Atn.PredictionContext updated; if (parents.Length == 1) { updated = new SingletonPredictionContext(parents[0], context.GetReturnState(0)); } else { ArrayPredictionContext arrayPredictionContext = (ArrayPredictionContext)context; updated = new ArrayPredictionContext(parents, arrayPredictionContext.returnStates, context.cachedHashCode); } existing = contextCache.GetOrAdd(updated, updated); visited[updated] = existing; visited[context] = existing; return updated; } public virtual Antlr4.Runtime.Atn.PredictionContext AppendContext(int returnContext, PredictionContextCache contextCache) { return AppendContext(Antlr4.Runtime.Atn.PredictionContext.EmptyFull.GetChild(returnContext), contextCache); } public abstract Antlr4.Runtime.Atn.PredictionContext AppendContext(Antlr4.Runtime.Atn.PredictionContext suffix, PredictionContextCache contextCache); public virtual Antlr4.Runtime.Atn.PredictionContext GetChild(int returnState) { return new SingletonPredictionContext(this, returnState); } public abstract bool IsEmpty { get; } public abstract bool HasEmpty { get; } public sealed override int GetHashCode() { return cachedHashCode; } public abstract override bool Equals(object o); //@Override //public String toString() { // return toString(null, Integer.MAX_VALUE); //} public virtual string[] ToStrings(IRecognizer recognizer, int currentState) { return ToStrings(recognizer, Antlr4.Runtime.Atn.PredictionContext.EmptyFull, currentState); } public virtual string[] ToStrings(IRecognizer recognizer, Antlr4.Runtime.Atn.PredictionContext stop, int currentState) { List<string> result = new List<string>(); for (int perm = 0; ; perm++) { int offset = 0; bool last = true; Antlr4.Runtime.Atn.PredictionContext p = this; int stateNumber = currentState; StringBuilder localBuffer = new StringBuilder(); localBuffer.Append("["); while (!p.IsEmpty && p != stop) { int index = 0; if (p.Size > 0) { int bits = 1; while ((1 << bits) < p.Size) { bits++; } int mask = (1 << bits) - 1; index = (perm >> offset) & mask; last &= index >= p.Size - 1; if (index >= p.Size) { goto outer_continue; } offset += bits; } if (recognizer != null) { if (localBuffer.Length > 1) { // first char is '[', if more than that this isn't the first rule localBuffer.Append(' '); } ATN atn = recognizer.Atn; ATNState s = atn.states[stateNumber]; string ruleName = recognizer.RuleNames[s.ruleIndex]; localBuffer.Append(ruleName); } else { if (p.GetReturnState(index) != EmptyFullStateKey) { if (!p.IsEmpty) { if (localBuffer.Length > 1) { // first char is '[', if more than that this isn't the first rule localBuffer.Append(' '); } localBuffer.Append(p.GetReturnState(index)); } } } stateNumber = p.GetReturnState(index); p = p.GetParent(index); } localBuffer.Append("]"); result.Add(localBuffer.ToString()); if (last) { break; } outer_continue: ; } return result.ToArray(); } public sealed class IdentityHashMap : Dictionary<PredictionContext, PredictionContext> { public IdentityHashMap() : base(PredictionContext.IdentityEqualityComparator.Instance) { } } public sealed class IdentityEqualityComparator : EqualityComparer<PredictionContext> { public static readonly PredictionContext.IdentityEqualityComparator Instance = new PredictionContext.IdentityEqualityComparator(); private IdentityEqualityComparator() { } public override int GetHashCode(PredictionContext obj) { return obj.GetHashCode(); } public override bool Equals(PredictionContext a, PredictionContext b) { return a == b; } } } }
namespace Selenium.WebDriver.Extensions { using System.Diagnostics.CodeAnalysis; using OpenQA.Selenium; using static System.Globalization.CultureInfo; using static System.String; using static JavaScriptSnippets; using static Softlr.Suppress; using static Validate; /// <summary>Searches the DOM elements using jQuery selector.</summary> /// <inheritdoc /> public class JQuerySelector : SelectorBase<JQuerySelector> { private const string VARIABLE = "window.jQuery"; private readonly string _chain; /// <summary>Initializes a new instance of the <see cref="JQuerySelector" /> class.</summary> /// <param name="selector">A string containing a selector expression.</param> /// <remarks> /// This constructor cannot be merged with <see /// cref="M:Selenium.WebDriver.Extensions.JQuerySelector.#ctor(System.String,Selenium.WebDriver.Extensions.JQuerySelector,System.String,System.String)" /> /// constructor as it is resolved by reflection. /// </remarks> public JQuerySelector(string selector) : this(selector, null, "jQuery", string.Empty) { } /// <summary>Initializes a new instance of the <see cref="JQuerySelector" /> class.</summary> /// <param name="selector">A string containing a selector expression.</param> /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param> public JQuerySelector(string selector, JQuerySelector context) : this(selector, context, "jQuery", string.Empty) { } /// <summary>Initializes a new instance of the <see cref="JQuerySelector" /> class.</summary> /// <param name="selector">A string containing a selector expression.</param> /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param> /// <param name="variable">A variable that has been assigned to jQuery.</param> public JQuerySelector(string selector, JQuerySelector context, string variable) : this(selector, context, variable, string.Empty) { } /// <summary>Initializes a new instance of the <see cref="JQuerySelector" /> class.</summary> /// <param name="selector">A string containing a selector expression.</param> /// <param name="variable">A variable that has been assigned to jQuery.</param> public JQuerySelector(string selector, string variable) : this(selector, null, variable, string.Empty) { } /// <summary>Initializes a new instance of the <see cref="JQuerySelector" /> class.</summary> /// <param name="selector">A string containing a selector expression.</param> /// <param name="context">A DOM Element, Document, or jQuery to use as context.</param> /// <param name="variable">A variable that has been assigned to jQuery.</param> /// <param name="chain">The jQuery method chain.</param> public JQuerySelector(string selector, JQuerySelector context, string variable, string chain) : base(selector, context) { _chain = NotNull(() => chain); Variable = Required(() => variable); Description = $"By.JQuerySelector: {RawSelector}"; } /// <summary>Gets the empty selector.</summary> public static JQuerySelector Empty { get; } = new JQuerySelector("*"); /// <inheritdoc /> public override string CheckScript => CheckScriptCode(VARIABLE); /// <inheritdoc /> public override string Selector => $"{Variable}('{RawSelector.Replace('\'', '"')}'" + (Context != null ? $", {Context.Selector}" : string.Empty) + $"){_chain}"; /// <summary>Gets the variable that has been assigned to jQuery.</summary> public virtual string Variable { get; } /// <inheritdoc /> protected override string ResultResolver => ".get()"; /// <summary>Adds elements to the set of matched elements.</summary> /// <param name="selector"> /// A string representing a selector expression to find additional elements to add to the set of matched /// elements. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Add(string selector) => Chain("add", Required(() => selector)); /// <summary>Adds elements to the set of matched elements.</summary> /// <param name="selector"> /// A string representing a selector expression to find additional elements to add to the set of matched /// elements. /// </param> /// <param name="context">The jQuery context selector.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Add(string selector, JQuerySelector context) => ChainWithContext("add", Required(() => selector), NotNull(() => context)); /// <summary> /// Add the previous set of elements on the stack to the current set, optionally filtered by a selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector AddBack() => AddBack(null); /// <summary> /// Add the previous set of elements on the stack to the current set, optionally filtered by a selector. /// </summary> /// <param name="selector"> /// A string containing a selector expression to match the current set of elements against. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector AddBack(string selector) => Chain("addBack", NullOrNotEmpty(() => selector)); /// <summary>Add the previous set of elements on the stack to the current set.</summary> /// <returns>The Selenium jQuery selector.</returns> /// <remarks>While this method is obsolete in jQuery 1.8+ we will support it.</remarks> public JQuerySelector AndSelf() => Chain("andSelf"); /// <summary> /// Get the children of each element in the set of matched elements, optionally filtered by a selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Children() => Children(null); /// <summary> /// Get the children of each element in the set of matched elements, optionally filtered by a selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Children(string selector) => Chain("children", NullOrNotEmpty(() => selector)); /// <summary> /// For each element in the set, get the first element that matches the selector by testing the element itself /// and traversing up through its ancestors in the DOM tree. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Closest(string selector) => Chain("closest", Required(() => selector)); /// <summary> /// For each element in the set, get the first element that matches the selector by testing the element itself /// and traversing up through its ancestors in the DOM tree. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <param name="context">The jQuery context selector.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Closest(string selector, JQuerySelector context) => ChainWithContext("closest", Required(() => selector), NotNull(() => context)); /// <summary> /// Get the children of each element in the set of matched elements, including text and comment nodes. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Contents() => Chain("contents"); /// <summary> /// End the most recent filtering operation in the current chain and return the set of matched elements to its /// previous state. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector End() => Chain("end"); /// <summary>Reduce the set of matched elements to the one at the specified index.</summary> /// <param name="index">An integer indicating the 0-based position of the element.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Eq(int index) => Chain("eq", index.ToString(InvariantCulture), true); /// <summary>Reduce the set of matched elements to the even ones in the set, numbered from zero.</summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Even() => Chain("even"); /// <summary> /// Reduce the set of matched elements to those that match the selector or pass the function's test. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Filter(string selector) => Chain("filter", Required(() => selector)); /// <summary> /// Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery /// object, or element. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Find(string selector) => Chain("find", Required(() => selector)); /// <summary>Reduce the set of matched elements to the first in the set.</summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector First() => Chain("first"); /// <summary> /// Reduce the set of matched elements to those that have a descendant that matches the selector or DOM /// element. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Has(string selector) => Chain("has", Required(() => selector)); /// <summary> /// Check the current matched set of elements against a selector, element, or jQuery object and return /// <see langword="true" /> if at least one of these elements matches the given arguments. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Is(string selector) => Chain("is", Required(() => selector)); /// <summary>Reduce the set of matched elements to the final one in the set.</summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Last() => Chain("last"); /// <summary> /// Get the immediately following sibling of each element in the set of matched elements. If a selector is /// provided, it retrieves the next sibling only if it matches that selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Next() => Next(null); /// <summary> /// Get the immediately following sibling of each element in the set of matched elements. If a selector is /// provided, it retrieves the next sibling only if it matches that selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Next(string selector) => Chain("next", NullOrNotEmpty(() => selector)); /// <summary> /// Get all following siblings of each element in the set of matched elements, optionally filtered by a /// selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector NextAll() => NextAll(null); /// <summary> /// Get all following siblings of each element in the set of matched elements, optionally filtered by a /// selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector NextAll(string selector) => Chain("nextAll", NullOrNotEmpty(() => selector)); /// <summary> /// Get all following siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object passed. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector NextUntil() => NextUntil(null, null); /// <summary> /// Get all following siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object passed. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching following sibling elements. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector NextUntil(string selector) => NextUntil(selector, null); /// <summary> /// Get all following siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object passed. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching following sibling elements. /// </param> /// <param name="filter">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector NextUntil(string selector, string filter) { var validatedSelector = NullOrNotEmpty(() => selector); var validatedFilter = NullOrNotEmpty(() => filter); var filteredSelector = validatedSelector == null && validatedFilter != null ? string.Empty : validatedSelector; return Chain("nextUntil", FilteredSelector(filteredSelector, validatedFilter), true); } /// <summary>Remove elements from the set of matched elements.</summary> /// <param name="selector"> /// A string containing a selector expression, a DOM element, or an array of elements to match against the set. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Not(string selector) => Chain("not", Required(() => selector)); /// <summary>Reduce the set of matched elements to the odd ones in the set, numbered from zero.</summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Odd() => Chain("odd"); /// <summary>Get the closest ancestor element that is positioned.</summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector OffsetParent() => Chain("offsetParent"); /// <summary> /// Get the parent of each element in the current set of matched elements, optionally filtered by a selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Parent() => Parent(null); /// <summary> /// Get the parent of each element in the current set of matched elements, optionally filtered by a selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Parent(string selector) => Chain("parent", NullOrNotEmpty(() => selector)); /// <summary> /// Get the ancestors of each element in the current set of matched elements, optionally filtered by a /// selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Parents() => Parents(null); /// <summary> /// Get the ancestors of each element in the current set of matched elements, optionally filtered by a /// selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Parents(string selector) => Chain("parents", NullOrNotEmpty(() => selector)); /// <summary> /// Get the ancestors of each element in the current set of matched elements, up to but not including the /// element matched by the selector, DOM node, or jQuery object. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector ParentsUntil() => ParentsUntil(null, null); /// <summary> /// Get the ancestors of each element in the current set of matched elements, up to but not including the /// element matched by the selector, DOM node, or jQuery object. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching ancestor elements. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector ParentsUntil(string selector) => ParentsUntil(selector, null); /// <summary> /// Get the ancestors of each element in the current set of matched elements, up to but not including the /// element matched by the selector, DOM node, or jQuery object. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching ancestor elements. /// </param> /// <param name="filter">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector ParentsUntil(string selector, string filter) { var validatedSelector = NullOrNotEmpty(() => selector); var validatedFilter = NullOrNotEmpty(() => filter); var filteredSelector = validatedSelector == null && validatedFilter != null ? string.Empty : validatedSelector; return Chain("parentsUntil", FilteredSelector(filteredSelector, validatedFilter), true); } /// <summary> /// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered /// by a selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Prev() => Prev(null); /// <summary> /// Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered /// by a selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Prev(string selector) => Chain("prev", NullOrNotEmpty(() => selector)); /// <summary> /// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a /// selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector PrevAll() => PrevAll(null); /// <summary> /// Get all preceding siblings of each element in the set of matched elements, optionally filtered by a /// selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector PrevAll(string selector) => Chain("prevAll", NullOrNotEmpty(() => selector)); /// <summary> /// Get all preceding siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector PrevUntil() => PrevUntil(null, null); /// <summary> /// Get all preceding siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching preceding sibling elements. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector PrevUntil(string selector) => PrevUntil(selector, null); /// <summary> /// Get all preceding siblings of each element up to but not including the element matched by the selector, /// DOM node, or jQuery object. /// </summary> /// <param name="selector"> /// A string containing a selector expression to indicate where to stop matching preceding sibling elements. /// </param> /// <param name="filter">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector PrevUntil(string selector, string filter) { var validatedSelector = NullOrNotEmpty(() => selector); var validatedFilter = NullOrNotEmpty(() => filter); var filteredSelector = validatedSelector == null && validatedFilter != null ? string.Empty : validatedSelector; return Chain("prevUntil", FilteredSelector(filteredSelector, validatedFilter), true); } /// <summary> /// Get the siblings of each element in the set of matched elements, optionally filtered by a selector. /// </summary> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Siblings() => Siblings(null); /// <summary> /// Get the siblings of each element in the set of matched elements, optionally filtered by a selector. /// </summary> /// <param name="selector">A string containing a selector expression to match elements against.</param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Siblings(string selector) => Chain("siblings", NullOrNotEmpty(() => selector)); /// <summary>Reduce the set of matched elements to a subset specified by a range of indexes.</summary> /// <param name="start"> /// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it /// indicates an offset from the end of the set. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Slice(int start) => Slice(start, null); /// <summary>Reduce the set of matched elements to a subset specified by a range of indexes.</summary> /// <param name="start"> /// An integer indicating the 0-based position at which the elements begin to be selected. If negative, it /// indicates an offset from the end of the set. /// </param> /// <param name="end"> /// An integer indicating the 0-based position at which the elements stop being selected. If negative, it /// indicates an offset from the end of the set. If omitted, the range continues until the end of the set. /// </param> /// <returns>The Selenium jQuery selector.</returns> public JQuerySelector Slice(int start, int? end) => Chain("slice", end.HasValue ? $"{start}, {end}" : start.ToString(InvariantCulture), true); /// <inheritdoc /> protected override JQuerySelector CreateContext(string contextSelector) => new(contextSelector, null, Variable); /// <inheritdoc /> protected override void LoadExternalLibrary(IWebDriver driver) => driver.LoadJQuery(); [SuppressMessage(SONARQUBE, S3358)] private static string FilteredSelector(string selector = null, string filter = null) => selector != null ? IsNullOrEmpty(filter) ? $"'{selector.Replace('\'', '"')}'" : $"'{selector.Replace('\'', '"')}', '{filter.Replace('\'', '"')}'" : string.Empty; [SuppressMessage(SONARQUBE, S3358)] private static string GetSelectorString(string selector, bool noWrap = false) => selector == null ? string.Empty : noWrap ? selector.Trim() : $"'{selector.Trim().Replace('\'', '"')}'"; private JQuerySelector Chain(string name, string selector = null, bool noWrap = false) => new(RawSelector, Context, Variable, $"{_chain}.{name}({GetSelectorString(selector, noWrap)})"); [SuppressMessage(SONARQUBE, S3242)] private JQuerySelector ChainWithContext(string name, string selector, JQuerySelector context) => new(RawSelector, Context, Variable, $".{name}('{selector.Replace('\'', '"')}', {context.Selector})"); } }
// *********************************************************************** // Copyright (c) 2012 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.Generic; using System.Threading; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Internal.Commands; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Internal.Execution { /// <summary> /// A CompositeWorkItem represents a test suite and /// encapsulates the execution of the suite as well /// as all its child tests. /// </summary> public class CompositeWorkItem : WorkItem { // static Logger log = InternalTrace.GetLogger("CompositeWorkItem"); private TestSuite _suite; private TestSuiteResult _suiteResult; private TestCommand _setupCommand; private TestCommand _teardownCommand; /// <summary> /// List of Child WorkItems /// </summary> public List<WorkItem> Children { get; } = new List<WorkItem>(); private CountdownEvent _childTestCountdown; /// <summary> /// Construct a CompositeWorkItem for executing a test suite /// using a filter to select child tests. /// </summary> /// <param name="suite">The TestSuite to be executed</param> /// <param name="childFilter">A filter used to select child tests</param> public CompositeWorkItem(TestSuite suite, ITestFilter childFilter) : base(suite, childFilter) { _suite = suite; _suiteResult = Result as TestSuiteResult; } /// <summary> /// Method that actually performs the work. Overridden /// in CompositeWorkItem to do one-time setup, run all child /// items and then dispatch the one-time teardown work item. /// </summary> protected override void PerformWork() { if (!CheckForCancellation()) if (Test.RunState == RunState.Explicit && !Filter.IsExplicitMatch(Test)) SkipFixture(ResultState.Explicit, GetSkipReason(), null); else switch (Test.RunState) { default: case RunState.Runnable: case RunState.Explicit: // Assume success, since the result will otherwise // default to inconclusive. Result.SetResult(ResultState.Success); if (Children.Count > 0) { InitializeSetUpAndTearDownCommands(); PerformOneTimeSetUp(); if (!CheckForCancellation()) { switch (Result.ResultState.Status) { case TestStatus.Passed: case TestStatus.Warning: RunChildren(); return; // Just return: completion event will take care // of OneTimeTearDown when all tests are done. case TestStatus.Skipped: case TestStatus.Inconclusive: case TestStatus.Failed: SkipChildren(this, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message); break; } } // Directly execute the OneTimeFixtureTearDown for tests that // were skipped, failed or set to inconclusive in one time setup // unless we are aborting. if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) PerformOneTimeTearDown(); } else if (Test.TestType == "Theory") Result.SetResult(ResultState.Failure, "No test cases were provided"); break; case RunState.Skipped: SkipFixture(ResultState.Skipped, GetSkipReason(), null); break; case RunState.Ignored: SkipFixture(ResultState.Ignored, GetSkipReason(), null); break; case RunState.NotRunnable: SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace()); break; } // Fall through in case nothing was run. // Otherwise, this is done in the completion event. WorkItemComplete(); } #region Helper Methods private bool CheckForCancellation() { if (Context.ExecutionStatus != TestExecutionStatus.Running) { Result.SetResult(ResultState.Cancelled, "Test cancelled by user"); return true; } return false; } private void InitializeSetUpAndTearDownCommands() { List<SetUpTearDownItem> setUpTearDownItems = BuildSetUpTearDownList(_suite.OneTimeSetUpMethods, _suite.OneTimeTearDownMethods); var actionItems = new List<TestActionItem>(); foreach (ITestAction action in Test.Actions) { // We need to go through all the actions on the test to determine which ones // will be used immediately and which will go into the context for use by // lower level tests. // // Special handling here for ParameterizedMethodSuite is a bit ugly. However, // it is needed because Tests are not supposed to know anything about Action // Attributes (or any attribute) and Attributes don't know where they were // initially applied unless we tell them. // // ParameterizedMethodSuites and individual test cases both use the same // MethodInfo as a source of attributes. We handle the Test and Default targets // in the test case, so we don't want to doubly handle it here. bool applyToSuite = action.Targets.HasFlag(ActionTargets.Suite) || action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite); bool applyToTest = action.Targets.HasFlag(ActionTargets.Test) && !(Test is ParameterizedMethodSuite); if (applyToSuite) actionItems.Add(new TestActionItem(action)); if (applyToTest) Context.UpstreamActions.Add(action); } _setupCommand = MakeOneTimeSetUpCommand(setUpTearDownItems, actionItems); _teardownCommand = MakeOneTimeTearDownCommand(setUpTearDownItems, actionItems); } private TestCommand MakeOneTimeSetUpCommand(List<SetUpTearDownItem> setUpTearDown, List<TestActionItem> actions) { TestCommand command = new EmptyTestCommand(Test); // Add Action Commands int index = actions.Count; while (--index >= 0) command = new BeforeTestActionCommand(command, actions[index]); if (Test.TypeInfo != null) { // Build the OneTimeSetUpCommands foreach (SetUpTearDownItem item in setUpTearDown) command = new OneTimeSetUpCommand(command, item); // Construct the fixture if necessary if (!Test.TypeInfo.IsStaticClass) command = new ConstructFixtureCommand(command); } // Prefix with any IApplyToContext items from attributes foreach (var attr in Test.GetCustomAttributes<IApplyToContext>(true)) command = new ApplyChangesToContextCommand(command, attr); return command; } private TestCommand MakeOneTimeTearDownCommand(List<SetUpTearDownItem> setUpTearDownItems, List<TestActionItem> actions) { TestCommand command = new EmptyTestCommand(Test); // For Theories, follow with TheoryResultCommand to adjust result as needed if (Test.TestType == "Theory") command = new TheoryResultCommand(command); // Create the AfterTestAction commands int index = actions.Count; while (--index >= 0) command = new AfterTestActionCommand(command, actions[index]); // Create the OneTimeTearDown commands foreach (SetUpTearDownItem item in setUpTearDownItems) command = new OneTimeTearDownCommand(command, item); // Dispose of fixture if necessary if (Test is IDisposableFixture && typeof(IDisposable).IsAssignableFrom(Test.TypeInfo.Type)) command = new DisposeFixtureCommand(command); return command; } private void PerformOneTimeSetUp() { try { _setupCommand.Execute(Context); // SetUp may have changed some things in the environment Context.UpdateContextFromEnvironment(); } catch (Exception ex) { if (ex is NUnitException || ex is TargetInvocationException) ex = ex.InnerException; Result.RecordException(ex, FailureSite.SetUp); } } private void RunChildren() { if (Test.TestType == "Theory") Result.SetResult(ResultState.Inconclusive); int childCount = Children.Count; if (childCount == 0) throw new InvalidOperationException("RunChildren called but item has no children"); _childTestCountdown = new CountdownEvent(childCount); foreach (WorkItem child in Children) { if (CheckForCancellation()) break; child.Completed += new EventHandler(OnChildItemCompleted); child.InitializeContext(new TestExecutionContext(Context)); #if PARALLEL // In case we run directly, on same thread child.TestWorker = TestWorker; #endif Context.Dispatcher.Dispatch(child); childCount--; } // If run was cancelled, reduce countdown by number of // child items not yet staged and check if we are done. if (childCount > 0) lock(_childCompletionLock) { _childTestCountdown.Signal(childCount); if (_childTestCountdown.CurrentCount == 0) OnAllChildItemsCompleted(); } } private void SkipFixture(ResultState resultState, string message, string stackTrace) { Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.DefaultFilter.Filter(stackTrace)); SkipChildren(this, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message); } private void SkipChildren(CompositeWorkItem workItem, ResultState resultState, string message) { foreach (WorkItem child in workItem.Children) { child.Result.SetResult(resultState, message); _suiteResult.AddResult(child.Result); // Some runners may depend on getting the TestFinished event // even for tests that have been skipped at a higher level. Context.Listener.TestFinished(child.Result); if (child is CompositeWorkItem) SkipChildren((CompositeWorkItem)child, resultState, message); } } private void PerformOneTimeTearDown() { // Our child tests or even unrelated tests may have // executed on the same thread since the time that // this test started, so we have to re-establish // the proper execution environment this.Context.EstablishExecutionEnvironment(); _teardownCommand.Execute(this.Context); } private string GetSkipReason() { return (string)Test.Properties.Get(PropertyNames.SkipReason); } private string GetProviderStackTrace() { return (string)Test.Properties.Get(PropertyNames.ProviderStackTrace); } private object _childCompletionLock = new object(); private void OnChildItemCompleted(object sender, EventArgs e) { // Since child tests may be run on various threads, this // method may be called simultaneously by different children. // The lock is a member of the parent item and thereore // only blocks its own children. lock (_childCompletionLock) { WorkItem childTask = sender as WorkItem; if (childTask != null) { childTask.Completed -= new EventHandler(OnChildItemCompleted); _suiteResult.AddResult(childTask.Result); if (Context.StopOnError && childTask.Result.ResultState.Status == TestStatus.Failed) Context.ExecutionStatus = TestExecutionStatus.StopRequested; // Check to see if all children completed _childTestCountdown.Signal(); if (_childTestCountdown.CurrentCount == 0) OnAllChildItemsCompleted(); } } } /// <summary> /// /// </summary> private void OnAllChildItemsCompleted() { var teardown = new OneTimeTearDownWorkItem(this); Context.Dispatcher.Dispatch(teardown); } private static bool IsStaticClass(Type type) { return type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed; } private object cancelLock = new object(); /// <summary> /// Cancel (abort or stop) a CompositeWorkItem and all of its children /// </summary> /// <param name="force">true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete</param> public override void Cancel(bool force) { lock (cancelLock) { foreach (var child in Children) { var ctx = child.Context; if (ctx != null) ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; if (child.State == WorkItemState.Running) child.Cancel(force); } } } #endregion #region Nested OneTimeTearDownWorkItem Class /// <summary> /// OneTimeTearDownWorkItem represents the cleanup /// and one-time teardown phase of a CompositeWorkItem /// </summary> public class OneTimeTearDownWorkItem : WorkItem { private CompositeWorkItem _originalWorkItem; private object _teardownLock = new object(); /// <summary> /// Construct a OneTimeTearDownWOrkItem wrapping a CompositeWorkItem /// </summary> /// <param name="originalItem">The CompositeWorkItem being wrapped</param> public OneTimeTearDownWorkItem(CompositeWorkItem originalItem) : base(originalItem) { _originalWorkItem = originalItem; } /// <summary> /// The WorkItem name, overridden to indicate this is the teardown. /// </summary> public override string Name { get { return string.Format("{0} OneTimeTearDown", base.Name); } } #if PARALLEL /// <summary> /// The ExecutionStrategy for use in running this work item /// </summary> public override ParallelExecutionStrategy ExecutionStrategy { get { return _originalWorkItem.ExecutionStrategy; } } #endif /// <summary> /// /// </summary> public override void Execute() { lock (_teardownLock) { //if (Test.Parent != null && Test.Parent.Name.EndsWith("nunit.framework.tests.dll")) // System.Diagnostics.Debugger.Launch(); if (Test.TestType == "Theory" && Result.ResultState == ResultState.Success && Result.PassCount == 0) Result.SetResult(ResultState.Failure, "No test cases were provided"); if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested) _originalWorkItem.PerformOneTimeTearDown(); foreach (var childResult in Result.Children) if (childResult.ResultState == ResultState.Cancelled) { this.Result.SetResult(ResultState.Cancelled, "Cancelled by user"); break; } _originalWorkItem.WorkItemComplete(); } } /// <summary> /// PerformWork is not used in CompositeWorkItem /// </summary> protected override void PerformWork() { } } #endregion } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework.Api; namespace NUnit.Framework.Internal { /// <summary> /// ParameterSet encapsulates method arguments and /// other selected parameters needed for constructing /// a parameterized test case. /// </summary> public class ParameterSet : ITestCaseData, IApplyToTest { #region Instance Fields private object[] arguments; private object[] originalArguments; private object result; private bool hasExpectedResult; private ExpectedExceptionData exceptionData; /// <summary> /// A dictionary of properties, used to add information /// to tests without requiring the class to change. /// </summary> private IPropertyBag properties; #endregion #region Properties private RunState runState; /// <summary> /// The RunState for this set of parameters. /// </summary> public RunState RunState { get { return runState; } set { runState = value; } } /// <summary> /// The arguments to be used in running the test, /// which must match the method signature. /// </summary> public object[] Arguments { get { return arguments; } set { arguments = value; if (originalArguments == null) originalArguments = value; } } /// <summary> /// The original arguments provided by the user, /// used for display purposes. /// </summary> public object[] OriginalArguments { get { return originalArguments; } } /// <summary> /// Gets a flag indicating whether an exception is expected. /// </summary> public bool ExceptionExpected { get { return exceptionData.ExpectedExceptionName != null; } } /// <summary> /// Data about any expected exception /// </summary> public ExpectedExceptionData ExceptionData { get { return exceptionData; } } /// <summary> /// The expected result of the test, which /// must match the method return type. /// </summary> public object ExpectedResult { get { return result; } set { result = value; hasExpectedResult = true; } } /// <summary> /// Gets a value indicating whether an expected result was specified. /// </summary> public bool HasExpectedResult { get { return hasExpectedResult; } } private string testName; /// <summary> /// A name to be used for this test case in lieu /// of the standard generated name containing /// the argument list. /// </summary> public string TestName { get { return testName; } set { testName = value; } } /// <summary> /// Gets the property dictionary for this test /// </summary> public IPropertyBag Properties { get { if (properties == null) properties = new PropertyBag(); return properties; } } #endregion #region Constructors /// <summary> /// Construct a non-runnable ParameterSet, specifying /// the provider exception that made it invalid. /// </summary> public ParameterSet(Exception exception) { this.RunState = RunState.NotRunnable; this.Properties.Set(PropertyNames.SkipReason, ExceptionHelper.BuildMessage(exception)); this.Properties.Set(PropertyNames.ProviderStackTrace, ExceptionHelper.BuildStackTrace(exception)); } /// <summary> /// Construct an empty parameter set, which /// defaults to being Runnable. /// </summary> public ParameterSet() { this.RunState = RunState.Runnable; } /// <summary> /// Construct a ParameterSet from an object implementing ITestCaseData /// </summary> /// <param name="data"></param> public ParameterSet(ITestCaseData data) { this.TestName = data.TestName; this.RunState = data.RunState; this.Arguments = data.Arguments; this.exceptionData = data.ExceptionData; if (data.HasExpectedResult) this.ExpectedResult = data.ExpectedResult; foreach (string key in data.Properties.Keys) this.Properties[key] = data.Properties[key]; } #endregion #region IApplyToTest Members /// <summary> /// Applies ParameterSet values to the test itself. /// </summary> /// <param name="test">A test.</param> public void ApplyToTest(Test test) { if (this.RunState != RunState.Runnable) test.RunState = this.RunState; foreach (string key in Properties.Keys) foreach (object value in Properties[key]) test.Properties.Add(key, value); TestMethod testMethod = test as TestMethod; if (testMethod != null && exceptionData.ExpectedExceptionName != null) testMethod.CustomDecorators.Add(new ExpectedExceptionDecorator(this.ExceptionData)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 RoundCurrentDirectionSingle() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__RoundCurrentDirectionSingle { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / sizeof(Single); private static Single[] _data = new Single[Op1ElementCount]; private static Vector256<Single> _clsVar; private Vector256<Single> _fld; private SimpleUnaryOpTest__DataTable<Single, Single> _dataTable; static SimpleUnaryOpTest__RoundCurrentDirectionSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _clsVar), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__RoundCurrentDirectionSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Single>, byte>(ref _fld), ref Unsafe.As<Single, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (float)(random.NextDouble()); } _dataTable = new SimpleUnaryOpTest__DataTable<Single, Single>(_data, new Single[RetElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.RoundCurrentDirection( Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.RoundCurrentDirection( Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.RoundCurrentDirection( Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundCurrentDirection), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundCurrentDirection), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.RoundCurrentDirection), new Type[] { typeof(Vector256<Single>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Single>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.RoundCurrentDirection( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Single>>(_dataTable.inArrayPtr); var result = Avx.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Single*)(_dataTable.inArrayPtr)); var result = Avx.RoundCurrentDirection(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__RoundCurrentDirectionSingle(); var result = Avx.RoundCurrentDirection(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.RoundCurrentDirection(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Single> firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Single[] inArray = new Single[Op1ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Single[] firstOp, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(MathF.Round(firstOp[i]))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.RoundCurrentDirection)}<Single>(Vector256<Single>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Rest.Azure; using Models; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Checks the availability of the given service namespace across all /// Azure subscriptions. This is useful because the domain name is /// created based on the service namespace name. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" /> /// </summary> /// <param name='parameters'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckAvailabilityResult>> CheckAvailabilityWithHttpMessagesAsync(CheckAvailabilityParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates/Updates a service namespace. Once created, this /// namespace's resource manifest is immutable. This operation is /// idempotent. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated notificationHubs under the namespace. /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns the description for the specified namespace. /// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets an authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. If resourceGroupName value is null /// the method lists all the namespaces within subscription /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the namespace /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the Namespace /// Authorization Rule /// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the namespace for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the Namespace Authorization Rule /// Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NamespaceResource>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets the authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // UnionQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Operator that yields the union of two data sources. /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class UnionQueryOperator<TInputOutput> : BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer. //--------------------------------------------------------------------------------------- // Constructs a new union operator. // internal UnionQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer) : base(left, right) { Debug.Assert(left != null && right != null, "child data sources cannot be null"); _comparer = comparer; _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TInputOutput> Open( QuerySettings settings, bool preferStriping) { // We just open our child operators, left and then right. Do not propagate the preferStriping value, but // instead explicitly set it to false. Regardless of whether the parent prefers striping or range // partitioning, the output will be hash-partitioned. QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false); QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false); return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TInputOutput, TLeftKey> leftStream, PartitionedStream<TInputOutput, TRightKey> rightStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings) { Debug.Assert(leftStream.PartitionCount == rightStream.PartitionCount); int partitionCount = leftStream.PartitionCount; // Wrap both child streams with hash repartition if (LeftChild.OutputOrdered) { PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream = ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken); WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>( leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken); } else { PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> leftHashStream = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken); WrapPartitionedStreamFixedLeftType<int, TRightKey>( leftHashStream, rightStream, outputRecipient, partitionCount, settings.CancellationState.MergedCancellationToken); } } //--------------------------------------------------------------------------------------- // A helper method that allows WrapPartitionedStream to fix the TLeftKey type parameter. // private void WrapPartitionedStreamFixedLeftType<TLeftKey, TRightKey>( PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount, CancellationToken cancellationToken) { if (RightChild.OutputOrdered) { PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightHashStream = ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TRightKey>( rightStream, null, null, _comparer, cancellationToken); WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>( leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken); } else { PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, int> rightHashStream = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>( rightStream, null, null, _comparer, cancellationToken); WrapPartitionedStreamFixedBothTypes<TLeftKey, int>( leftHashStream, rightHashStream, outputRecipient, partitionCount, cancellationToken); } } //--------------------------------------------------------------------------------------- // A helper method that allows WrapPartitionedStreamHelper to fix the TRightKey type parameter. // private void WrapPartitionedStreamFixedBothTypes<TLeftKey, TRightKey>( PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftHashStream, PartitionedStream<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightHashStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, int partitionCount, CancellationToken cancellationToken) { if (LeftChild.OutputOrdered || RightChild.OutputOrdered) { IComparer<ConcatKey<TLeftKey, TRightKey>> compoundKeyComparer = ConcatKey<TLeftKey, TRightKey>.MakeComparer(leftHashStream.KeyComparer, rightHashStream.KeyComparer); PartitionedStream<TInputOutput, ConcatKey<TLeftKey, TRightKey>> outputStream = new PartitionedStream<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(partitionCount, compoundKeyComparer, OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey>( leftHashStream[i], rightHashStream[i], LeftChild.OutputOrdered, RightChild.OutputOrdered, _comparer, compoundKeyComparer, cancellationToken); } outputRecipient.Receive(outputStream); } else { PartitionedStream<TInputOutput, int> outputStream = new PartitionedStream<TInputOutput, int>(partitionCount, Util.GetDefaultComparer<int>(), OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new UnionQueryOperatorEnumerator<TLeftKey, TRightKey>( leftHashStream[i], rightHashStream[i], _comparer, cancellationToken); } outputRecipient.Receive(outputStream); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token); IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token); return wrappedLeftChild.Union(wrappedRightChild, _comparer); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator performs the union operation incrementally. It does this by maintaining // a history -- in the form of a set -- of all data already seen. It is careful not to // return any duplicates. // class UnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, int> { private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> _rightSource; // Right data source. private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the union. private CancellationToken _cancellationToken; private Shared<int> _outputLoopCount; private readonly IEqualityComparer<TInputOutput> _comparer; //--------------------------------------------------------------------------------------- // Instantiates a new union operator. // internal UnionQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource, QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightSource, IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = comparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the union. // internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { if (_hashLookup == null) { _hashLookup = new Set<TInputOutput>(_comparer); _outputLoopCount = new Shared<int>(0); } Debug.Assert(_hashLookup != null); // Enumerate the left and then right data source. When each is done, we set the // field to null so we will skip it upon subsequent calls to MoveNext. if (_leftSource != null) { // Iterate over this set's elements until we find a unique element. TLeftKey keyUnused = default(TLeftKey); Pair<TInputOutput, NoKeyMemoizationRequired> currentLeftElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>); int i = 0; while (_leftSource.MoveNext(ref currentLeftElement, ref keyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // We ensure we never return duplicates by tracking them in our set. if (_hashLookup.Add(currentLeftElement.First)) { #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif currentElement = currentLeftElement.First; return true; } } _leftSource.Dispose(); _leftSource = null; } if (_rightSource != null) { // Iterate over this set's elements until we find a unique element. TRightKey keyUnused = default(TRightKey); Pair<TInputOutput, NoKeyMemoizationRequired> currentRightElement = default(Pair<TInputOutput, NoKeyMemoizationRequired>); while (_rightSource.MoveNext(ref currentRightElement, ref keyUnused)) { if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); // We ensure we never return duplicates by tracking them in our set. if (_hashLookup.Add(currentRightElement.First)) { #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif currentElement = currentRightElement.First; return true; } } _rightSource.Dispose(); _rightSource = null; } return false; } protected override void Dispose(bool disposing) { if (_leftSource != null) { _leftSource.Dispose(); } if (_rightSource != null) { _rightSource.Dispose(); } } } class OrderedUnionQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TInputOutput, ConcatKey<TLeftKey, TRightKey>> { private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> _rightSource; // Right data source. private IComparer<ConcatKey<TLeftKey, TRightKey>> _keyComparer; // Comparer for compound order keys. private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>>> _outputEnumerator; // Enumerator over the output of the union. private bool _leftOrdered; // Whether the left data source is ordered. private bool _rightOrdered; // Whether the right data source is ordered. private IEqualityComparer<TInputOutput> _comparer; // Comparer for the elements. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new union operator. // internal OrderedUnionQueryOperatorEnumerator( QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TLeftKey> leftSource, QueryOperatorEnumerator<Pair<TInputOutput, NoKeyMemoizationRequired>, TRightKey> rightSource, bool leftOrdered, bool rightOrdered, IEqualityComparer<TInputOutput> comparer, IComparer<ConcatKey<TLeftKey, TRightKey>> keyComparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _keyComparer = keyComparer; _leftOrdered = leftOrdered; _rightOrdered = rightOrdered; _comparer = comparer; if (_comparer == null) { _comparer = EqualityComparer<TInputOutput>.Default; } _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the union. // internal override bool MoveNext(ref TInputOutput currentElement, ref ConcatKey<TLeftKey, TRightKey> currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); if (_outputEnumerator == null) { IEqualityComparer<Wrapper<TInputOutput>> wrapperComparer = new WrapperEqualityComparer<TInputOutput>(_comparer); Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>> union = new Dictionary<Wrapper<TInputOutput>, Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>>(wrapperComparer); Pair<TInputOutput, NoKeyMemoizationRequired> elem = default(Pair<TInputOutput, NoKeyMemoizationRequired>); TLeftKey leftKey = default(TLeftKey); int i = 0; while (_leftSource.MoveNext(ref elem, ref leftKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); ConcatKey<TLeftKey, TRightKey> key = ConcatKey<TLeftKey, TRightKey>.MakeLeft(_leftOrdered ? leftKey : default(TLeftKey)); Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> oldEntry; Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First); if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, oldEntry.Second) < 0) { union[wrappedElem] = new Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(elem.First, key); } } TRightKey rightKey = default(TRightKey); while (_rightSource.MoveNext(ref elem, ref rightKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); ConcatKey<TLeftKey, TRightKey> key = ConcatKey<TLeftKey, TRightKey>.MakeRight(_rightOrdered ? rightKey : default(TRightKey)); Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> oldEntry; Wrapper<TInputOutput> wrappedElem = new Wrapper<TInputOutput>(elem.First); if (!union.TryGetValue(wrappedElem, out oldEntry) || _keyComparer.Compare(key, oldEntry.Second) < 0) { union[wrappedElem] = new Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>>(elem.First, key); } } _outputEnumerator = union.GetEnumerator(); } if (_outputEnumerator.MoveNext()) { Pair<TInputOutput, ConcatKey<TLeftKey, TRightKey>> current = _outputEnumerator.Current.Value; currentElement = current.First; currentKey = current.Second; return true; } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } } }
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; namespace DalSic { /// <summary> /// Strongly-typed collection for the AprPercentilesIMCEdad class. /// </summary> [Serializable] public partial class AprPercentilesIMCEdadCollection : ActiveList<AprPercentilesIMCEdad, AprPercentilesIMCEdadCollection> { public AprPercentilesIMCEdadCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>AprPercentilesIMCEdadCollection</returns> public AprPercentilesIMCEdadCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { AprPercentilesIMCEdad 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 APR_PercentilesIMCEdad table. /// </summary> [Serializable] public partial class AprPercentilesIMCEdad : ActiveRecord<AprPercentilesIMCEdad>, IActiveRecord { #region .ctors and Default Settings public AprPercentilesIMCEdad() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public AprPercentilesIMCEdad(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public AprPercentilesIMCEdad(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public AprPercentilesIMCEdad(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("APR_PercentilesIMCEdad", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = true; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarSexo = new TableSchema.TableColumn(schema); colvarSexo.ColumnName = "Sexo"; colvarSexo.DataType = DbType.Int32; colvarSexo.MaxLength = 0; colvarSexo.AutoIncrement = false; colvarSexo.IsNullable = false; colvarSexo.IsPrimaryKey = false; colvarSexo.IsForeignKey = false; colvarSexo.IsReadOnly = false; colvarSexo.DefaultSetting = @""; colvarSexo.ForeignKeyTableName = ""; schema.Columns.Add(colvarSexo); TableSchema.TableColumn colvarEdad = new TableSchema.TableColumn(schema); colvarEdad.ColumnName = "Edad"; colvarEdad.DataType = DbType.Int32; colvarEdad.MaxLength = 0; colvarEdad.AutoIncrement = false; colvarEdad.IsNullable = false; colvarEdad.IsPrimaryKey = false; colvarEdad.IsForeignKey = false; colvarEdad.IsReadOnly = false; colvarEdad.DefaultSetting = @""; colvarEdad.ForeignKeyTableName = ""; schema.Columns.Add(colvarEdad); TableSchema.TableColumn colvarL = new TableSchema.TableColumn(schema); colvarL.ColumnName = "L"; colvarL.DataType = DbType.Decimal; colvarL.MaxLength = 0; colvarL.AutoIncrement = false; colvarL.IsNullable = false; colvarL.IsPrimaryKey = false; colvarL.IsForeignKey = false; colvarL.IsReadOnly = false; colvarL.DefaultSetting = @""; colvarL.ForeignKeyTableName = ""; schema.Columns.Add(colvarL); TableSchema.TableColumn colvarM = new TableSchema.TableColumn(schema); colvarM.ColumnName = "M"; colvarM.DataType = DbType.Decimal; colvarM.MaxLength = 0; colvarM.AutoIncrement = false; colvarM.IsNullable = false; colvarM.IsPrimaryKey = false; colvarM.IsForeignKey = false; colvarM.IsReadOnly = false; colvarM.DefaultSetting = @""; colvarM.ForeignKeyTableName = ""; schema.Columns.Add(colvarM); TableSchema.TableColumn colvarS = new TableSchema.TableColumn(schema); colvarS.ColumnName = "S"; colvarS.DataType = DbType.Decimal; colvarS.MaxLength = 0; colvarS.AutoIncrement = false; colvarS.IsNullable = false; colvarS.IsPrimaryKey = false; colvarS.IsForeignKey = false; colvarS.IsReadOnly = false; colvarS.DefaultSetting = @""; colvarS.ForeignKeyTableName = ""; schema.Columns.Add(colvarS); TableSchema.TableColumn colvarP01 = new TableSchema.TableColumn(schema); colvarP01.ColumnName = "P01"; colvarP01.DataType = DbType.Decimal; colvarP01.MaxLength = 0; colvarP01.AutoIncrement = false; colvarP01.IsNullable = false; colvarP01.IsPrimaryKey = false; colvarP01.IsForeignKey = false; colvarP01.IsReadOnly = false; colvarP01.DefaultSetting = @""; colvarP01.ForeignKeyTableName = ""; schema.Columns.Add(colvarP01); TableSchema.TableColumn colvarP1 = new TableSchema.TableColumn(schema); colvarP1.ColumnName = "P1"; colvarP1.DataType = DbType.Decimal; colvarP1.MaxLength = 0; colvarP1.AutoIncrement = false; colvarP1.IsNullable = false; colvarP1.IsPrimaryKey = false; colvarP1.IsForeignKey = false; colvarP1.IsReadOnly = false; colvarP1.DefaultSetting = @""; colvarP1.ForeignKeyTableName = ""; schema.Columns.Add(colvarP1); TableSchema.TableColumn colvarP3 = new TableSchema.TableColumn(schema); colvarP3.ColumnName = "P3"; colvarP3.DataType = DbType.Decimal; colvarP3.MaxLength = 0; colvarP3.AutoIncrement = false; colvarP3.IsNullable = false; colvarP3.IsPrimaryKey = false; colvarP3.IsForeignKey = false; colvarP3.IsReadOnly = false; colvarP3.DefaultSetting = @""; colvarP3.ForeignKeyTableName = ""; schema.Columns.Add(colvarP3); TableSchema.TableColumn colvarP5 = new TableSchema.TableColumn(schema); colvarP5.ColumnName = "P5"; colvarP5.DataType = DbType.Decimal; colvarP5.MaxLength = 0; colvarP5.AutoIncrement = false; colvarP5.IsNullable = false; colvarP5.IsPrimaryKey = false; colvarP5.IsForeignKey = false; colvarP5.IsReadOnly = false; colvarP5.DefaultSetting = @""; colvarP5.ForeignKeyTableName = ""; schema.Columns.Add(colvarP5); TableSchema.TableColumn colvarP10 = new TableSchema.TableColumn(schema); colvarP10.ColumnName = "P10"; colvarP10.DataType = DbType.Decimal; colvarP10.MaxLength = 0; colvarP10.AutoIncrement = false; colvarP10.IsNullable = false; colvarP10.IsPrimaryKey = false; colvarP10.IsForeignKey = false; colvarP10.IsReadOnly = false; colvarP10.DefaultSetting = @""; colvarP10.ForeignKeyTableName = ""; schema.Columns.Add(colvarP10); TableSchema.TableColumn colvarP15 = new TableSchema.TableColumn(schema); colvarP15.ColumnName = "P15"; colvarP15.DataType = DbType.Decimal; colvarP15.MaxLength = 0; colvarP15.AutoIncrement = false; colvarP15.IsNullable = false; colvarP15.IsPrimaryKey = false; colvarP15.IsForeignKey = false; colvarP15.IsReadOnly = false; colvarP15.DefaultSetting = @""; colvarP15.ForeignKeyTableName = ""; schema.Columns.Add(colvarP15); TableSchema.TableColumn colvarP25 = new TableSchema.TableColumn(schema); colvarP25.ColumnName = "P25"; colvarP25.DataType = DbType.Decimal; colvarP25.MaxLength = 0; colvarP25.AutoIncrement = false; colvarP25.IsNullable = false; colvarP25.IsPrimaryKey = false; colvarP25.IsForeignKey = false; colvarP25.IsReadOnly = false; colvarP25.DefaultSetting = @""; colvarP25.ForeignKeyTableName = ""; schema.Columns.Add(colvarP25); TableSchema.TableColumn colvarP50 = new TableSchema.TableColumn(schema); colvarP50.ColumnName = "P50"; colvarP50.DataType = DbType.Decimal; colvarP50.MaxLength = 0; colvarP50.AutoIncrement = false; colvarP50.IsNullable = false; colvarP50.IsPrimaryKey = false; colvarP50.IsForeignKey = false; colvarP50.IsReadOnly = false; colvarP50.DefaultSetting = @""; colvarP50.ForeignKeyTableName = ""; schema.Columns.Add(colvarP50); TableSchema.TableColumn colvarP75 = new TableSchema.TableColumn(schema); colvarP75.ColumnName = "P75"; colvarP75.DataType = DbType.Decimal; colvarP75.MaxLength = 0; colvarP75.AutoIncrement = false; colvarP75.IsNullable = false; colvarP75.IsPrimaryKey = false; colvarP75.IsForeignKey = false; colvarP75.IsReadOnly = false; colvarP75.DefaultSetting = @""; colvarP75.ForeignKeyTableName = ""; schema.Columns.Add(colvarP75); TableSchema.TableColumn colvarP85 = new TableSchema.TableColumn(schema); colvarP85.ColumnName = "P85"; colvarP85.DataType = DbType.Decimal; colvarP85.MaxLength = 0; colvarP85.AutoIncrement = false; colvarP85.IsNullable = false; colvarP85.IsPrimaryKey = false; colvarP85.IsForeignKey = false; colvarP85.IsReadOnly = false; colvarP85.DefaultSetting = @""; colvarP85.ForeignKeyTableName = ""; schema.Columns.Add(colvarP85); TableSchema.TableColumn colvarP90 = new TableSchema.TableColumn(schema); colvarP90.ColumnName = "P90"; colvarP90.DataType = DbType.Decimal; colvarP90.MaxLength = 0; colvarP90.AutoIncrement = false; colvarP90.IsNullable = false; colvarP90.IsPrimaryKey = false; colvarP90.IsForeignKey = false; colvarP90.IsReadOnly = false; colvarP90.DefaultSetting = @""; colvarP90.ForeignKeyTableName = ""; schema.Columns.Add(colvarP90); TableSchema.TableColumn colvarP95 = new TableSchema.TableColumn(schema); colvarP95.ColumnName = "P95"; colvarP95.DataType = DbType.Decimal; colvarP95.MaxLength = 0; colvarP95.AutoIncrement = false; colvarP95.IsNullable = false; colvarP95.IsPrimaryKey = false; colvarP95.IsForeignKey = false; colvarP95.IsReadOnly = false; colvarP95.DefaultSetting = @""; colvarP95.ForeignKeyTableName = ""; schema.Columns.Add(colvarP95); TableSchema.TableColumn colvarP97 = new TableSchema.TableColumn(schema); colvarP97.ColumnName = "P97"; colvarP97.DataType = DbType.Decimal; colvarP97.MaxLength = 0; colvarP97.AutoIncrement = false; colvarP97.IsNullable = false; colvarP97.IsPrimaryKey = false; colvarP97.IsForeignKey = false; colvarP97.IsReadOnly = false; colvarP97.DefaultSetting = @""; colvarP97.ForeignKeyTableName = ""; schema.Columns.Add(colvarP97); TableSchema.TableColumn colvarP99 = new TableSchema.TableColumn(schema); colvarP99.ColumnName = "P99"; colvarP99.DataType = DbType.Decimal; colvarP99.MaxLength = 0; colvarP99.AutoIncrement = false; colvarP99.IsNullable = false; colvarP99.IsPrimaryKey = false; colvarP99.IsForeignKey = false; colvarP99.IsReadOnly = false; colvarP99.DefaultSetting = @""; colvarP99.ForeignKeyTableName = ""; schema.Columns.Add(colvarP99); TableSchema.TableColumn colvarP999 = new TableSchema.TableColumn(schema); colvarP999.ColumnName = "P999"; colvarP999.DataType = DbType.Decimal; colvarP999.MaxLength = 0; colvarP999.AutoIncrement = false; colvarP999.IsNullable = false; colvarP999.IsPrimaryKey = false; colvarP999.IsForeignKey = false; colvarP999.IsReadOnly = false; colvarP999.DefaultSetting = @""; colvarP999.ForeignKeyTableName = ""; schema.Columns.Add(colvarP999); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("APR_PercentilesIMCEdad",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Sexo")] [Bindable(true)] public int Sexo { get { return GetColumnValue<int>(Columns.Sexo); } set { SetColumnValue(Columns.Sexo, value); } } [XmlAttribute("Edad")] [Bindable(true)] public int Edad { get { return GetColumnValue<int>(Columns.Edad); } set { SetColumnValue(Columns.Edad, value); } } [XmlAttribute("L")] [Bindable(true)] public decimal L { get { return GetColumnValue<decimal>(Columns.L); } set { SetColumnValue(Columns.L, value); } } [XmlAttribute("M")] [Bindable(true)] public decimal M { get { return GetColumnValue<decimal>(Columns.M); } set { SetColumnValue(Columns.M, value); } } [XmlAttribute("S")] [Bindable(true)] public decimal S { get { return GetColumnValue<decimal>(Columns.S); } set { SetColumnValue(Columns.S, value); } } [XmlAttribute("P01")] [Bindable(true)] public decimal P01 { get { return GetColumnValue<decimal>(Columns.P01); } set { SetColumnValue(Columns.P01, value); } } [XmlAttribute("P1")] [Bindable(true)] public decimal P1 { get { return GetColumnValue<decimal>(Columns.P1); } set { SetColumnValue(Columns.P1, value); } } [XmlAttribute("P3")] [Bindable(true)] public decimal P3 { get { return GetColumnValue<decimal>(Columns.P3); } set { SetColumnValue(Columns.P3, value); } } [XmlAttribute("P5")] [Bindable(true)] public decimal P5 { get { return GetColumnValue<decimal>(Columns.P5); } set { SetColumnValue(Columns.P5, value); } } [XmlAttribute("P10")] [Bindable(true)] public decimal P10 { get { return GetColumnValue<decimal>(Columns.P10); } set { SetColumnValue(Columns.P10, value); } } [XmlAttribute("P15")] [Bindable(true)] public decimal P15 { get { return GetColumnValue<decimal>(Columns.P15); } set { SetColumnValue(Columns.P15, value); } } [XmlAttribute("P25")] [Bindable(true)] public decimal P25 { get { return GetColumnValue<decimal>(Columns.P25); } set { SetColumnValue(Columns.P25, value); } } [XmlAttribute("P50")] [Bindable(true)] public decimal P50 { get { return GetColumnValue<decimal>(Columns.P50); } set { SetColumnValue(Columns.P50, value); } } [XmlAttribute("P75")] [Bindable(true)] public decimal P75 { get { return GetColumnValue<decimal>(Columns.P75); } set { SetColumnValue(Columns.P75, value); } } [XmlAttribute("P85")] [Bindable(true)] public decimal P85 { get { return GetColumnValue<decimal>(Columns.P85); } set { SetColumnValue(Columns.P85, value); } } [XmlAttribute("P90")] [Bindable(true)] public decimal P90 { get { return GetColumnValue<decimal>(Columns.P90); } set { SetColumnValue(Columns.P90, value); } } [XmlAttribute("P95")] [Bindable(true)] public decimal P95 { get { return GetColumnValue<decimal>(Columns.P95); } set { SetColumnValue(Columns.P95, value); } } [XmlAttribute("P97")] [Bindable(true)] public decimal P97 { get { return GetColumnValue<decimal>(Columns.P97); } set { SetColumnValue(Columns.P97, value); } } [XmlAttribute("P99")] [Bindable(true)] public decimal P99 { get { return GetColumnValue<decimal>(Columns.P99); } set { SetColumnValue(Columns.P99, value); } } [XmlAttribute("P999")] [Bindable(true)] public decimal P999 { get { return GetColumnValue<decimal>(Columns.P999); } set { SetColumnValue(Columns.P999, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varSexo,int varEdad,decimal varL,decimal varM,decimal varS,decimal varP01,decimal varP1,decimal varP3,decimal varP5,decimal varP10,decimal varP15,decimal varP25,decimal varP50,decimal varP75,decimal varP85,decimal varP90,decimal varP95,decimal varP97,decimal varP99,decimal varP999) { AprPercentilesIMCEdad item = new AprPercentilesIMCEdad(); item.Sexo = varSexo; item.Edad = varEdad; item.L = varL; item.M = varM; item.S = varS; item.P01 = varP01; item.P1 = varP1; item.P3 = varP3; item.P5 = varP5; item.P10 = varP10; item.P15 = varP15; item.P25 = varP25; item.P50 = varP50; item.P75 = varP75; item.P85 = varP85; item.P90 = varP90; item.P95 = varP95; item.P97 = varP97; item.P99 = varP99; item.P999 = varP999; 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 varId,int varSexo,int varEdad,decimal varL,decimal varM,decimal varS,decimal varP01,decimal varP1,decimal varP3,decimal varP5,decimal varP10,decimal varP15,decimal varP25,decimal varP50,decimal varP75,decimal varP85,decimal varP90,decimal varP95,decimal varP97,decimal varP99,decimal varP999) { AprPercentilesIMCEdad item = new AprPercentilesIMCEdad(); item.Id = varId; item.Sexo = varSexo; item.Edad = varEdad; item.L = varL; item.M = varM; item.S = varS; item.P01 = varP01; item.P1 = varP1; item.P3 = varP3; item.P5 = varP5; item.P10 = varP10; item.P15 = varP15; item.P25 = varP25; item.P50 = varP50; item.P75 = varP75; item.P85 = varP85; item.P90 = varP90; item.P95 = varP95; item.P97 = varP97; item.P99 = varP99; item.P999 = varP999; 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 IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn SexoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn EdadColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn LColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn MColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn SColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn P01Column { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn P1Column { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn P3Column { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn P5Column { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn P10Column { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn P15Column { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn P25Column { get { return Schema.Columns[12]; } } public static TableSchema.TableColumn P50Column { get { return Schema.Columns[13]; } } public static TableSchema.TableColumn P75Column { get { return Schema.Columns[14]; } } public static TableSchema.TableColumn P85Column { get { return Schema.Columns[15]; } } public static TableSchema.TableColumn P90Column { get { return Schema.Columns[16]; } } public static TableSchema.TableColumn P95Column { get { return Schema.Columns[17]; } } public static TableSchema.TableColumn P97Column { get { return Schema.Columns[18]; } } public static TableSchema.TableColumn P99Column { get { return Schema.Columns[19]; } } public static TableSchema.TableColumn P999Column { get { return Schema.Columns[20]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string Sexo = @"Sexo"; public static string Edad = @"Edad"; public static string L = @"L"; public static string M = @"M"; public static string S = @"S"; public static string P01 = @"P01"; public static string P1 = @"P1"; public static string P3 = @"P3"; public static string P5 = @"P5"; public static string P10 = @"P10"; public static string P15 = @"P15"; public static string P25 = @"P25"; public static string P50 = @"P50"; public static string P75 = @"P75"; public static string P85 = @"P85"; public static string P90 = @"P90"; public static string P95 = @"P95"; public static string P97 = @"P97"; public static string P99 = @"P99"; public static string P999 = @"P999"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using Internal.Runtime.CompilerServices; namespace System.Globalization { public partial class CompareInfo { [NonSerialized] private Interop.Globalization.SafeSortHandle _sortHandle; [NonSerialized] private bool _isAsciiEqualityOrdinal; private void InitSort(CultureInfo culture) { _sortName = culture.SortName; if (GlobalizationMode.Invariant) { _isAsciiEqualityOrdinal = true; } else { Interop.Globalization.ResultCode resultCode = Interop.Globalization.GetSortHandle(GetNullTerminatedUtf8String(_sortName), out _sortHandle); if (resultCode != Interop.Globalization.ResultCode.Success) { _sortHandle.Dispose(); if (resultCode == Interop.Globalization.ResultCode.OutOfMemory) throw new OutOfMemoryException(); throw new ExternalException(SR.Arg_ExternalException); } _isAsciiEqualityOrdinal = (_sortName == "en-US" || _sortName == ""); } } internal static unsafe int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); if (value.Length == 0) { return startIndex; } if (count < value.Length) { return -1; } if (ignoreCase) { fixed (char* pSource = source) { int index = Interop.Globalization.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false); return index != -1 ? startIndex + index : -1; } } int endIndex = startIndex + (count - value.Length); for (int i = startIndex; i <= endIndex; i++) { int valueIndex, sourceIndex; for (valueIndex = 0, sourceIndex = i; valueIndex < value.Length && source[sourceIndex] == value[valueIndex]; valueIndex++, sourceIndex++) ; if (valueIndex == value.Length) { return i; } } return -1; } internal static unsafe int IndexOfOrdinalCore(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source.Length != 0); Debug.Assert(value.Length != 0); if (source.Length < value.Length) { return -1; } if (ignoreCase) { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pValue = &MemoryMarshal.GetReference(value)) { return Interop.Globalization.IndexOfOrdinalIgnoreCase(pValue, value.Length, pSource, source.Length, findLast: !fromBeginning); } } int startIndex, endIndex, jump; if (fromBeginning) { // Left to right, from zero to last possible index in the source string. // Incrementing by one after each iteration. Stop condition is last possible index plus 1. startIndex = 0; endIndex = source.Length - value.Length + 1; jump = 1; } else { // Right to left, from first possible index in the source string to zero. // Decrementing by one after each iteration. Stop condition is last possible index minus 1. startIndex = source.Length - value.Length; endIndex = -1; jump = -1; } for (int i = startIndex; i != endIndex; i += jump) { int valueIndex, sourceIndex; for (valueIndex = 0, sourceIndex = i; valueIndex < value.Length && source[sourceIndex] == value[valueIndex]; valueIndex++, sourceIndex++) ; if (valueIndex == value.Length) { return i; } } return -1; } internal static unsafe int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); if (value.Length == 0) { return startIndex; } if (count < value.Length) { return -1; } // startIndex is the index into source where we start search backwards from. // leftStartIndex is the index into source of the start of the string that is // count characters away from startIndex. int leftStartIndex = startIndex - count + 1; if (ignoreCase) { fixed (char* pSource = source) { int lastIndex = Interop.Globalization.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true); return lastIndex != -1 ? leftStartIndex + lastIndex : -1; } } for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--) { int valueIndex, sourceIndex; for (valueIndex = 0, sourceIndex = i; valueIndex < value.Length && source[sourceIndex] == value[valueIndex]; valueIndex++, sourceIndex++) ; if (valueIndex == value.Length) { return i; } } return -1; } private static unsafe int CompareStringOrdinalIgnoreCase(ref char string1, int count1, ref char string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); fixed (char* char1 = &string1) fixed (char* char2 = &string2) { return Interop.Globalization.CompareStringOrdinalIgnoreCase(char1, count1, char2, count2); } } // TODO https://github.com/dotnet/coreclr/issues/13827: // This method shouldn't be necessary, as we should be able to just use the overload // that takes two spans. But due to this issue, that's adding significant overhead. private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(string2 != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &string2.GetRawStringData()) { return Interop.Globalization.CompareString(_sortHandle, pString1, string1.Length, pString2, string2.Length, options); } } private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &MemoryMarshal.GetReference(string2)) { return Interop.Globalization.CompareString(_sortHandle, pString1, string1.Length, pString2, string2.Length, options); } } internal unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); Debug.Assert((options & CompareOptions.Ordinal) == 0); #if CORECLR if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort()) { int index = IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options)); if (index != -1) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return index; } #endif fixed (char* pSource = source) fixed (char* pTarget = target) { int index = Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource + startIndex, count, options, matchLengthPtr); return index != -1 ? index + startIndex : -1; } } // For now, this method is only called from Span APIs with either options == CompareOptions.None or CompareOptions.IgnoreCase internal unsafe int IndexOfCore(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source.Length != 0); Debug.Assert(target.Length != 0); if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) return IndexOfOrdinalIgnoreCaseHelper(source, target, options, matchLengthPtr, fromBeginning); else return IndexOfOrdinalHelper(source, target, options, matchLengthPtr, fromBeginning); } else { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pTarget = &MemoryMarshal.GetReference(target)) { if (fromBeginning) return Interop.Globalization.IndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options, matchLengthPtr); else return Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource, source.Length, options); } } } /// <summary> /// Duplicate of IndexOfOrdinalHelper that also handles ignore case. Can't converge both methods /// as the JIT wouldn't be able to optimize the ignoreCase path away. /// </summary> /// <returns></returns> private unsafe int IndexOfOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!target.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(target)) { char* a = ap; char* b = bp; if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) { char targetChar = *(b + j); if (targetChar >= 0x80 || s_highCharTable[targetChar]) goto InteropCall; } int startIndex, endIndex, jump; if (fromBeginning) { // Left to right, from zero to last possible index in the source string. // Incrementing by one after each iteration. Stop condition is last possible index plus 1. startIndex = 0; endIndex = source.Length - target.Length + 1; jump = 1; } else { // Right to left, from first possible index in the source string to zero. // Decrementing by one after each iteration. Stop condition is last possible index minus 1. startIndex = source.Length - target.Length; endIndex = -1; jump = -1; } for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); if (valueChar == targetChar && valueChar < 0x80 && !s_highCharTable[valueChar]) { continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(valueChar - 'a') <= ('z' - 'a')) valueChar = (char)(valueChar - 0x20); if ((uint)(targetChar - 'a') <= ('z' - 'a')) targetChar = (char)(targetChar - 0x20); if (valueChar >= 0x80 || s_highCharTable[valueChar]) goto InteropCall; else if (valueChar != targetChar) break; } if (targetIndex == target.Length) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; return i; } } return -1; InteropCall: if (fromBeginning) return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); else return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } private unsafe int IndexOfOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> target, CompareOptions options, int* matchLengthPtr, bool fromBeginning) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!target.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(target)) { char* a = ap; char* b = bp; if (target.Length > source.Length) goto InteropCall; for (int j = 0; j < target.Length; j++) { char targetChar = *(b + j); if (targetChar >= 0x80 || s_highCharTable[targetChar]) goto InteropCall; } int startIndex, endIndex, jump; if (fromBeginning) { // Left to right, from zero to last possible index in the source string. // Incrementing by one after each iteration. Stop condition is last possible index plus 1. startIndex = 0; endIndex = source.Length - target.Length + 1; jump = 1; } else { // Right to left, from first possible index in the source string to zero. // Decrementing by one after each iteration. Stop condition is last possible index minus 1. startIndex = source.Length - target.Length; endIndex = -1; jump = -1; } for (int i = startIndex; i != endIndex; i += jump) { int targetIndex = 0; int sourceIndex = i; for (; targetIndex < target.Length; targetIndex++, sourceIndex++) { char valueChar = *(a + sourceIndex); char targetChar = *(b + targetIndex); if (valueChar >= 0x80 || s_highCharTable[valueChar]) goto InteropCall; else if (valueChar != targetChar) break; } if (targetIndex == target.Length) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; return i; } } return -1; InteropCall: if (fromBeginning) return Interop.Globalization.IndexOf(_sortHandle, b, target.Length, a, source.Length, options, matchLengthPtr); else return Interop.Globalization.LastIndexOf(_sortHandle, b, target.Length, a, source.Length, options); } } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { return startIndex; } if (options == CompareOptions.Ordinal) { return LastIndexOfOrdinalCore(source, target, startIndex, count, ignoreCase: false); } #if CORECLR if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && target.IsFastSort()) { return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options)); } #endif // startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source // of the start of the string that is count characters away from startIndex. int leftStartIndex = (startIndex - count + 1); fixed (char* pSource = source) fixed (char* pTarget = target) { int lastIndex = Interop.Globalization.LastIndexOf(_sortHandle, pTarget, target.Length, pSource + (startIndex - count + 1), count, options); return lastIndex != -1 ? lastIndex + leftStartIndex : -1; } } private bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); #if CORECLR if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && prefix.IsFastSort()) { return IsPrefix(source, prefix, GetOrdinalCompareOptions(options)); } #endif return Interop.Globalization.StartsWith(_sortHandle, prefix, prefix.Length, source, source.Length, options); } private unsafe bool StartsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!prefix.IsEmpty); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if (source.Length < prefix.Length) { return false; } if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) { return StartsWithOrdinalIgnoreCaseHelper(source, prefix, options); } else { return StartsWithOrdinalHelper(source, prefix, options); } } else { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pPrefix = &MemoryMarshal.GetReference(prefix)) { return Interop.Globalization.StartsWith(_sortHandle, pPrefix, prefix.Length, pSource, source.Length, options); } } } private unsafe bool StartsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!prefix.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); Debug.Assert(source.Length >= prefix.Length); int length = prefix.Length; fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(prefix)) { char* a = ap; char* b = bp; while (length != 0 && (*a < 0x80) && (*b < 0x80) && (!s_highCharTable[*a]) && (!s_highCharTable[*b])) { int charA = *a; int charB = *b; if (charA == charB) { a++; b++; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; if (charA != charB) return false; // Next char a++; b++; length--; } if (length == 0) return true; return Interop.Globalization.StartsWith(_sortHandle, b, length, a, length, options); } } private unsafe bool StartsWithOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!prefix.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); Debug.Assert(source.Length >= prefix.Length); int length = prefix.Length; fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(prefix)) { char* a = ap; char* b = bp; while (length != 0 && (*a < 0x80) && (*b < 0x80) && (!s_highCharTable[*a]) && (!s_highCharTable[*b])) { int charA = *a; int charB = *b; if (charA != charB) return false; // Next char a++; b++; length--; } if (length == 0) return true; return Interop.Globalization.StartsWith(_sortHandle, b, length, a, length, options); } } private bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); #if CORECLR if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsFastSort() && suffix.IsFastSort()) { return IsSuffix(source, suffix, GetOrdinalCompareOptions(options)); } #endif return Interop.Globalization.EndsWith(_sortHandle, suffix, suffix.Length, source, source.Length, options); } private unsafe bool EndsWith(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!suffix.IsEmpty); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options)) { if (source.Length < suffix.Length) { return false; } if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) { return EndsWithOrdinalIgnoreCaseHelper(source, suffix, options); } else { return EndsWithOrdinalHelper(source, suffix, options); } } else { fixed (char* pSource = &MemoryMarshal.GetReference(source)) fixed (char* pSuffix = &MemoryMarshal.GetReference(suffix)) { return Interop.Globalization.EndsWith(_sortHandle, pSuffix, suffix.Length, pSource, source.Length, options); } } } private unsafe bool EndsWithOrdinalIgnoreCaseHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!suffix.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); Debug.Assert(source.Length >= suffix.Length); int length = suffix.Length; fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(suffix)) { char* a = ap + source.Length - 1; char* b = bp + suffix.Length - 1; while (length != 0 && (*a < 0x80) && (*b < 0x80) && (!s_highCharTable[*a]) && (!s_highCharTable[*b])) { int charA = *a; int charB = *b; if (charA == charB) { a--; b--; length--; continue; } // uppercase both chars - notice that we need just one compare per char if ((uint)(charA - 'a') <= (uint)('z' - 'a')) charA -= 0x20; if ((uint)(charB - 'a') <= (uint)('z' - 'a')) charB -= 0x20; if (charA != charB) return false; // Next char a--; b--; length--; } if (length == 0) return true; return Interop.Globalization.EndsWith(_sortHandle, b - length + 1, length, a - length + 1, length, options); } } private unsafe bool EndsWithOrdinalHelper(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(!source.IsEmpty); Debug.Assert(!suffix.IsEmpty); Debug.Assert(_isAsciiEqualityOrdinal); Debug.Assert(source.Length >= suffix.Length); int length = suffix.Length; fixed (char* ap = &MemoryMarshal.GetReference(source)) fixed (char* bp = &MemoryMarshal.GetReference(suffix)) { char* a = ap + source.Length - 1; char* b = bp + suffix.Length - 1; while (length != 0 && (*a < 0x80) && (*b < 0x80) && (!s_highCharTable[*a]) && (!s_highCharTable[*b])) { int charA = *a; int charB = *b; if (charA != charB) return false; // Next char a--; b--; length--; } if (length == 0) return true; return Interop.Globalization.EndsWith(_sortHandle, b - length + 1, length, a - length + 1, length, options); } } private unsafe SortKey CreateSortKey(string source, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); if (source==null) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } byte [] keyData; if (source.Length == 0) { keyData = Array.Empty<Byte>(); } else { fixed (char* pSource = source) { int sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, null, 0, options); keyData = new byte[sortKeyLength]; fixed (byte* pSortKey = keyData) { if (Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, pSortKey, sortKeyLength, options) != sortKeyLength) { throw new ArgumentException(SR.Arg_ExternalException); } } } } return new SortKey(Name, source, options, keyData); } private static unsafe bool IsSortable(char *text, int length) { Debug.Assert(!GlobalizationMode.Invariant); int index = 0; UnicodeCategory uc; while (index < length) { if (char.IsHighSurrogate(text[index])) { if (index == length - 1 || !char.IsLowSurrogate(text[index+1])) return false; // unpaired surrogate uc = CharUnicodeInfo.GetUnicodeCategory(char.ConvertToUtf32(text[index], text[index+1])); if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned) return false; index += 2; continue; } if (char.IsLowSurrogate(text[index])) { return false; // unpaired surrogate } uc = CharUnicodeInfo.GetUnicodeCategory(text[index]); if (uc == UnicodeCategory.PrivateUse || uc == UnicodeCategory.OtherNotAssigned) { return false; } index++; } return true; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- internal unsafe int GetHashCodeOfStringCore(ReadOnlySpan<char> source, CompareOptions options) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } fixed (char* pSource = source) { int sortKeyLength = Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, null, 0, options); byte[] borrowedArr = null; Span<byte> span = sortKeyLength <= 512 ? stackalloc byte[512] : (borrowedArr = ArrayPool<byte>.Shared.Rent(sortKeyLength)); fixed (byte* pSortKey = &MemoryMarshal.GetReference(span)) { if (Interop.Globalization.GetSortKey(_sortHandle, pSource, source.Length, pSortKey, sortKeyLength, options) != sortKeyLength) { throw new ArgumentException(SR.Arg_ExternalException); } } int hash = Marvin.ComputeHash32(span.Slice(0, sortKeyLength), Marvin.DefaultSeed); // Return the borrowed array if necessary. if (borrowedArr != null) { ArrayPool<byte>.Shared.Return(borrowedArr); } return hash; } } private static CompareOptions GetOrdinalCompareOptions(CompareOptions options) { if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase) { return CompareOptions.OrdinalIgnoreCase; } else { return CompareOptions.Ordinal; } } private static bool CanUseAsciiOrdinalForOptions(CompareOptions options) { // Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. '). return (options & CompareOptions.IgnoreSymbols) == 0; } private static byte[] GetNullTerminatedUtf8String(string s) { int byteLen = System.Text.Encoding.UTF8.GetByteCount(s); // Allocate an extra byte (which defaults to 0) as the null terminator. byte[] buffer = new byte[byteLen + 1]; int bytesWritten = System.Text.Encoding.UTF8.GetBytes(s, 0, s.Length, buffer, 0); Debug.Assert(bytesWritten == byteLen); return buffer; } private SortVersion GetSortVersion() { Debug.Assert(!GlobalizationMode.Invariant); int sortVersion = Interop.Globalization.GetSortVersion(_sortHandle); return new SortVersion(sortVersion, LCID, new Guid(sortVersion, 0, 0, 0, 0, 0, 0, (byte) (LCID >> 24), (byte) ((LCID & 0x00FF0000) >> 16), (byte) ((LCID & 0x0000FF00) >> 8), (byte) (LCID & 0xFF))); } // See https://github.com/dotnet/coreclr/blob/master/src/utilcode/util_nodependencies.cpp#L970 private static readonly bool[] s_highCharTable = new bool[0x80] { true, /* 0x0, 0x0 */ true, /* 0x1, .*/ true, /* 0x2, .*/ true, /* 0x3, .*/ true, /* 0x4, .*/ true, /* 0x5, .*/ true, /* 0x6, .*/ true, /* 0x7, .*/ true, /* 0x8, .*/ false, /* 0x9, */ true, /* 0xA, */ false, /* 0xB, .*/ false, /* 0xC, .*/ true, /* 0xD, */ true, /* 0xE, .*/ true, /* 0xF, .*/ true, /* 0x10, .*/ true, /* 0x11, .*/ true, /* 0x12, .*/ true, /* 0x13, .*/ true, /* 0x14, .*/ true, /* 0x15, .*/ true, /* 0x16, .*/ true, /* 0x17, .*/ true, /* 0x18, .*/ true, /* 0x19, .*/ true, /* 0x1A, */ true, /* 0x1B, .*/ true, /* 0x1C, .*/ true, /* 0x1D, .*/ true, /* 0x1E, .*/ true, /* 0x1F, .*/ false, /*0x20, */ false, /*0x21, !*/ false, /*0x22, "*/ false, /*0x23, #*/ false, /*0x24, $*/ false, /*0x25, %*/ false, /*0x26, &*/ true, /*0x27, '*/ false, /*0x28, (*/ false, /*0x29, )*/ false, /*0x2A **/ false, /*0x2B, +*/ false, /*0x2C, ,*/ true, /*0x2D, -*/ false, /*0x2E, .*/ false, /*0x2F, /*/ false, /*0x30, 0*/ false, /*0x31, 1*/ false, /*0x32, 2*/ false, /*0x33, 3*/ false, /*0x34, 4*/ false, /*0x35, 5*/ false, /*0x36, 6*/ false, /*0x37, 7*/ false, /*0x38, 8*/ false, /*0x39, 9*/ false, /*0x3A, :*/ false, /*0x3B, ;*/ false, /*0x3C, <*/ false, /*0x3D, =*/ false, /*0x3E, >*/ false, /*0x3F, ?*/ false, /*0x40, @*/ false, /*0x41, A*/ false, /*0x42, B*/ false, /*0x43, C*/ false, /*0x44, D*/ false, /*0x45, E*/ false, /*0x46, F*/ false, /*0x47, G*/ false, /*0x48, H*/ false, /*0x49, I*/ false, /*0x4A, J*/ false, /*0x4B, K*/ false, /*0x4C, L*/ false, /*0x4D, M*/ false, /*0x4E, N*/ false, /*0x4F, O*/ false, /*0x50, P*/ false, /*0x51, Q*/ false, /*0x52, R*/ false, /*0x53, S*/ false, /*0x54, T*/ false, /*0x55, U*/ false, /*0x56, V*/ false, /*0x57, W*/ false, /*0x58, X*/ false, /*0x59, Y*/ false, /*0x5A, Z*/ false, /*0x5B, [*/ false, /*0x5C, \*/ false, /*0x5D, ]*/ false, /*0x5E, ^*/ false, /*0x5F, _*/ false, /*0x60, `*/ false, /*0x61, a*/ false, /*0x62, b*/ false, /*0x63, c*/ false, /*0x64, d*/ false, /*0x65, e*/ false, /*0x66, f*/ false, /*0x67, g*/ false, /*0x68, h*/ false, /*0x69, i*/ false, /*0x6A, j*/ false, /*0x6B, k*/ false, /*0x6C, l*/ false, /*0x6D, m*/ false, /*0x6E, n*/ false, /*0x6F, o*/ false, /*0x70, p*/ false, /*0x71, q*/ false, /*0x72, r*/ false, /*0x73, s*/ false, /*0x74, t*/ false, /*0x75, u*/ false, /*0x76, v*/ false, /*0x77, w*/ false, /*0x78, x*/ false, /*0x79, y*/ false, /*0x7A, z*/ false, /*0x7B, {*/ false, /*0x7C, |*/ false, /*0x7D, }*/ false, /*0x7E, ~*/ true, /*0x7F, */ }; } }
// 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; namespace System.Numerics.Tests { public class logTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunLogTests() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; BigInteger bi; // Log Method - Log(1,+Infinity) Assert.Equal(0, BigInteger.Log(1, Double.PositiveInfinity)); // Log Method - Log(1,0) VerifyLogString("0 1 bLog"); // Log Method - Log(0, >1) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 10); VerifyLogString(Print(tempByteArray1) + "0 bLog"); } // Log Method - Log(0, 0>x>1) for (int i = 0; i < s_samples; i++) { Assert.Equal(Double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble())); } // Log Method - base = 0 for (int i = 0; i < s_samples; i++) { bi = 1; while (bi == 1) { bi = new BigInteger(GetRandomPosByteArray(s_random, 8)); } Assert.True((Double.IsNaN(BigInteger.Log(bi, 0)))); } // Log Method - base = 1 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); VerifyLogString("1 " + Print(tempByteArray1) + "bLog"); } // Log Method - base = NaN for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.NaN))); } // Log Method - base = +Infinity for (int i = 0; i < s_samples; i++) { Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.PositiveInfinity))); } // Log Method - Log(0,1) VerifyLogString("1 0 bLog"); // Log Method - base < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 10); tempByteArray2 = GetRandomNegByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble()))); } // Log Method - value < 0 for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomNegByteArray(s_random, 10); tempByteArray2 = GetRandomPosByteArray(s_random, 1); VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog"); } // Log Method - Small BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10)); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - Large BigInteger and 0<base<0.5 for (int i = 0; i < s_samples; i++) { BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100))); Double newbase = Math.Min(s_random.NextDouble(), 0.5); Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase))); } // Log Method - two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 3); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - one small and one large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 1); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - two large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100)); VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog"); } // Log Method - Very Large BigInteger 1 << 128 << Int.MaxValue and 2 LargeValueLogTests(128, 1); } [Fact] [OuterLoop] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void RunLargeValueLogTests() { LargeValueLogTests(0, 4, 64, 3); } /// <summary> /// Test Log Method on Very Large BigInteger more than (1 &lt;&lt; Int.MaxValue) by base 2 /// Tested BigInteger are: pow(2, startShift + smallLoopShift * [1..smallLoopLimit] + Int32.MaxValue * [1..bigLoopLimit]) /// Note: /// ToString() can not operate such large values /// VerifyLogString() can not operate such large values, /// Math.Log() can not operate such large values /// </summary> private static void LargeValueLogTests(int startShift, int bigShiftLoopLimit, int smallShift = 0, int smallShiftLoopLimit = 1) { BigInteger init = BigInteger.One << startShift; double logbase = 2D; for (int i = 0; i < smallShiftLoopLimit; i++) { BigInteger temp = init << ((i + 1) * smallShift); for (int j = 0; j<bigShiftLoopLimit; j++) { temp = temp << (int.MaxValue / 10); double expected = (double)startShift + smallShift * (double)(i + 1) + (int.MaxValue / 10) * (double)(j + 1); Assert.True(ApproxEqual(BigInteger.Log(temp, logbase), expected)); } } } private static void VerifyLogString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(0, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetRandomByteArray(random, size); } private static Byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; i++) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static Byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } private static bool ApproxEqual(double value1, double value2) { //Special case values; if (Double.IsNaN(value1)) { return Double.IsNaN(value2); } if (Double.IsNegativeInfinity(value1)) { return Double.IsNegativeInfinity(value2); } if (Double.IsPositiveInfinity(value1)) { return Double.IsPositiveInfinity(value2); } if (value2 == 0) { return (value1 == 0); } double result = Math.Abs((value1 / value2) - 1); return (result <= Double.Parse("1e-15")); } } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using MLifter.Components.Properties; using System.Net; namespace MLifter.Components { public partial class MLifterCheckBox : UserControl { #region properties private int number; /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> /// <remarks>Documented by Dev05, 2009-04-14</remarks> [Category("Appearance"), Description("The number of the Button."), DefaultValue(1)] public int Number { get { return number; } set { number = value; checkButtonNumber.Text = "&" + value + "."; } } private Image imageChecked; [DefaultValue(typeof(Image), null), Category("Appearance-CheckedImage"), Description("The Image for the checked control")] public Image ImageChecked { get { return imageChecked; } set { imageChecked = value; checkButtonNumber.ImageChecked = value; } } private Image backGroundCheckBox; [DefaultValue(typeof(Image), null), Category("Appearance-CheckedImage"), Description("The Image for the checked control")] public Image BackGroundCheckBox { get { return backGroundCheckBox; } set { backGroundCheckBox = value; checkButtonNumber.BackGroundCheckBox = value; } } /// <summary> /// The text associated with this control. /// </summary> /// <remarks>Documented by Dev05, 2009-04-14</remarks> [Category("Appearance"), Description("The text associated with this control."), DefaultValue("MLifterCheckBox")] public override string Text { get { return WebUtility.HtmlEncode(labelText.Text); } set { labelText.Text = WebUtility.HtmlDecode(value); } } /// <summary> /// Gets or sets a value indicating whether this <see cref="MLifterCheckBox"/> is checked. /// </summary> /// <value><c>true</c> if checked; otherwise, <c>false</c>.</value> /// <remarks>Documented by Dev05, 2009-04-14</remarks> [Category("Appearance"), Description("Gets or sets a value indicating whether this MLifterCheckBox is checked."), DefaultValue(false)] public bool Checked { get { return checkButtonNumber.Checked; } set { checkButtonNumber.Checked = value; } } #endregion properties #region constructor /// <summary> /// Initializes a new instance of the <see cref="MLifterCheckBox"/> class. /// </summary> /// <remarks>Documented by Dev05, 2009-04-14</remarks> public MLifterCheckBox() { DoubleBuffered = true; SetStyle(ControlStyles.Selectable, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); InitializeComponent(); } #endregion constructor #region checked_CheckButton /// <summary> /// Occurs when checked changed. /// </summary> /// <remarks>Documented by Dev05, 2009-04-14</remarks> public event EventHandler CheckedChanged; /// <summary> /// Raises the <see cref="E:CheckedChange"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-04-14</remarks> protected virtual void OnCheckedChange(EventArgs e) { if (CheckedChanged != null) CheckedChanged(this, e); } /// <summary> /// Handles the CheckedChanged event of the checkButtonNumber control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-04-14</remarks> private void checkButtonNumber_CheckedChanged(object sender, EventArgs e) { OnCheckedChange(e); } #endregion checked_CheckButton #region clickEvents /// <summary> /// Handles the Click event of the labelText control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-04-15</remarks> private void labelText_Click(object sender, EventArgs e) { Checked = !Checked; } /// <summary> /// Handles the Click event of the MLifterCheckBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-04-15</remarks> private void MLifterCheckBox_Click(object sender, EventArgs e) { Checked = !Checked; } #endregion clickEvents #region keyEvents /// <summary> /// Handles the KeyUp event of the checkButtonNumber control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2009-04-16</remarks> private void checkButtonNumber_KeyUp(object sender, KeyEventArgs e) { OnKeyUp(e); } /// <summary> /// Handles the KeyDown event of the checkButtonNumber control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.KeyEventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev02, 2009-04-16</remarks> private void checkButtonNumber_KeyDown(object sender, KeyEventArgs e) { OnKeyDown(e); } #endregion keyEvents #region override /// <summary> /// Retrieves the size of a rectangular area into which a control can be fitted. /// </summary> /// <param name="proposedSize">The custom-sized area for a control.</param> /// <returns> /// An ordered pair of type <see cref="T:System.Drawing.Size"/> representing the width and height of a rectangle. /// </returns> /// <remarks>Documented by Dev05, 2009-04-15</remarks> public override Size GetPreferredSize(Size proposedSize) { Size labelSize = labelText.GetPreferredSize(proposedSize); return new Size(labelSize.Width + Width - labelText.Width, labelSize.Height + Height - labelText.Height); } #endregion override #region alginmentChanged /// <summary> /// Handles the RightToLeftChanged event of the MLifterCheckBox control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-05-04</remarks> private void MLifterCheckBox_RightToLeftChanged(object sender, EventArgs e) { checkButtonNumber.Anchor = AnchorStyles.None; checkButtonNumber.Left = RightToLeft == RightToLeft.Yes ? Width - checkButtonNumber.Width - 10 : 10; checkButtonNumber.Anchor = RightToLeft == RightToLeft.Yes ? AnchorStyles.Right : AnchorStyles.Left; labelText.Anchor = AnchorStyles.None; labelText.Left = RightToLeft == RightToLeft.Yes ? 10 : checkButtonNumber.Width + 20; labelText.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top; } #endregion alginmentChanged } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.Activities.DurableInstancing { using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Runtime; using System.Transactions; using System.Runtime.Diagnostics; sealed class SqlCommandAsyncResult : TransactedAsyncResult { static readonly TimeSpan MaximumOpenTimeout = TimeSpan.FromMinutes(2); static readonly RetryErrorCode[] retryErrorCodes = { new RetryErrorCode(-2, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SqlError: Timeout new RetryErrorCode(20, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - a connection failed early in the login process. to SQL Server. new RetryErrorCode(53, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A network-related or instance-specific error occurred while establishing a connection to SQL Server. new RetryErrorCode(64, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), //A transport-level error has occurred when receiving results from the server (TCP Provider, error: 0 - The specified network name is no longer available). new RetryErrorCode(121, RetryErrorOptions.RetryBeginOrEnd), // A transport-level error has occurred new RetryErrorCode(233, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed shared memory/named pipe connection drawn from the pool new RetryErrorCode(1205, RetryErrorOptions.RetryBeginOrEnd), // Deadlock new RetryErrorCode(1222, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Lock Request Timeout new RetryErrorCode(3910, RetryErrorOptions.RetryOnBegin | RetryErrorOptions.RetryWhenTransaction), // Transaction context in use by another session. new RetryErrorCode(4060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Database not online new RetryErrorCode(8645, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A timeout occurred while waiting for memory resources new RetryErrorCode(8641, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Could not perform the operation because the requested memory grant was not available new RetryErrorCode(10053, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // A transport-level error has occurred when receiving results from the server new RetryErrorCode(10054, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // Severed tcp connection drawn from the pool new RetryErrorCode(10060, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // The server was not found or was not accessible. new RetryErrorCode(10061, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Server not started new RetryErrorCode(40143, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request. new RetryErrorCode(40197, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server encountered error processing the request. new RetryErrorCode(40501, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - server is currently busy. new RetryErrorCode(40549, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - transaction blocking system calls new RetryErrorCode(40553, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction), // SQL Azure error - excessive memory usage new RetryErrorCode(40613, RetryErrorOptions.RetryBeginOrEnd | RetryErrorOptions.RetryWhenTransaction) // SQL Azure error - database on server is not available. }; static AsyncCompletion onExecuteReaderCallback = new AsyncCompletion(OnExecuteReader); static AsyncCompletion onRetryCommandCallback = new AsyncCompletion(OnRetryCommand); string connectionString; DependentTransaction dependentTransaction; int maximumRetries; int retryCount; EventTraceActivity eventTraceActivity; SqlCommand sqlCommand; SqlDataReader sqlDataReader; TimeoutHelper timeoutHelper; public SqlCommandAsyncResult(SqlCommand sqlCommand, string connectionString, EventTraceActivity eventTraceActivity, DependentTransaction dependentTransaction, TimeSpan timeout, int retryCount, int maximumRetries, AsyncCallback callback, object state) : base(callback, state) { long openTimeout = Math.Min(timeout.Ticks, SqlCommandAsyncResult.MaximumOpenTimeout.Ticks); this.sqlCommand = sqlCommand; this.connectionString = connectionString; this.eventTraceActivity = eventTraceActivity; this.dependentTransaction = dependentTransaction; this.timeoutHelper = new TimeoutHelper(TimeSpan.FromTicks(openTimeout)); this.retryCount = retryCount; this.maximumRetries = maximumRetries; } [Flags] enum RetryErrorOptions { RetryOnBegin = 1, RetryOnEnd = 2, RetryWhenTransaction = 4, RetryBeginOrEnd = RetryOnBegin | RetryOnEnd } public static SqlDataReader End(IAsyncResult result) { SqlCommandAsyncResult SqlCommandAsyncResult = AsyncResult.End<SqlCommandAsyncResult>(result); return SqlCommandAsyncResult.sqlDataReader; } public void StartCommand() { StartCommandInternal(true); } static bool OnExecuteReader(IAsyncResult result) { SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult)(result.AsyncState); return thisPtr.CompleteExecuteReader(result); } static bool OnRetryCommand(IAsyncResult childPtr) { SqlCommandAsyncResult parentPtr = (SqlCommandAsyncResult)(childPtr.AsyncState); parentPtr.sqlDataReader = SqlCommandAsyncResult.End(childPtr); return true; } static bool ShouldRetryForSqlError(int error, RetryErrorOptions retryErrorOptions) { if (Transaction.Current != null) { retryErrorOptions |= RetryErrorOptions.RetryWhenTransaction; } return SqlCommandAsyncResult.retryErrorCodes.Any(x => x.ErrorCode == error && (x.RetryErrorOptions & retryErrorOptions) == retryErrorOptions); } static void StartCommandCallback(object state) { SqlCommandAsyncResult thisPtr = (SqlCommandAsyncResult) state; try { // this can throw on the [....] path - we need to signal the callback thisPtr.StartCommandInternal(false); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (thisPtr.sqlCommand.Connection != null) { thisPtr.sqlCommand.Connection.Close(); } thisPtr.Complete(false, e); } } bool CheckRetryCount() { return (++this.retryCount < maximumRetries); } bool CheckRetryCountAndTimer() { return (this.CheckRetryCount() && !this.HasOperationTimedOut()); } bool CompleteExecuteReader(IAsyncResult result) { bool completeSelf = true; try { this.sqlDataReader = this.sqlCommand.EndExecuteReader(result); } catch (SqlException exception) { if (TD.SqlExceptionCaughtIsEnabled()) { TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture), exception.Message); } if (this.sqlDataReader != null) { this.sqlDataReader.Close(); } if (this.sqlCommand.Connection != null) { this.sqlCommand.Connection.Close(); } // If we completed [....] then any retry is done by the original caller. if (!result.CompletedSynchronously) { if (this.CheckRetryCountAndTimer() && ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnEnd)) { if (this.EnqueueRetry()) { if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled()) { TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture)); } completeSelf = false; } } } if (completeSelf) { if (this.retryCount == maximumRetries && TD.MaximumRetriesExceededForSqlCommandIsEnabled()) { TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity); } throw; } } return completeSelf; } bool EnqueueRetry() { bool result = false; int delay = this.GetRetryDelay(); if (this.timeoutHelper.RemainingTime().TotalMilliseconds > delay) { this.sqlCommand.Dispose(); IOThreadTimer iott = new IOThreadTimer(StartCommandCallback, new SqlCommandAsyncResult(CloneSqlCommand(this.sqlCommand), this.connectionString, this.eventTraceActivity, this.dependentTransaction, this.timeoutHelper.RemainingTime(), this.retryCount, this.maximumRetries, this.PrepareAsyncCompletion(onRetryCommandCallback), this), false); iott.Set(delay); if (TD.QueuingSqlRetryIsEnabled()) { TD.QueuingSqlRetry(this.eventTraceActivity, delay.ToString(CultureInfo.InvariantCulture)); } result = true; } return result; } static SqlCommand CloneSqlCommand(SqlCommand command) { //We do not want to use SqlCommand.Clone here because we do not want to replicate the parameters SqlCommand newCommand = new SqlCommand() { CommandType = command.CommandType, CommandText = command.CommandText, }; SqlParameter[] tempParameterList = new SqlParameter[command.Parameters.Count]; for (int i = 0; i < command.Parameters.Count; i++) { tempParameterList[i] = command.Parameters[i]; } command.Parameters.Clear(); newCommand.Parameters.AddRange(tempParameterList); return newCommand; } int GetRetryDelay() { return 1000; } bool HasOperationTimedOut() { return (this.timeoutHelper.RemainingTime() <= TimeSpan.Zero); } void StartCommandInternal(bool synchronous) { if (!this.HasOperationTimedOut()) { try { IAsyncResult result; using (this.PrepareTransactionalCall(this.dependentTransaction)) { AsyncCallback wrappedCallback = this.PrepareAsyncCompletion(onExecuteReaderCallback); this.sqlCommand.Connection = StoreUtilities.CreateConnection(this.connectionString); if (!this.HasOperationTimedOut()) { result = this.sqlCommand.BeginExecuteReader(wrappedCallback, this, CommandBehavior.CloseConnection); } else { this.sqlCommand.Connection.Close(); this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString()))); return; } } if (this.CheckSyncContinue(result)) { if (this.CompleteExecuteReader(result)) { this.Complete(synchronous); } } return; } catch (SqlException exception) { if (TD.SqlExceptionCaughtIsEnabled()) { TD.SqlExceptionCaught(this.eventTraceActivity, exception.Number.ToString(null, CultureInfo.InvariantCulture), exception.Message); } if (this.sqlCommand.Connection != null) { this.sqlCommand.Connection.Close(); } if (!this.CheckRetryCount() || !ShouldRetryForSqlError(exception.Number, RetryErrorOptions.RetryOnBegin)) { throw; } if (TD.RetryingSqlCommandDueToSqlErrorIsEnabled()) { TD.RetryingSqlCommandDueToSqlError(this.eventTraceActivity, exception.Number.ToString(CultureInfo.InvariantCulture)); } } catch (InvalidOperationException) { if (!this.CheckRetryCount()) { throw; } } if (this.EnqueueRetry()) { return; } } if (this.HasOperationTimedOut()) { if (TD.TimeoutOpeningSqlConnectionIsEnabled()) { TD.TimeoutOpeningSqlConnection(this.eventTraceActivity, this.timeoutHelper.OriginalTimeout.ToString()); } } else { if (TD.MaximumRetriesExceededForSqlCommandIsEnabled()) { TD.MaximumRetriesExceededForSqlCommand(this.eventTraceActivity); } } this.Complete(synchronous, new TimeoutException(SR.TimeoutOnSqlOperation(this.timeoutHelper.OriginalTimeout.ToString()))); } class RetryErrorCode { public RetryErrorCode(int code, RetryErrorOptions retryErrorOptions) { this.ErrorCode = code; this.RetryErrorOptions = retryErrorOptions; } public int ErrorCode { get; private set; } public RetryErrorOptions RetryErrorOptions { get; private set; } } } }
/* * 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 Nini.Config; using System; using System.Collections.Generic; using System.Reflection; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors; using OpenSim.Services.Connectors.SimianGrid; using OpenMetaverse; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory { public class HGInventoryBroker : ISharedRegionModule, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static bool m_Enabled = false; private static IInventoryService m_LocalGridInventoryService; private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>(); // A cache of userIDs --> ServiceURLs, for HGBroker only protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>(); private List<Scene> m_Scenes = new List<Scene>(); public Type ReplaceableInterface { get { return null; } } public string Name { get { return "HGInventoryBroker"; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryServices", ""); if (name == Name) { IConfig inventoryConfig = source.Configs["InventoryService"]; if (inventoryConfig == null) { m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini"); return; } string localDll = inventoryConfig.GetString("LocalGridInventoryService", String.Empty); //string HGDll = inventoryConfig.GetString("HypergridInventoryService", // String.Empty); if (localDll == String.Empty) { m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService"); //return; throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's"); } Object[] args = new Object[] { source }; m_LocalGridInventoryService = ServerUtils.LoadPlugin<IInventoryService>(localDll, args); if (m_LocalGridInventoryService == null) { m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service"); return; } m_Enabled = true; m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType()); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scenes.Add(scene); scene.RegisterModuleInterface<IInventoryService>(this); scene.EventManager.OnClientClosed += OnClientClosed; } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scenes.Remove(scene); } public void RegionLoaded(Scene scene) { if (!m_Enabled) return; m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName); } #region URL Cache void OnClientClosed(UUID clientID, Scene scene) { if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache { ScenePresence sp = null; foreach (Scene s in m_Scenes) { s.TryGetScenePresence(clientID, out sp); if ((sp != null) && !sp.IsChildAgent && (s != scene)) { m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache", scene.RegionInfo.RegionName, clientID); return; } } DropInventoryServiceURL(clientID); } } /// <summary> /// Gets the user's inventory URL from its serviceURLs, if the user is foreign, /// and sticks it in the cache /// </summary> /// <param name="userID"></param> private void CacheInventoryServiceURL(UUID userID) { if (m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, userID) == null) { // The user does not have a local account; let's cache its service URL string inventoryURL = string.Empty; ScenePresence sp = null; foreach (Scene scene in m_Scenes) { scene.TryGetScenePresence(userID, out sp); if (sp != null) { AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode); if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI")) { inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString(); if (inventoryURL != null && inventoryURL != string.Empty) { inventoryURL = inventoryURL.Trim(new char[] { '/' }); m_InventoryURLs.Add(userID, inventoryURL); m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL); return; } } } } } } private void DropInventoryServiceURL(UUID userID) { lock (m_InventoryURLs) if (m_InventoryURLs.ContainsKey(userID)) { string url = m_InventoryURLs[userID]; m_InventoryURLs.Remove(userID); m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url); } } public string GetInventoryServiceURL(UUID userID) { if (m_InventoryURLs.ContainsKey(userID)) return m_InventoryURLs[userID]; CacheInventoryServiceURL(userID); if (m_InventoryURLs.ContainsKey(userID)) return m_InventoryURLs[userID]; return null; //it means that the methods should forward to local grid's inventory } #endregion #region IInventoryService public bool CreateUserInventory(UUID userID) { return m_LocalGridInventoryService.CreateUserInventory(userID); } public List<InventoryFolderBase> GetInventorySkeleton(UUID userId) { return m_LocalGridInventoryService.GetInventorySkeleton(userId); } public InventoryCollection GetUserInventory(UUID userID) { return null; } public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { } public InventoryFolderBase GetRootFolder(UUID userID) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetRootFolder(userID); IInventoryService connector = GetConnector(invURL); return connector.GetRootFolder(userID); } public InventoryFolderBase GetFolderForType(UUID userID, AssetType type) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetFolderForType(userID, type); IInventoryService connector = GetConnector(invURL); return connector.GetFolderForType(userID, type); } public InventoryCollection GetFolderContent(UUID userID, UUID folderID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetFolderContent(userID, folderID); IInventoryService connector = GetConnector(invURL); return connector.GetFolderContent(userID, folderID); } public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetFolderItems(userID, folderID); IInventoryService connector = GetConnector(invURL); return connector.GetFolderItems(userID, folderID); } public bool AddFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.AddFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.AddFolder(folder); } public bool UpdateFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.UpdateFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.UpdateFolder(folder); } public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs) { if (folderIDs == null) return false; if (folderIDs.Count == 0) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID); string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs); IInventoryService connector = GetConnector(invURL); return connector.DeleteFolders(ownerID, folderIDs); } public bool MoveFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.MoveFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.MoveFolder(folder); } public bool PurgeFolder(InventoryFolderBase folder) { if (folder == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.PurgeFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.PurgeFolder(folder); } public bool AddItem(InventoryItemBase item) { if (item == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID); string invURL = GetInventoryServiceURL(item.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.AddItem(item); IInventoryService connector = GetConnector(invURL); return connector.AddItem(item); } public bool UpdateItem(InventoryItemBase item) { if (item == null) return false; //m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID); string invURL = GetInventoryServiceURL(item.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.UpdateItem(item); IInventoryService connector = GetConnector(invURL); return connector.UpdateItem(item); } public bool MoveItems(UUID ownerID, List<InventoryItemBase> items) { if (items == null) return false; if (items.Count == 0) return true; //m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID); string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.MoveItems(ownerID, items); IInventoryService connector = GetConnector(invURL); return connector.MoveItems(ownerID, items); } public bool DeleteItems(UUID ownerID, List<UUID> itemIDs) { //m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID); if (itemIDs == null) return false; if (itemIDs.Count == 0) return true; string invURL = GetInventoryServiceURL(ownerID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs); IInventoryService connector = GetConnector(invURL); return connector.DeleteItems(ownerID, itemIDs); } public InventoryItemBase GetItem(InventoryItemBase item) { if (item == null) return null; //m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID); string invURL = GetInventoryServiceURL(item.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetItem(item); IInventoryService connector = GetConnector(invURL); return connector.GetItem(item); } public InventoryFolderBase GetFolder(InventoryFolderBase folder) { if (folder == null) return null; //m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID); string invURL = GetInventoryServiceURL(folder.Owner); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetFolder(folder); IInventoryService connector = GetConnector(invURL); return connector.GetFolder(folder); } public bool HasInventoryForUser(UUID userID) { return false; } public List<InventoryItemBase> GetActiveGestures(UUID userId) { return new List<InventoryItemBase>(); } public int GetAssetPermissions(UUID userID, UUID assetID) { //m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID); string invURL = GetInventoryServiceURL(userID); if (invURL == null) // not there, forward to local inventory connector to resolve return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID); IInventoryService connector = GetConnector(invURL); return connector.GetAssetPermissions(userID, assetID); } #endregion private IInventoryService GetConnector(string url) { IInventoryService connector = null; lock (m_connectors) { if (m_connectors.ContainsKey(url)) { connector = m_connectors[url]; } else { // Still not as flexible as I would like this to be, // but good enough for now string connectorType = new HeloServicesConnector(url).Helo(); m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType); if (connectorType == "opensim-simian") connector = new SimianInventoryServiceConnector(url); else connector = new RemoteXInventoryServicesConnector(url); m_connectors.Add(url, connector); } } return connector; } } }
// 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.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.CSharp.Interactive; using Microsoft.CodeAnalysis.Interactive; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Scripting; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Traits = Roslyn.Test.Utilities.Traits; namespace Microsoft.CodeAnalysis.UnitTests.Interactive { [Trait(Traits.Feature, Traits.Features.InteractiveHost)] public sealed class InteractiveHostTests : AbstractInteractiveHostTests { #region Utils private SynchronizedStringWriter _synchronizedOutput; private SynchronizedStringWriter _synchronizedErrorOutput; private int[] _outputReadPosition = new int[] { 0, 0 }; private readonly InteractiveHost Host; public InteractiveHostTests() { Host = new InteractiveHost(typeof(CSharpRepl), GetInteractiveHostPath(), ".", millisecondsTimeout: -1); RedirectOutput(); Host.ResetAsync(InteractiveHostOptions.Default).Wait(); var remoteService = Host.TryGetService(); Assert.NotNull(remoteService); remoteService.SetTestObjectFormattingOptions(); // assert and remove logo: var output = SplitLines(ReadOutputToEnd()); var errorOutput = ReadErrorOutputToEnd(); Assert.Equal("", errorOutput); Assert.Equal(2, output.Length); Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); // "Type "#help" for more information." Assert.Equal(FeaturesResources.TypeHelpForMoreInformation, output[1]); // remove logo: ClearOutput(); } public override void Dispose() { try { Process process = Host.TryGetProcess(); DisposeInteractiveHostProcess(Host); // the process should be terminated if (process != null && !process.HasExited) { process.WaitForExit(); } } finally { // Dispose temp files only after the InteractiveHost exits, // so that assemblies are unloaded. base.Dispose(); } } private void RedirectOutput() { _synchronizedOutput = new SynchronizedStringWriter(); _synchronizedErrorOutput = new SynchronizedStringWriter(); ClearOutput(); Host.Output = _synchronizedOutput; Host.ErrorOutput = _synchronizedErrorOutput; } private AssemblyLoadResult LoadReference(string reference) { return Host.TryGetService().LoadReferenceThrowing(reference, addReference: true); } private bool Execute(string code) { var task = Host.ExecuteAsync(code); task.Wait(); return task.Result.Success; } private bool IsShadowCopy(string path) { return Host.TryGetService().IsShadowCopy(path); } public string ReadErrorOutputToEnd() { return ReadOutputToEnd(isError: true); } public void ClearOutput() { _outputReadPosition = new int[] { 0, 0 }; _synchronizedOutput.Clear(); _synchronizedErrorOutput.Clear(); } public void RestartHost(string rspFile = null) { ClearOutput(); var initTask = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile)); initTask.Wait(); } public string ReadOutputToEnd(bool isError = false) { var writer = isError ? _synchronizedErrorOutput : _synchronizedOutput; var markPrefix = '\uFFFF'; var mark = markPrefix + Guid.NewGuid().ToString(); // writes mark to the STDOUT/STDERR pipe in the remote process: Host.TryGetService().RemoteConsoleWrite(Encoding.UTF8.GetBytes(mark), isError); while (true) { var data = writer.Prefix(mark, ref _outputReadPosition[isError ? 0 : 1]); if (data != null) { return data; } Thread.Sleep(10); } } private class CompiledFile { public string Path; public ImmutableArray<byte> Image; } private static CompiledFile CompileLibrary(TempDirectory dir, string fileName, string assemblyName, string source, params MetadataReference[] references) { var file = dir.CreateFile(fileName); var compilation = CreateCompilation( new[] { source }, assemblyName: assemblyName, references: references.Concat(new[] { MetadataReference.CreateFromAssemblyInternal(typeof(object).Assembly) }), options: fileName.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) ? TestOptions.ReleaseExe : TestOptions.ReleaseDll); var image = compilation.EmitToArray(); file.WriteAllBytes(image); return new CompiledFile { Path = file.Path, Image = image }; } #endregion [Fact] // Bugs #5018, #5344 public void OutputRedirection() { Execute(@" System.Console.WriteLine(""hello-\u4567!""); System.Console.Error.WriteLine(""error-\u7890!""); 1+1 "); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("hello-\u4567!\r\n2\r\n", output); Assert.Equal("error-\u7890!\r\n", error); } [Fact] public void OutputRedirection2() { Execute(@"System.Console.WriteLine(1);"); Execute(@"System.Console.Error.WriteLine(2);"); var output = ReadOutputToEnd(); var error = ReadErrorOutputToEnd(); Assert.Equal("1\r\n", output); Assert.Equal("2\r\n", error); RedirectOutput(); Execute(@"System.Console.WriteLine(3);"); Execute(@"System.Console.Error.WriteLine(4);"); output = ReadOutputToEnd(); error = ReadErrorOutputToEnd(); Assert.Equal("3\r\n", output); Assert.Equal("4\r\n", error); } [Fact] public void StackOverflow() { // Windows Server 2008 (OS v6.0), Vista (OS v6.0) and XP (OS v5.1) ignores SetErrorMode and shows crash dialog, which would hang the test: if (Environment.OSVersion.Version < new Version(6, 1, 0, 0)) { return; } Execute(@" int foo(int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9) { return foo(0,1,2,3,4,5,6,7,8,9) + foo(0,1,2,3,4,5,6,7,8,9); } foo(0,1,2,3,4,5,6,7,8,9) "); Assert.Equal("", ReadOutputToEnd()); // Hosting process exited with exit code -1073741571. Assert.Equal("Process is terminated due to StackOverflowException.\n" + string.Format(FeaturesResources.HostingProcessExitedWithExitCode, -1073741571), ReadErrorOutputToEnd().Trim()); Execute(@"1+1"); Assert.Equal("2\r\n", ReadOutputToEnd().ToString()); } private const string MethodWithInfiniteLoop = @" void foo() { int i = 0; while (true) { if (i < 10) { i = i + 1; } else if (i == 10) { System.Console.Error.WriteLine(""in the loop""); i = i + 1; } } } "; [Fact] public void AsyncExecute_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteAsync(MethodWithInfiniteLoop + "\r\nfoo()"); Assert.True(mayTerminate.WaitOne()); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact(Skip = "529027")] public void AsyncExecute_HangingForegroundThreads() { var mayTerminate = new ManualResetEvent(false); Host.OutputReceived += (_, __) => { mayTerminate.Set(); }; var executeTask = Host.ExecuteAsync(@" using System.Threading; int i1 = 0; Thread t1 = new Thread(() => { while(true) { i1++; } }); t1.Name = ""TestThread-1""; t1.IsBackground = false; t1.Start(); int i2 = 0; Thread t2 = new Thread(() => { while(true) { i2++; } }); t2.Name = ""TestThread-2""; t2.IsBackground = true; t2.Start(); Thread t3 = new Thread(() => Thread.Sleep(Timeout.Infinite)); t3.Name = ""TestThread-3""; t3.Start(); while (i1 < 2 || i2 < 2 || t3.ThreadState != System.Threading.ThreadState.WaitSleepJoin) { } System.Console.WriteLine(""terminate!""); while(true) {} "); Assert.Equal("", ReadErrorOutputToEnd()); Assert.True(mayTerminate.WaitOne()); var service = Host.TryGetService(); Assert.NotNull(service); var process = Host.TryGetProcess(); Assert.NotNull(process); service.EmulateClientExit(); // the process should terminate with exit code 0: process.WaitForExit(); Assert.Equal(0, process.ExitCode); } [Fact] public void AsyncExecuteFile_InfiniteLoop() { var file = Temp.CreateFile().WriteAllText(MethodWithInfiniteLoop + "\r\nfoo();").Path; var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); var executeTask = Host.ExecuteFileAsync(file); mayTerminate.WaitOne(); RestartHost(); executeTask.Wait(); Assert.True(Execute(@"1+1")); Assert.Equal("2\r\n", ReadOutputToEnd()); } [Fact] public void AsyncExecuteFile_SourceKind() { var file = Temp.CreateFile().WriteAllText("1+1").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file + "(1,4):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_NonExistingFile() { var task = Host.ExecuteFileAsync("non existing file"); task.Wait(); Assert.False(task.Result.Success); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.Contains("Specified file not found.", errorOut, StringComparison.Ordinal); Assert.Contains("Searched in directories:", errorOut, StringComparison.Ordinal); } [Fact] public void AsyncExecuteFile() { var file = Temp.CreateFile().WriteAllText(@" using static System.Console; public class C { public int field = 4; public int Foo(int i) { return i; } } public int Foo(int i) { return i; } WriteLine(5); ").Path; var task = Host.ExecuteFileAsync(file); task.Wait(); Assert.True(task.Result.Success); Assert.Equal("5", ReadOutputToEnd().Trim()); Execute("Foo(2)"); Assert.Equal("2", ReadOutputToEnd().Trim()); Execute("new C().Foo(3)"); Assert.Equal("3", ReadOutputToEnd().Trim()); Execute("new C().field"); Assert.Equal("4", ReadOutputToEnd().Trim()); } [Fact] public void AsyncExecuteFile_InvalidFileContent() { var executeTask = Host.ExecuteFileAsync(typeof(Process).Assembly.Location); executeTask.Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(typeof(Process).Assembly.Location + "(1,3):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS1056"), "Error output should include error CS1056"); Assert.True(errorOut.Contains("CS1002"), "Error output should include error CS1002"); } [Fact] public void AsyncExecuteFile_ScriptFileWithBuildErrors() { var file = Temp.CreateFile().WriteAllText("#load blah.csx" + "\r\n" + "class C {}"); Host.ExecuteFileAsync(file.Path).Wait(); var errorOut = ReadErrorOutputToEnd().Trim(); Assert.True(errorOut.StartsWith(file.Path + "(1,7):", StringComparison.Ordinal), "Error output should start with file name, line and column"); Assert.True(errorOut.Contains("CS7010"), "Error output should include error CS7010"); } /// <summary> /// Check that the assembly resolve event doesn't cause any harm. It shouldn't actually be /// even invoked since we resolve the assembly via Fusion. /// </summary> [Fact(Skip = "987032")] public void UserDefinedAssemblyResolve_InfiniteLoop() { var mayTerminate = new ManualResetEvent(false); Host.ErrorOutputReceived += (_, __) => mayTerminate.Set(); Host.TryGetService().HookMaliciousAssemblyResolve(); var executeTask = Host.AddReferenceAsync("nonexistingassembly" + Guid.NewGuid()); Assert.True(mayTerminate.WaitOne()); executeTask.Wait(); Assert.True(Execute(@"1+1")); var output = ReadOutputToEnd(); Assert.Equal("2\r\n", output); } [Fact] public void AddReference_PartialName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference("System").IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact] public void AddReference_PartialName_LatestVersion() { // there might be two versions of System.Data - v2 and v4, we should get the latter: Assert.True(LoadReference("System.Data").IsSuccessful); Assert.True(LoadReference("System").IsSuccessful); Assert.True(LoadReference("System.Xml").IsSuccessful); Execute(@"new System.Data.DataSet().GetType().Assembly.GetName().Version"); var output = ReadOutputToEnd(); Assert.Equal("[4.0.0.0]\r\n", output); } [Fact] public void AddReference_FullName() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.FullName).IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [ConditionalFact(typeof(Framework35Installed))] public void AddReference_VersionUnification1() { var location = typeof(Enumerable).Assembly.Location; // V3.5 unifies with the current Framework version: var result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.True(result.IsSuccessful, "First load"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); } // TODO: merge with previous test [Fact] public void AddReference_VersionUnification2() { var location = typeof(Enumerable).Assembly.Location; var result = LoadReference("System.Core"); Assert.True(result.IsSuccessful, "First load"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); result = LoadReference("System.Core.dll"); Assert.False(result.IsSuccessful, "Already loaded"); Assert.Equal(location, result.Path, StringComparer.OrdinalIgnoreCase); Assert.Equal(location, result.OriginalPath); } [Fact] public void AddReference_Path() { Assert.False(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); Assert.True(LoadReference(typeof(Process).Assembly.Location).IsSuccessful); Assert.True(Execute("System.Diagnostics.Process.GetCurrentProcess().HasExited")); } [Fact(Skip = "530414")] public void AddReference_ShadowCopy() { var dir = Temp.CreateDirectory(); // create C.dll var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); // load C.dll: Assert.True(LoadReference(c.Path).IsSuccessful); Assert.True(Execute("new C()")); Assert.Equal("C { }", ReadOutputToEnd().Trim()); // rewrite C.dll: File.WriteAllBytes(c.Path, new byte[] { 1, 2, 3 }); // we can still run code: var result = Execute("new C()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("C { }", ReadOutputToEnd().Trim()); Assert.True(result); } /// <summary> /// Tests that a dependency is correctly resolved and loaded at runtime. /// A depends on B, which depends on C. When CallB is jitted B is loaded. When CallC is jitted C is loaded. /// </summary> [Fact(Skip = "https://github.com/dotnet/roslyn/issues/860")] public void AddReference_Dependencies() { var dir = Temp.CreateDirectory(); var c = CompileLibrary(dir, "c.dll", "c", @"public class C { }"); var b = CompileLibrary(dir, "b.dll", "b", @"public class B { public static int CallC() { new C(); return 1; } }", MetadataReference.CreateFromImage(c.Image)); var a = CompileLibrary(dir, "a.dll", "a", @"public class A { public static int CallB() { B.CallC(); return 1; } }", MetadataReference.CreateFromImage(b.Image)); AssemblyLoadResult result; result = LoadReference(a.Path); Assert.Equal(a.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); Assert.True(Execute("A.CallB()")); // c.dll is loaded as a dependency, so #r should be successful: result = LoadReference(c.Path); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.True(result.IsSuccessful); // c.dll was already loaded explicitly via #r so we should fail now: result = LoadReference(c.Path); Assert.False(result.IsSuccessful); Assert.Equal(c.Path, result.OriginalPath); Assert.True(IsShadowCopy(result.Path)); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } /// <summary> /// When two files of the same version are in the same directory, prefer .dll over .exe. /// </summary> [Fact] public void AddReference_Dependencies_DllExe() { var dir = Temp.CreateDirectory(); var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); var exe = CompileLibrary(dir, "c.exe", "C", @"public class C { public static int Main() { return 2; } }"); var main = CompileLibrary(dir, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(dll.Image)); Assert.True(LoadReference(main.Path).IsSuccessful); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_Dependencies_Versions() { var dir1 = Temp.CreateDirectory(); var dir2 = Temp.CreateDirectory(); var dir3 = Temp.CreateDirectory(); // [assembly:AssemblyVersion("1.0.0.0")] public class C { public static int Main() { return 1; } }"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(TestResources.General.C1); // [assembly:AssemblyVersion("2.0.0.0")] public class C { public static int Main() { return 2; } }"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(TestResources.General.C2); Assert.True(LoadReference(file1.Path).IsSuccessful); Assert.True(LoadReference(file2.Path).IsSuccessful); var main = CompileLibrary(dir3, "main.exe", "Main", @"public class Program { public static int Main() { return C.Main(); } }", MetadataReference.CreateFromImage(TestResources.General.C2.AsImmutableOrNull())); Assert.True(LoadReference(main.Path).IsSuccessful); Assert.True(Execute("Program.Main()")); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("2", ReadOutputToEnd().Trim()); } [Fact] public void AddReference_AlreadyLoadedDependencies() { var dir = Temp.CreateDirectory(); var lib1 = CompileLibrary(dir, "lib1.dll", "lib1", @"public interface I { int M(); }"); var lib2 = CompileLibrary(dir, "lib2.dll", "lib2", @"public class C : I { public int M() { return 1; } }", MetadataReference.CreateFromFile(lib1.Path)); Execute("#r \"" + lib1.Path + "\""); Execute("#r \"" + lib2.Path + "\""); Execute("new C().M()"); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal("1", ReadOutputToEnd().Trim()); } [Fact(Skip = "530414")] public void AddReference_LoadUpdatedReference() { var dir = Temp.CreateDirectory(); var source1 = "public class C { public int X = 1; }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file = dir.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); // use: Execute(@" #r """ + file.Path + @""" C foo() { return new C(); } new C().X "); // update: var source2 = "public class D { public int Y = 2; }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); file.WriteAllBytes(c2.EmitToArray()); // add the reference again: Execute(@" #r """ + file.Path + @""" new D().Y "); Assert.Equal("", ReadErrorOutputToEnd().Trim()); Assert.Equal( @"1 2", ReadOutputToEnd().Trim()); } [Fact(Skip = "987032")] public void AddReference_MultipleReferencesWithSameWeakIdentity() { var dir = Temp.CreateDirectory(); var dir1 = dir.CreateDirectory("1"); var dir2 = dir.CreateDirectory("2"); var source1 = "public class C1 { }"; var c1 = CreateCompilationWithMscorlib(source1, assemblyName: "C"); var file1 = dir1.CreateFile("c.dll").WriteAllBytes(c1.EmitToArray()); var source2 = "public class C2 { }"; var c2 = CreateCompilationWithMscorlib(source2, assemblyName: "C"); var file2 = dir2.CreateFile("c.dll").WriteAllBytes(c2.EmitToArray()); Execute(@" #r """ + file1.Path + @""" #r """ + file2.Path + @""" "); Execute("new C1()"); Execute("new C2()"); Assert.Equal( @"(2,1): error CS1704: An assembly with the same simple name 'C' has already been imported. Try removing one of the references (e.g. '" + file1.Path + @"') or sign them to enable side-by-side. (1,5): error CS0246: The type or namespace name 'C1' could not be found (are you missing a using directive or an assembly reference?) (1,5): error CS0246: The type or namespace name 'C2' could not be found (are you missing a using directive or an assembly reference?)", ReadErrorOutputToEnd().Trim()); Assert.Equal("", ReadOutputToEnd().Trim()); } //// TODO (987032): //// [Fact] //// public void AsyncInitializeContextWithDotNETLibraries() //// { //// var rspFile = Temp.CreateFile(); //// var rspDisplay = Path.GetFileName(rspFile.Path); //// var initScript = Temp.CreateFile(); //// rspFile.WriteAllText(@" /////r:System.Core ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Linq.Expressions; ////WriteLine(Expression.Constant(123)); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var output = SplitLines(ReadOutputToEnd()); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(typeof(Compilation).Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("123", output[3]); //// Assert.Equal("", errorOutput); //// Host.InitializeContextAsync(rspFile.Path).Wait(); //// output = SplitLines(ReadOutputToEnd()); //// errorOutput = ReadErrorOutputToEnd(); //// Assert.True(2 == output.Length, "Output is: '" + string.Join("<NewLine>", output) + "'. Expecting 2 lines."); //// Assert.Equal("Loading context from '" + rspDisplay + "'.", output[0]); //// Assert.Equal("123", output[1]); //// Assert.Equal("", errorOutput); //// } //// [Fact] //// public void AsyncInitializeContextWithBothUserDefinedAndDotNETLibraries() //// { //// var dir = Temp.CreateDirectory(); //// var rspFile = Temp.CreateFile(); //// var initScript = Temp.CreateFile(); //// var dll = CompileLibrary(dir, "c.dll", "C", @"public class C { public static int Main() { return 1; } }"); //// rspFile.WriteAllText(@" /////r:System.Numerics /////r:" + dll.Path + @" ////""" + initScript.Path + @""" ////"); //// initScript.WriteAllText(@" ////using static System.Console; ////using System.Numerics; ////WriteLine(new Complex(12, 6).Real + C.Main()); ////"); //// // override default "is restarting" behavior (the REPL is already initialized): //// var task = Host.InitializeContextAsync(rspFile.Path, isRestarting: false, killProcess: true); //// task.Wait(); //// var errorOutput = ReadErrorOutputToEnd(); //// Assert.Equal("", errorOutput); //// var output = SplitLines(ReadOutputToEnd()); //// Assert.Equal(4, output.Length); //// Assert.Equal("Microsoft (R) Roslyn C# Compiler version " + FileVersionInfo.GetVersionInfo(Host.GetType().Assembly.Location).FileVersion, output[0]); //// Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[1]); //// Assert.Equal("Type \"#help\" for more information.", output[2]); //// Assert.Equal("13", output[3]); //// } [Fact] public void ReferencePaths() { var directory = Temp.CreateDirectory(); var assemblyName = GetUniqueName(); CompileLibrary(directory, assemblyName + ".dll", assemblyName, @"public class C { }"); var rspFile = Temp.CreateFile(); rspFile.WriteAllText("/rp:" + directory.Path); var task = Host.ResetAsync(InteractiveHostOptions.Default.WithInitializationFile(rspFile.Path)); task.Wait(); Execute( $@"#r ""{assemblyName}.dll"" typeof(C).Assembly.GetName()"); var output = SplitLines(ReadOutputToEnd()); Assert.Equal(2, output.Length); Assert.Equal("Loading context from '" + Path.GetFileName(rspFile.Path) + "'.", output[0]); Assert.Equal($"[{assemblyName}, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]", output[1]); } [Fact] public void ReferenceDirectives() { Execute(@" #r ""System.Numerics"" #r """ + typeof(System.Linq.Expressions.Expression).Assembly.Location + @""" using static System.Console; using System.Linq.Expressions; using System.Numerics; WriteLine(Expression.Constant(1)); WriteLine(new Complex(2, 6).Real); "); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n", output); } [Fact] public void ExecutesOnStaThread() { Execute(@" #r ""System"" #r ""System.Xaml"" #r ""WindowsBase"" #r ""PresentationCore"" #r ""PresentationFramework"" new System.Windows.Window(); System.Console.WriteLine(""OK""); "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("OK\r\n", output); } /// <summary> /// Execution of expressions should be /// sequential, even await expressions. /// </summary> [Fact] public void ExecuteSequentially() { Execute(@"using System; using System.Threading.Tasks;"); Execute(@"await Task.Delay(1000).ContinueWith(t => 1)"); Execute(@"await Task.Delay(500).ContinueWith(t => 2)"); Execute(@"3"); var output = ReadOutputToEnd(); Assert.Equal("1\r\n2\r\n3\r\n", output); } [Fact] public void MultiModuleAssembly() { var dir = Temp.CreateDirectory(); var dll = dir.CreateFile("MultiModule.dll").WriteAllBytes(TestResources.SymbolsTests.MultiModule.MultiModuleDll); dir.CreateFile("mod2.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod2); dir.CreateFile("mod3.netmodule").WriteAllBytes(TestResources.SymbolsTests.MultiModule.mod3); Execute(@" #r """ + dll.Path + @""" new object[] { new Class1(), new Class2(), new Class3() } "); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); var output = ReadOutputToEnd(); Assert.Equal("object[3] { Class1 { }, Class2 { }, Class3 { } }\r\n", output); } [Fact] public void SearchPaths1() { var dll = Temp.CreateFile(extension: ".dll").WriteAllBytes(TestResources.MetadataTests.InterfaceAndClass.CSInterfaces01); var srcDir = Temp.CreateDirectory(); var dllDir = Path.GetDirectoryName(dll.Path); srcDir.CreateFile("foo.csx").WriteAllText("ReferencePaths.Add(@\"" + dllDir + "\");"); Func<string, string> normalizeSeparatorsAndFrameworkFolders = (s) => s.Replace("\\", "\\\\").Replace("Framework64", "Framework"); // print default: Host.ExecuteAsync(@"ReferencePaths").Wait(); var output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultReferenceSearchPaths)) + "\" }\r\n", output); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths)) + "\" }\r\n", output); // add and test if added: Host.ExecuteAsync("SourcePaths.Add(@\"" + srcDir + "\");").Wait(); Host.ExecuteAsync(@"SourcePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultSourceSearchPaths.Concat(new[] { srcDir.Path }))) + "\" }\r\n", output); // execute file (uses modified search paths), the file adds a reference path Host.ExecuteFileAsync("foo.csx").Wait(); Host.ExecuteAsync(@"ReferencePaths").Wait(); output = ReadOutputToEnd(); Assert.Equal("SearchPaths { \"" + normalizeSeparatorsAndFrameworkFolders(string.Join("\", \"", InteractiveHost.Service.DefaultReferenceSearchPaths.Concat(new[] { dllDir }))) + "\" }\r\n", output); Host.AddReferenceAsync(Path.GetFileName(dll.Path)).Wait(); Host.ExecuteAsync(@"typeof(Metadata.ICSProp)").Wait(); var error = ReadErrorOutputToEnd(); Assert.Equal("", error); output = ReadOutputToEnd(); Assert.Equal("[Metadata.ICSProp]\r\n", output); } [Fact] public void InvalidArguments() { Assert.Throws<FileNotFoundException>(() => LoadReference("")); Assert.Throws<FileNotFoundException>(() => LoadReference("\0")); Assert.Throws<FileNotFoundException>(() => LoadReference("blah \0")); Assert.Throws<FileNotFoundException>(() => LoadReference("*.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("*.exe")); Assert.Throws<FileNotFoundException>(() => LoadReference("http://foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("blah:foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("C:\\" + new string('x', 10000) + "\\foo.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference("system,mscorlib")); Assert.Throws<FileNotFoundException>(() => LoadReference(@"\\sample\sample1.dll")); Assert.Throws<FileNotFoundException>(() => LoadReference(typeof(string).Assembly.Location + " " + typeof(string).Assembly.Location)); } #region Submission result printing - null/void/value. [Fact] public void SubmissionResult_PrintingNull() { Execute(@" string s; s "); var output = ReadOutputToEnd(); Assert.Equal("null\r\n", output); } [Fact] public void SubmissionResult_PrintingVoid() { Execute(@"System.Console.WriteLine(2)"); var output = ReadOutputToEnd(); Assert.Equal("2\r\n<void>\r\n", output); Execute(@" void foo() { } foo() "); output = ReadOutputToEnd(); Assert.Equal("<void>\r\n", output); } #endregion private static ImmutableArray<string> SplitLines(string text) { return ImmutableArray.Create(text.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries)); } } }
//----------------------------------------------------------------------- // <copyright file="SmartDateTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>no summary</summary> //----------------------------------------------------------------------- using Csla; using Csla.Serialization; using Csla.Testing.Business.ReadOnlyTest; using System; using UnitDriven; #if !WINDOWS_PHONE using Microsoft.VisualBasic; #endif using Csla.Serialization.Mobile; using System.Threading; #if NUNIT using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; using TestCleanup = NUnit.Framework.TearDownAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestSetup = NUnit.Framework.SetUpAttribute; using Microsoft.VisualBasic; using Csla.Serialization.Mobile; #elif MSTEST using Microsoft.VisualStudio.TestTools.UnitTesting; #endif namespace Csla.Test.SmartDate { [TestClass()] public class SmartDateTests { System.Globalization.CultureInfo CurrentCulture { get; set; } System.Globalization.CultureInfo CurrentUICulture { get; set; } [TestInitialize] public void Setup() { // store current cultures CurrentCulture = System.Threading.Thread.CurrentThread.CurrentCulture; CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentUICulture; // set to "en-US" for all tests System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo("en-US"); } [TestCleanup] public void Cleanup() { // restore original cultures System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCulture; System.Threading.Thread.CurrentThread.CurrentUICulture = CurrentUICulture; } #region Test Constructors [TestMethod()] public void TestSmartDateConstructors() { DateTime now = DateTime.Now; Csla.SmartDate d = new Csla.SmartDate(now); Assert.AreEqual(now, d.Date); d = new Csla.SmartDate(true); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate(false); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate("1/1/2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("Jan/1/2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("January-1-2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate("1-1-2005"); Assert.AreEqual("1/1/2005", d.ToString()); d = new Csla.SmartDate(""); Assert.AreEqual("", d.ToString()); Assert.IsTrue(d.IsEmpty); d = new Csla.SmartDate("1/1/2005", true); Assert.AreEqual("1/1/2005", d.ToString()); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate("1/1/2005", false); Assert.AreEqual("1/1/2005", d.ToString()); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate("", true); Assert.AreEqual(DateTime.MinValue, d.Date); Assert.AreEqual("", d.ToString()); d = new Csla.SmartDate("", false); Assert.AreEqual(DateTime.MaxValue, d.Date); Assert.AreEqual("", d.ToString()); try { d = new Csla.SmartDate("Invalid Date", true); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } try { d = new Csla.SmartDate("Invalid Date", false); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } d = new Csla.SmartDate(now, true); Assert.AreEqual(now, d.Date); Assert.IsTrue(d.EmptyIsMin); d = new Csla.SmartDate(now, false); Assert.AreEqual(now, d.Date); Assert.IsFalse(d.EmptyIsMin); d = new Csla.SmartDate((DateTime?)null, true); Assert.AreEqual(DateTime.MinValue, d.Date); d = new Csla.SmartDate((DateTime?)null, false); Assert.AreEqual(DateTime.MaxValue, d.Date); d = new Csla.SmartDate((DateTime?)null, Csla.SmartDate.EmptyValue.MinDate); Assert.AreEqual(DateTime.MinValue, d.Date); d = new Csla.SmartDate((DateTime?)null, Csla.SmartDate.EmptyValue.MaxDate); Assert.AreEqual(DateTime.MaxValue, d.Date); } #endregion #region Converters [TestMethod] public void TestConverters() { DateTime d = Csla.SmartDate.StringToDate("1/1/2005"); Assert.AreEqual("1/1/2005", d.ToShortDateString()); d = Csla.SmartDate.StringToDate("january-1-2005"); Assert.AreEqual("1/1/2005", d.ToShortDateString()); d = Csla.SmartDate.StringToDate("."); Assert.AreEqual(DateTime.Now.ToShortDateString(), d.ToShortDateString()); d = Csla.SmartDate.StringToDate("-"); Assert.AreEqual(DateTime.Now.AddDays(-1.0).ToShortDateString(), d.ToShortDateString()); d = Csla.SmartDate.StringToDate("+"); Assert.AreEqual(DateTime.Now.AddDays(1.0).ToShortDateString(), d.ToShortDateString()); try { d = Csla.SmartDate.StringToDate("Invalid Date"); } catch (Exception ex) { Assert.IsTrue(ex is System.ArgumentException); } d = Csla.SmartDate.StringToDate(""); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate(null); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate("", true); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate("", false); Assert.AreEqual(DateTime.MaxValue, d); try { d = Csla.SmartDate.StringToDate("Invalid Date", true); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } try { d = Csla.SmartDate.StringToDate("Invalid Date", false); } catch (Exception ex) { Assert.IsTrue(ex is ArgumentException); } d = Csla.SmartDate.StringToDate(null, true); Assert.AreEqual(DateTime.MinValue, d); d = Csla.SmartDate.StringToDate(null, false); Assert.AreEqual(DateTime.MaxValue, d); d = new DateTime(2005, 1, 2); string date = Csla.SmartDate.DateToString(d, "dd/MM/yyyy"); Assert.AreEqual("02/01/2005", date, "dd/MM/yyyy test"); date = Csla.SmartDate.DateToString(d, "MM/dd/yy"); Assert.AreEqual("01/02/05", date, "MM/dd/yy test"); date = Csla.SmartDate.DateToString(d, ""); Assert.AreEqual("1/2/2005 12:00:00 AM", date); date = Csla.SmartDate.DateToString(d, "d"); Assert.AreEqual("1/2/2005", date); date = new Csla.SmartDate(d).ToString(); Assert.AreEqual("1/2/2005", date); date = Csla.SmartDate.DateToString(DateTime.MinValue, "dd/MM/yyyy", true); Assert.AreEqual("", date, "MinValue w/ emptyIsMin=true"); date = Csla.SmartDate.DateToString(DateTime.MinValue, "dd/MM/yyyy", false); Assert.AreEqual(DateTime.MinValue.ToString("dd/MM/yyyy"), date, "MinValue w/ emptyIsMin=false"); date = Csla.SmartDate.DateToString(DateTime.MaxValue, "dd/MM/yyyy", true); Assert.AreEqual(DateTime.MaxValue.ToString("dd/MM/yyyy"), date, "MaxValue w/ emptyIsMin=true"); date = Csla.SmartDate.DateToString(DateTime.MaxValue, "dd/MM/yyyy", false); Assert.AreEqual("", date, "MaxValue w/ emptyIsMin=false"); } #endregion #if !WINDOWS_PHONE #region Add [TestMethod()] public void Add() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Add(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(DateAndTime.DateAdd(DateInterval.Day, 30, d2.Date), d3.Date, "Dates should be equal"); Assert.AreEqual(d3, d2 + new TimeSpan(30, 0, 0, 0, 0), "Dates should be equal"); } #endregion #region Subtract [TestMethod()] public void Subtract() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Subtract(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(DateAndTime.DateAdd(DateInterval.Day, -30, d2.Date), d3.Date, "Dates should be equal"); Assert.AreEqual(30, ((TimeSpan)(d2 - d3)).Days, "Should be 30 days different"); Assert.AreEqual(d3, d2 - new TimeSpan(30, 0, 0, 0, 0), "Should be equal"); } #endregion #endif #region Comparison [TestMethod()] public void Comparison() { Csla.SmartDate d2 = new Csla.SmartDate(true); Csla.SmartDate d3 = new Csla.SmartDate(false); Csla.SmartDate d4 = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MinDate); Csla.SmartDate d5 = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MaxDate); Assert.IsTrue(d2.Equals(d3), "Empty dates should be equal"); Assert.IsTrue(Csla.SmartDate.Equals(d2, d3), "Empty dates should be equal (shared)"); Assert.IsTrue(d2.Equals(d3), "Empty dates should be equal (unary)"); Assert.IsTrue(d2.Equals(""), "Should be equal to an empty string (d2)"); Assert.IsTrue(d3.Equals(""), "Should be equal to an empty string (d3)"); Assert.IsTrue(d2.Date.Equals(DateTime.MinValue), "Should be DateTime.MinValue"); Assert.IsTrue(d3.Date.Equals(DateTime.MaxValue), "Should be DateTime.MaxValue"); Assert.IsTrue(d4.Date.Equals(DateTime.MinValue), "Should be DateTime.MinValue (d4)"); Assert.IsTrue(d5.Date.Equals(DateTime.MaxValue), "Should be DateTime.MaxValue (d5)"); d2.Date = new DateTime(2005, 1, 1); d3 = new Csla.SmartDate(d2.Date, d2.EmptyIsMin); Assert.AreEqual(d2, d3, "Assigned dates should be equal"); d3.Date = new DateTime(2005, 2, 2); Assert.AreEqual(1, d3.CompareTo(d2), "Should be greater than"); Assert.AreEqual(-1, d2.CompareTo(d3), "Should be less than"); Assert.IsFalse(d2.CompareTo(d3) == 0, "should not be equal"); d3.Date = new DateTime(2005, 1, 1); Assert.IsFalse(1 == d2.CompareTo(d3), "should be equal"); Assert.IsFalse(-1 == d2.CompareTo(d3), "should be equal"); Assert.AreEqual(0, d2.CompareTo(d3), "should be equal"); Assert.IsTrue(d3.Equals("1/1/2005"), "Should be equal to string date"); Assert.IsTrue(d3.Equals(new DateTime(2005, 1, 1)), "should be equal to DateTime"); Assert.IsTrue(d3.Equals(d2.Date.ToString()), "Should be equal to any date time string"); Assert.IsTrue(d3.Equals(d2.Date.ToLongDateString()), "Should be equal to any date time string"); Assert.IsTrue(d3.Equals(d2.Date.ToShortDateString()), "Should be equal to any date time string"); Assert.IsFalse(d3.Equals(""), "Should not be equal to a blank string"); //DateTime can be compared using all sorts of formats but the SmartDate cannot. //DateTime dt = DateTime.Now; //long ldt = dt.ToBinary(); //Assert.IsTrue(dt.Equals(ldt), "Should be equal"); //Should smart date also be converted into these various types? } #endregion #region Empty [TestMethod()] public void Empty() { Csla.SmartDate d2 = new Csla.SmartDate(); Csla.SmartDate d3; d3 = new Csla.SmartDate(d2.Add(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(d2, d3, "Dates should be equal"); Assert.AreEqual("", d2.Text, "Text should be empty"); d3 = new Csla.SmartDate(d2.Subtract(new TimeSpan(30, 0, 0, 0))); Assert.AreEqual(d2, d3, "Dates should be equal"); Assert.AreEqual("", d2.Text, "Text should be empty"); d3 = new Csla.SmartDate(); Assert.AreEqual(0, d2.CompareTo(d3), "d2 and d3 should be the same"); Assert.IsTrue(d2.Equals(d3), "d2 and d3 should be the same"); Assert.IsTrue(Csla.SmartDate.Equals(d2, d3), "d2 and d3 should be the same"); d3.Date = DateTime.Now; Assert.AreEqual(-1, d2.CompareTo(d3), "d2 and d3 should not be the same"); Assert.AreEqual(1, d3.CompareTo(d2), "d2 and d3 should not be the same"); Assert.IsFalse(d2.Equals(d3), "d2 and d3 should not be the same"); Assert.IsFalse(Csla.SmartDate.Equals(d2, d3), "d2 and d3 should not be the same"); Assert.IsFalse(d3.Equals(d2), "d2 and d3 should not be the same"); Assert.IsFalse(Csla.SmartDate.Equals(d3, d2), "d2 and d3 should not be the same"); } [TestMethod] public void MaxDateMaxValue() { // test for maxDateValue Csla.SmartDate target = new Csla.SmartDate(Csla.SmartDate.EmptyValue.MaxDate); DateTime expected = DateTime.MaxValue; DateTime actual = target.Date; Assert.AreEqual(expected, actual); } #endregion #region Comparison Operators [TestMethod()] public void ComparisonOperators() { Csla.SmartDate d1 = new Csla.SmartDate(); Csla.SmartDate d2 = new Csla.SmartDate(); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 < d2, "d1 should be less than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 < d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 < d2, "d1 should be greater than d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 > d2, "d1 should be greater than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 > d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 > d2, "d1 should be less than d2"); d1.Date = new DateTime(2005, 2, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 == d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 == d2, "d1 should not be equal to d2"); //#warning Smart date does not overload the <= or >= operators! //Assert.Fail("Missing <= and >= operators"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 <= d2, "d1 should be less than or equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 <= d2, "d1 should be less than or equal to d2"); d1.Date = new DateTime(2005, 3, 1); Assert.IsFalse(d1 <= d2, "d1 should be greater than to d2"); d1.Date = new DateTime(2005, 3, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 >= d2, "d1 should be greater than or equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 >= d2, "d1 should be greater than or equal to d2"); d1.Date = new DateTime(2005, 1, 1); Assert.IsFalse(d1 >= d2, "d1 should be less than to d2"); d1.Date = new DateTime(2005, 1, 1); d2.Date = new DateTime(2005, 2, 1); Assert.IsTrue(d1 != d2, "d1 should not be equal to d2"); d1.Date = new DateTime(2005, 2, 1); Assert.IsFalse(d1 != d2, "d1 should be equal to d2"); d1.Date = new DateTime(2005, 3, 1); Assert.IsTrue(d1 != d2, "d1 should be greater than d2"); } [TestMethod] public void TryParseTest() { Csla.SmartDate sd = new Csla.SmartDate(); if (Csla.SmartDate.TryParse("blah", ref sd)) Assert.AreEqual(true, false, "TryParse should have failed"); if (Csla.SmartDate.TryParse("t", ref sd)) Assert.AreEqual(DateTime.Now.Date, sd.Date.Date, "Date should have been now"); else Assert.AreEqual(true, false, "TryParse should have succeeded"); } #endregion #region Serialization [TestMethod()] public void SerializationTest() { Csla.SmartDate d2; d2 = new Csla.SmartDate(); Csla.SmartDate clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); d2 = new Csla.SmartDate(DateTime.Now, false); clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); d2 = new Csla.SmartDate(DateTime.Now.AddDays(10), false); d2.FormatString = "YYYY/DD/MM"; clone = (Csla.SmartDate)MobileFormatter.Deserialize(MobileFormatter.Serialize(d2)); Assert.AreEqual(d2, clone, "Dates should have ben the same"); cslalighttest.Serialization.PersonWIthSmartDateField person; person = cslalighttest.Serialization.PersonWIthSmartDateField.GetPersonWIthSmartDateField("Sergey", 2000); Assert.AreEqual(person.Birthdate, person.Clone().Birthdate, "Dates should have ben the same"); Csla.SmartDate expected = person.Birthdate; person.BeginEdit(); person.Birthdate = new Csla.SmartDate(expected.Date.AddDays(10)); // to guarantee it's a different value person.CancelEdit(); Csla.SmartDate actual = person.Birthdate; Assert.AreEqual(expected, actual); } #endregion [TestMethod] public void DefaultFormat() { var obj = new SDtest(); Assert.AreEqual("", obj.TextDate, "Should be empty"); var now = DateTime.Now; obj.TextDate = string.Format("{0:g}", now); Assert.AreEqual(string.Format("{0:g}", now), obj.TextDate, "Should be today"); } [TestMethod] public void CustomParserReturnsDateTime() { Csla.SmartDate.CustomParser = (s) => { if (s == "test") return DateTime.Now; return null; }; // uses custom parser var date = new Csla.SmartDate("test"); Assert.AreEqual(DateTime.Now.Date, date.Date.Date); // uses buildin parser var date2 = new Csla.SmartDate("t"); Assert.AreEqual(DateTime.Now.Date, date.Date.Date); } } [Serializable] public class SDtest : BusinessBase<SDtest> { public static PropertyInfo<Csla.SmartDate> TextDateProperty = RegisterProperty<Csla.SmartDate>(c => c.TextDate, null, new Csla.SmartDate { FormatString = "g" }); public string TextDate { get { return GetPropertyConvert<Csla.SmartDate, string>(TextDateProperty); } set { SetPropertyConvert<Csla.SmartDate, string>(TextDateProperty, value); } } public static PropertyInfo<Csla.SmartDate> MyDateProperty = RegisterProperty<Csla.SmartDate>(c => c.MyDate); public Csla.SmartDate MyDate { get { return GetProperty(MyDateProperty); } set { SetProperty(MyDateProperty, value); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.Serialization; namespace System.Globalization { // This abstract class represents a calendar. A calendar reckons time in // divisions such as weeks, months and years. The number, length and start of // the divisions vary in each calendar. // // Any instant in time can be represented as an n-tuple of numeric values using // a particular calendar. For example, the next vernal equinox occurs at (0.0, 0 // , 46, 8, 20, 3, 1999) in the Gregorian calendar. An implementation of // Calendar can map any DateTime value to such an n-tuple and vice versa. The // DateTimeFormat class can map between such n-tuples and a textual // representation such as "8:46 AM March 20th 1999 AD". // // Most calendars identify a year which begins the current era. There may be any // number of previous eras. The Calendar class identifies the eras as enumerated // integers where the current era (CurrentEra) has the value zero. // // For consistency, the first unit in each interval, e.g. the first month, is // assigned the value one. // The calculation of hour/minute/second is moved to Calendar from GregorianCalendar, // since most of the calendars (or all?) have the same way of calcuating hour/minute/second. public abstract class Calendar : ICloneable { // Number of 100ns (10E-7 second) ticks per time unit internal const long TicksPerMillisecond = 10000; internal const long TicksPerSecond = TicksPerMillisecond * 1000; internal const long TicksPerMinute = TicksPerSecond * 60; internal const long TicksPerHour = TicksPerMinute * 60; internal const long TicksPerDay = TicksPerHour * 24; // Number of milliseconds per time unit internal const int MillisPerSecond = 1000; internal const int MillisPerMinute = MillisPerSecond * 60; internal const int MillisPerHour = MillisPerMinute * 60; internal const int MillisPerDay = MillisPerHour * 24; // Number of days in a non-leap year internal const int DaysPerYear = 365; // Number of days in 4 years internal const int DaysPer4Years = DaysPerYear * 4 + 1; // Number of days in 100 years internal const int DaysPer100Years = DaysPer4Years * 25 - 1; // Number of days in 400 years internal const int DaysPer400Years = DaysPer100Years * 4 + 1; // Number of days from 1/1/0001 to 1/1/10000 internal const int DaysTo10000 = DaysPer400Years * 25 - 366; internal const long MaxMillis = (long)DaysTo10000 * MillisPerDay; private int _currentEraValue = -1; private bool _isReadOnly = false; // The minimum supported DateTime range for the calendar. public virtual DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } // The maximum supported DateTime range for the calendar. public virtual DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public virtual CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.Unknown; } } protected Calendar() { //Do-nothing constructor. } /// // This can not be abstract, otherwise no one can create a subclass of Calendar. // internal virtual CalendarId ID { get { return CalendarId.UNINITIALIZED_VALUE; } } /// // Return the Base calendar ID for calendars that didn't have defined data in calendarData // internal virtual CalendarId BaseCalendarID { get { return ID; } } //////////////////////////////////////////////////////////////////////// // // IsReadOnly // // Detect if the object is readonly. // //////////////////////////////////////////////////////////////////////// public bool IsReadOnly { get { return (_isReadOnly); } } //////////////////////////////////////////////////////////////////////// // // Clone // // Is the implementation of ICloneable. // //////////////////////////////////////////////////////////////////////// public virtual object Clone() { object o = MemberwiseClone(); ((Calendar)o).SetReadOnlyState(false); return (o); } //////////////////////////////////////////////////////////////////////// // // ReadOnly // // Create a cloned readonly instance or return the input one if it is // readonly. // //////////////////////////////////////////////////////////////////////// public static Calendar ReadOnly(Calendar calendar) { if (calendar == null) { throw new ArgumentNullException(nameof(calendar)); } Contract.EndContractBlock(); if (calendar.IsReadOnly) { return (calendar); } Calendar clonedCalendar = (Calendar)(calendar.MemberwiseClone()); clonedCalendar.SetReadOnlyState(true); return (clonedCalendar); } internal void VerifyWritable() { if (_isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } } internal void SetReadOnlyState(bool readOnly) { _isReadOnly = readOnly; } /*=================================CurrentEraValue========================== **Action: This is used to convert CurretEra(0) to an appropriate era value. **Returns: **Arguments: **Exceptions: **Notes: ** The value is from calendar.nlp. ============================================================================*/ internal virtual int CurrentEraValue { get { // The following code assumes that the current era value can not be -1. if (_currentEraValue == -1) { Debug.Assert(BaseCalendarID != CalendarId.UNINITIALIZED_VALUE, "[Calendar.CurrentEraValue] Expected a real calendar ID"); _currentEraValue = CalendarData.GetCalendarData(BaseCalendarID).iCurrentEra; } return (_currentEraValue); } } // The current era for a calendar. public const int CurrentEra = 0; internal int twoDigitYearMax = -1; internal static void CheckAddResult(long ticks, DateTime minValue, DateTime maxValue) { if (ticks < minValue.Ticks || ticks > maxValue.Ticks) { throw new ArgumentException( String.Format(CultureInfo.InvariantCulture, SR.Format(SR.Argument_ResultCalendarRange, minValue, maxValue))); } Contract.EndContractBlock(); } internal DateTime Add(DateTime time, double value, int scale) { // From ECMA CLI spec, Partition III, section 3.27: // // If overflow occurs converting a floating-point type to an integer, or if the floating-point value // being converted to an integer is a NaN, the value returned is unspecified. // // Based upon this, this method should be performing the comparison against the double // before attempting a cast. Otherwise, the result is undefined. double tempMillis = (value * scale + (value >= 0 ? 0.5 : -0.5)); if (!((tempMillis > -(double)MaxMillis) && (tempMillis < (double)MaxMillis))) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_AddValue); } long millis = (long)tempMillis; long ticks = time.Ticks + millis * TicksPerMillisecond; CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // milliseconds to the specified DateTime. The result is computed by rounding // the number of milliseconds given by value to the nearest integer, // and adding that interval to the specified DateTime. The value // argument is permitted to be negative. // public virtual DateTime AddMilliseconds(DateTime time, double milliseconds) { return (Add(time, milliseconds, 1)); } // Returns the DateTime resulting from adding a fractional number of // days to the specified DateTime. The result is computed by rounding the // fractional number of days given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddDays(DateTime time, int days) { return (Add(time, days, MillisPerDay)); } // Returns the DateTime resulting from adding a fractional number of // hours to the specified DateTime. The result is computed by rounding the // fractional number of hours given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddHours(DateTime time, int hours) { return (Add(time, hours, MillisPerHour)); } // Returns the DateTime resulting from adding a fractional number of // minutes to the specified DateTime. The result is computed by rounding the // fractional number of minutes given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddMinutes(DateTime time, int minutes) { return (Add(time, minutes, MillisPerMinute)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public abstract DateTime AddMonths(DateTime time, int months); // Returns the DateTime resulting from adding a number of // seconds to the specified DateTime. The result is computed by rounding the // fractional number of seconds given by value to the nearest // millisecond, and adding that interval to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddSeconds(DateTime time, int seconds) { return Add(time, seconds, MillisPerSecond); } // Returns the DateTime resulting from adding a number of // weeks to the specified DateTime. The // value argument is permitted to be negative. // public virtual DateTime AddWeeks(DateTime time, int weeks) { return (AddDays(time, weeks * 7)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public abstract DateTime AddYears(DateTime time, int years); // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public abstract int GetDayOfMonth(DateTime time); // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public abstract DayOfWeek GetDayOfWeek(DateTime time); // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public abstract int GetDayOfYear(DateTime time); // Returns the number of days in the month given by the year and // month arguments. // public virtual int GetDaysInMonth(int year, int month) { return (GetDaysInMonth(year, month, CurrentEra)); } // Returns the number of days in the month given by the year and // month arguments for the specified era. // public abstract int GetDaysInMonth(int year, int month, int era); // Returns the number of days in the year given by the year argument for the current era. // public virtual int GetDaysInYear(int year) { return (GetDaysInYear(year, CurrentEra)); } // Returns the number of days in the year given by the year argument for the current era. // public abstract int GetDaysInYear(int year, int era); // Returns the era for the specified DateTime value. public abstract int GetEra(DateTime time); /*=================================Eras========================== **Action: Get the list of era values. **Returns: The int array of the era names supported in this calendar. ** null if era is not used. **Arguments: None. **Exceptions: None. ============================================================================*/ public abstract int[] Eras { get; } // Returns the hour part of the specified DateTime. The returned value is an // integer between 0 and 23. // public virtual int GetHour(DateTime time) { return ((int)((time.Ticks / TicksPerHour) % 24)); } // Returns the millisecond part of the specified DateTime. The returned value // is an integer between 0 and 999. // public virtual double GetMilliseconds(DateTime time) { return (double)((time.Ticks / TicksPerMillisecond) % 1000); } // Returns the minute part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetMinute(DateTime time) { return ((int)((time.Ticks / TicksPerMinute) % 60)); } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public abstract int GetMonth(DateTime time); // Returns the number of months in the specified year in the current era. public virtual int GetMonthsInYear(int year) { return (GetMonthsInYear(year, CurrentEra)); } // Returns the number of months in the specified year and era. public abstract int GetMonthsInYear(int year, int era); // Returns the second part of the specified DateTime. The returned value is // an integer between 0 and 59. // public virtual int GetSecond(DateTime time) { return ((int)((time.Ticks / TicksPerSecond) % 60)); } /*=================================GetFirstDayWeekOfYear========================== **Action: Get the week of year using the FirstDay rule. **Returns: the week of year. **Arguments: ** time ** firstDayOfWeek the first day of week (0=Sunday, 1=Monday, ... 6=Saturday) **Notes: ** The CalendarWeekRule.FirstDay rule: Week 1 begins on the first day of the year. ** Assume f is the specifed firstDayOfWeek, ** and n is the day of week for January 1 of the specified year. ** Assign offset = n - f; ** Case 1: offset = 0 ** E.g. ** f=1 ** weekday 0 1 2 3 4 5 6 0 1 ** date 1/1 ** week# 1 2 ** then week of year = (GetDayOfYear(time) - 1) / 7 + 1 ** ** Case 2: offset < 0 ** e.g. ** n=1 f=3 ** weekday 0 1 2 3 4 5 6 0 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 5 days before 1/1. ** So week of year = (GetDayOfYear(time) + (7 + offset) - 1) / 7 + 1 ** Case 3: offset > 0 ** e.g. ** f=0 n=2 ** weekday 0 1 2 3 4 5 6 0 1 2 ** date 1/1 ** week# 1 2 ** This means that the first week actually starts 2 days before 1/1. ** So Week of year = (GetDayOfYear(time) + offset - 1) / 7 + 1 ============================================================================*/ internal int GetFirstDayWeekOfYear(DateTime time, int firstDayOfWeek) { int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // Calculate the day of week for the first day of the year. // dayOfWeek - (dayOfYear % 7) is the day of week for the first day of this year. Note that // this value can be less than 0. It's fine since we are making it positive again in calculating offset. int dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); int offset = (dayForJan1 - firstDayOfWeek + 14) % 7; Debug.Assert(offset >= 0, "Calendar.GetFirstDayWeekOfYear(): offset >= 0"); return ((dayOfYear + offset) / 7 + 1); } private int GetWeekOfYearFullDays(DateTime time, int firstDayOfWeek, int fullDays) { int dayForJan1; int offset; int day; int dayOfYear = GetDayOfYear(time) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. // // Calculate the number of days between the first day of year (1/1) and the first day of the week. // This value will be a positive value from 0 ~ 6. We call this value as "offset". // // If offset is 0, it means that the 1/1 is the start of the first week. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 12/31 1/1 1/2 1/3 1/4 1/5 1/6 // +--> First week starts here. // // If offset is 1, it means that the first day of the week is 1 day ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 // +--> First week starts here. // // If offset is 2, it means that the first day of the week is 2 days ahead of 1/1. // Assume the first day of the week is Monday, it will look like this: // Sat Sun Mon Tue Wed Thu Fri Sat // 1/1 1/2 1/3 1/4 1/5 1/6 1/7 1/8 // +--> First week starts here. // Day of week is 0-based. // Get the day of week for 1/1. This can be derived from the day of week of the target day. // Note that we can get a negative value. It's ok since we are going to make it a positive value when calculating the offset. dayForJan1 = (int)GetDayOfWeek(time) - (dayOfYear % 7); // Now, calculate the offset. Subtract the first day of week from the dayForJan1. And make it a positive value. offset = (firstDayOfWeek - dayForJan1 + 14) % 7; if (offset != 0 && offset >= fullDays) { // // If the offset is greater than the value of fullDays, it means that // the first week of the year starts on the week where Jan/1 falls on. // offset -= 7; } // // Calculate the day of year for specified time by taking offset into account. // day = dayOfYear - offset; if (day >= 0) { // // If the day of year value is greater than zero, get the week of year. // return (day / 7 + 1); } // // Otherwise, the specified time falls on the week of previous year. // Call this method again by passing the last day of previous year. // // the last day of the previous year may "underflow" to no longer be a valid date time for // this calendar if we just subtract so we need the subclass to provide us with // that information if (time <= MinSupportedDateTime.AddDays(dayOfYear)) { return GetWeekOfYearOfMinSupportedDateTime(firstDayOfWeek, fullDays); } return (GetWeekOfYearFullDays(time.AddDays(-(dayOfYear + 1)), firstDayOfWeek, fullDays)); } private int GetWeekOfYearOfMinSupportedDateTime(int firstDayOfWeek, int minimumDaysInFirstWeek) { int dayOfYear = GetDayOfYear(MinSupportedDateTime) - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfYear = (int)GetDayOfWeek(MinSupportedDateTime) - dayOfYear % 7; // Calculate the offset (how many days from the start of the year to the start of the week) int offset = (firstDayOfWeek + 7 - dayOfWeekOfFirstOfYear) % 7; if (offset == 0 || offset >= minimumDaysInFirstWeek) { // First of year falls in the first week of the year return 1; } int daysInYearBeforeMinSupportedYear = DaysInYearBeforeMinSupportedYear - 1; // Make the day of year to be 0-based, so that 1/1 is day 0. int dayOfWeekOfFirstOfPreviousYear = dayOfWeekOfFirstOfYear - 1 - (daysInYearBeforeMinSupportedYear % 7); // starting from first day of the year, how many days do you have to go forward // before getting to the first day of the week? int daysInInitialPartialWeek = (firstDayOfWeek - dayOfWeekOfFirstOfPreviousYear + 14) % 7; int day = daysInYearBeforeMinSupportedYear - daysInInitialPartialWeek; if (daysInInitialPartialWeek >= minimumDaysInFirstWeek) { // If the offset is greater than the minimum Days in the first week, it means that // First of year is part of the first week of the year even though it is only a partial week // add another week day += 7; } return (day / 7 + 1); } // it would be nice to make this abstract but we can't since that would break previous implementations protected virtual int DaysInYearBeforeMinSupportedYear { get { return 365; } } // Returns the week of year for the specified DateTime. The returned value is an // integer between 1 and 53. // public virtual int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { if ((int)firstDayOfWeek < 0 || (int)firstDayOfWeek > 6) { throw new ArgumentOutOfRangeException( nameof(firstDayOfWeek), SR.Format(SR.ArgumentOutOfRange_Range, DayOfWeek.Sunday, DayOfWeek.Saturday)); } Contract.EndContractBlock(); switch (rule) { case CalendarWeekRule.FirstDay: return (GetFirstDayWeekOfYear(time, (int)firstDayOfWeek)); case CalendarWeekRule.FirstFullWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 7)); case CalendarWeekRule.FirstFourDayWeek: return (GetWeekOfYearFullDays(time, (int)firstDayOfWeek, 4)); } throw new ArgumentOutOfRangeException( nameof(rule), SR.Format(SR.ArgumentOutOfRange_Range, CalendarWeekRule.FirstDay, CalendarWeekRule.FirstFourDayWeek)); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public abstract int GetYear(DateTime time); // Checks whether a given day in the current era is a leap day. This method returns true if // the date is a leap day, or false if not. // public virtual bool IsLeapDay(int year, int month, int day) { return (IsLeapDay(year, month, day, CurrentEra)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public abstract bool IsLeapDay(int year, int month, int day, int era); // Checks whether a given month in the current era is a leap month. This method returns true if // month is a leap month, or false if not. // public virtual bool IsLeapMonth(int year, int month) { return (IsLeapMonth(year, month, CurrentEra)); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public abstract bool IsLeapMonth(int year, int month, int era); // Returns the leap month in a calendar year of the current era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year) { return (GetLeapMonth(year, CurrentEra)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public virtual int GetLeapMonth(int year, int era) { if (!IsLeapYear(year, era)) return 0; int monthsCount = GetMonthsInYear(year, era); for (int month = 1; month <= monthsCount; month++) { if (IsLeapMonth(year, month, era)) return month; } return 0; } // Checks whether a given year in the current era is a leap year. This method returns true if // year is a leap year, or false if not. // public virtual bool IsLeapYear(int year) { return (IsLeapYear(year, CurrentEra)); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public abstract bool IsLeapYear(int year, int era); // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public virtual DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond) { return (ToDateTime(year, month, day, hour, minute, second, millisecond, CurrentEra)); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public abstract DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era); internal virtual Boolean TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { result = DateTime.MinValue; try { result = ToDateTime(year, month, day, hour, minute, second, millisecond, era); return true; } catch (ArgumentException) { return false; } } internal virtual bool IsValidYear(int year, int era) { return (year >= GetYear(MinSupportedDateTime) && year <= GetYear(MaxSupportedDateTime)); } internal virtual bool IsValidMonth(int year, int month, int era) { return (IsValidYear(year, era) && month >= 1 && month <= GetMonthsInYear(year, era)); } internal virtual bool IsValidDay(int year, int month, int day, int era) { return (IsValidMonth(year, month, era) && day >= 1 && day <= GetDaysInMonth(year, month, era)); } // Returns and assigns the maximum value to represent a two digit year. This // value is the upper boundary of a 100 year range that allows a two digit year // to be properly translated to a four digit year. For example, if 2029 is the // upper boundary, then a two digit value of 30 should be interpreted as 1930 // while a two digit value of 29 should be interpreted as 2029. In this example // , the 100 year range would be from 1930-2029. See ToFourDigitYear(). public virtual int TwoDigitYearMax { get { return (twoDigitYearMax); } set { VerifyWritable(); twoDigitYearMax = value; } } // Converts the year value to the appropriate century by using the // TwoDigitYearMax property. For example, if the TwoDigitYearMax value is 2029, // then a two digit value of 30 will get converted to 1930 while a two digit // value of 29 will get converted to 2029. public virtual int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return ((TwoDigitYearMax / 100 - (year > TwoDigitYearMax % 100 ? 1 : 0)) * 100 + year); } // If the year value is above 100, just return the year value. Don't have to do // the TwoDigitYearMax comparison. return (year); } // Return the tick count corresponding to the given hour, minute, second. // Will check the if the parameters are valid. internal static long TimeToTicks(int hour, int minute, int second, int millisecond) { if (hour >= 0 && hour < 24 && minute >= 0 && minute < 60 && second >= 0 && second < 60) { if (millisecond < 0 || millisecond >= MillisPerSecond) { throw new ArgumentOutOfRangeException( nameof(millisecond), String.Format( CultureInfo.InvariantCulture, SR.Format(SR.ArgumentOutOfRange_Range, 0, MillisPerSecond - 1))); } return InternalGlobalizationHelper.TimeToTicks(hour, minute, second) + millisecond * TicksPerMillisecond; } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadHourMinuteSecond); } internal static int GetSystemTwoDigitYearSetting(CalendarId CalID, int defaultYearValue) { // Call nativeGetTwoDigitYearMax int twoDigitYearMax = CalendarData.GetTwoDigitYearMax(CalID); if (twoDigitYearMax < 0) { twoDigitYearMax = defaultYearValue; } return (twoDigitYearMax); } } }
using System; using System.Data; using Codentia.Common.Data; using Codentia.Common.Logging.BL; using Codentia.Common.Membership.Test.Creator; using Codentia.Common.Membership.Test.Queries; using Codentia.Test.Generator; using Codentia.Test.Helper; using NUnit.Framework; namespace Codentia.Common.Membership.Test { /// <summary> /// TestFixture for WebAddressData /// <seealso cref="WebAddressData"/> /// </summary> [TestFixture] public class WebAddressDataTest { private int _webAddressIdExistant; private int _webAddressIdNonExistant; /// <summary> /// Ensure all set-up required for testing has been completed /// </summary> [TestFixtureSetUp] public void TestFixtureSetUp() { InternetDataCreator.CreateOnlyWebAddresses("membership", 30); _webAddressIdNonExistant = SqlHelper.GetUnusedIdFromTable("membership", "WebAddress"); _webAddressIdExistant = SqlHelper.GetRandomIdFromTable("membership", "WebAddress"); } /// <summary> /// Perform test clean-up activities /// </summary> [TestFixtureTearDown] public void TestFixtureTearDown() { LogManager.Instance.Dispose(); } /// <summary> /// Scenario: Attempt to call GetWebAddressTypes /// Expected: Table row count is greater than 0 /// </summary> [Test] public void _001_GetWebAddressTypes() { DataTable dt = WebAddressData.GetWebAddressTypes(); Assert.That(dt.Rows.Count, Is.GreaterThan(0), "DataTable should have 1 or more rows"); DataTable dt2 = DbInterface.ExecuteQueryDataTable("membership", WebAddressDataQueries.WebAddressType_Get_All); Assert.That(SqlHelper.CompareDataTables(dt, dt2), Is.True); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an empty Web address /// Expected: Web Address not specified Exception raised for null and empty strings /// Invalid Web address Exception raised for invalid Web address /// </summary> [Test] public void _002_WebAddressExists_Address_EmptyAddress() { // null Assert.That(delegate { WebAddressData.WebAddressExists(null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); // empty Assert.That(delegate { WebAddressData.WebAddressExists(string.Empty); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an existing address /// Expected: WebAddressExists returns true for check id 0, WebAddressExists returns false for check id _SystemUserIdForExistantWebAddress /// </summary> [Test] public void _003_WebAddressExists_Address_ExistingAddress() { string urlExistant = DbInterface.ExecuteQueryScalar<string>("membership", WebAddressDataQueries.URL_Get_Random); Assert.That(WebAddressData.WebAddressExists(urlExistant), Is.True, "Result should be true"); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an non-existant Web address /// Expected: WebAddressExists returns false /// </summary> [Test] public void _004_WebAddressExists_Address_NonExistantAddress() { Assert.That(WebAddressData.WebAddressExists("http:// www.THISISNOTANEXISTINGURL.COM"), Is.False, "Result should be false"); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an invalid Id /// Expected: Invalid Web Address Exception raised /// </summary> [Test] public void _005_WebAddressExists_Id_InvalidId() { // 0 Assert.That(delegate { WebAddressData.WebAddressExists(0); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: 0 is not valid")); // -1 Assert.That(delegate { WebAddressData.WebAddressExists(-1); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: -1 is not valid")); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an existing address /// Expected: WebAddressExists returns true for check id 0, WebAddressExists returns false for check id _SystemUserIdForExistantWebAddress /// </summary> [Test] public void _006_WebAddressExists_Id_ExistingAddress() { int webAddressExistant = SqlHelper.GetRandomIdFromTable("membership", "WebAddress"); Assert.That(WebAddressData.WebAddressExists(webAddressExistant), Is.True, "Result should be true"); } /// <summary> /// Scenario: Attempt to call WebAddressExists with an non-existant web address /// Expected: WebAddressExists returns false /// </summary> [Test] public void _007_WebAddressExists_Id_NonExistantAddress() { int webAddressNonExistant = SqlHelper.GetUnusedIdFromTable("membership", "WebAddress"); Assert.That(WebAddressData.WebAddressExists(webAddressNonExistant), Is.False, "Result should be false"); } /// <summary> /// Scenario: Attempt to call GetWebAddressData with an invalid Id /// Expected: Invalid Id Exception raised /// </summary> [Test] public void _008_GetWebAddressData_Id_InvalidId() { // 0 Assert.That(delegate { WebAddressData.GetWebAddressData(0); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: 0 is not valid")); // -1 Assert.That(delegate { WebAddressData.GetWebAddressData(-1); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: -1 is not valid")); // non-existant int webAddressIdNonExistant = SqlHelper.GetUnusedIdFromTable("membership", "WebAddress"); Assert.That(delegate { WebAddressData.GetWebAddressData(webAddressIdNonExistant); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo(string.Format("webAddressId: {0} does not exist", webAddressIdNonExistant))); } /// <summary> /// Scenario: Attempt to call GetWebAddressData with an existing Id /// Expected: WebAddress data returned /// </summary> [Test] public void _009_GetWebAddressData_Id_ExistingId() { DataTable dt = DbInterface.ExecuteQueryDataTable("membership", WebAddressDataQueries.WebAddressIdAndURL_Get_Random); int webAddressId = Convert.ToInt32(dt.Rows[0]["WebAddressId"]); string url = Convert.ToString(dt.Rows[0]["URL"]); DataTable dt2 = WebAddressData.GetWebAddressData(webAddressId); string urlCheck = Convert.ToString(dt2.Rows[0]["URL"]); Assert.That(url, Is.EqualTo(urlCheck), "URLs do not match"); } /// <summary> /// Scenario: Attempt to call UpdateWebAddressAsDead with an invalid id /// Expected: Exceptions raised /// </summary> [Test] public void _010_UpdateWebAddressAsDead_InvalidId() { // 0 Assert.That(delegate { WebAddressData.UpdateWebAddressAsDead(0); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: 0 is not valid")); // -1 Assert.That(delegate { WebAddressData.UpdateWebAddressAsDead(-1); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("webAddressId: -1 is not valid")); // non-existant int webAddressIdNonExistant = SqlHelper.GetUnusedIdFromTable("membership", "WebAddress"); Assert.That(delegate { WebAddressData.UpdateWebAddressAsDead(webAddressIdNonExistant); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo(string.Format("webAddressId: {0} does not exist", webAddressIdNonExistant))); } /// <summary> /// Scenario: Attempt to call UpdateWebAddressAsDead with an valid existing id /// Expected: Runs Successfully /// </summary> [Test] public void _011_UpdateWebAddressAsDead_ValidParam() { int webAddressId = DbInterface.ExecuteQueryScalar<int>("membership", WebAddressDataQueries.WebAddressId_Get_Random_Alive); WebAddressData.UpdateWebAddressAsDead(webAddressId); DataTable dt = WebAddressData.GetWebAddressData(webAddressId); Assert.That(dt.Rows.Count, Is.EqualTo(1)); bool isDead = Convert.ToBoolean(dt.Rows[0]["IsDead"]); // reset first DbInterface.ExecuteQueryNoReturn("membership", string.Format(WebAddressDataQueries.WebAddress_UpdateAsAlive, webAddressId)); Assert.That(isDead, Is.True); } /// <summary> /// Scenario: Attempt to call CreateWebAddress with an invalid url /// Expected: Exceptions raised /// </summary> [Test] public void _012_CreateWebAddress_InvalidURL() { // null Assert.That(delegate { WebAddressData.CreateWebAddress(null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); // empty Assert.That(delegate { WebAddressData.CreateWebAddress(string.Empty); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); // existing string urlExistant = DbInterface.ExecuteQueryScalar<string>("membership", WebAddressDataQueries.URL_Get_Random); Assert.That(delegate { WebAddressData.CreateWebAddress(urlExistant); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo(string.Format("url: {0} already exists", urlExistant))); } /// <summary> /// Scenario: Attempt to call CreateWebAddress with a valid url /// Expected: Runs Successfully /// </summary> [Test] public void _013_CreateWebAddress_ValidURL() { string domainType = DataGenerator.RetrieveRandomStringFromXmlDoc(InternetDataCreator.GetDomainType(), "domaintype"); string url = string.Format("http:// www.{0}.{1}", Guid.NewGuid().ToString().Replace("-", string.Empty), domainType); int webAddressId = WebAddressData.CreateWebAddress(url); DataTable dt = WebAddressData.GetWebAddressData(webAddressId); Assert.That(dt.Rows.Count, Is.EqualTo(1)); Assert.That(Convert.ToString(dt.Rows[0]["URL"]), Is.EqualTo(url)); Assert.That(Convert.ToBoolean(dt.Rows[0]["IsDead"]), Is.False); } /// <summary> /// Scenario: Check WebAddressType Enums both in class and in database /// Expected: Runs Successfully /// </summary> [Test] public void _014_WebAddressTypesCheck() { Assert.That((int)WebAddressType.None == 0, Is.True); Assert.That((int)WebAddressType.Blog == 1, Is.True); Assert.That((int)WebAddressType.Shop == 2, Is.True); DataTable dt = DbInterface.ExecuteQueryDataTable("membership", WebAddressDataQueries.WebAddressType_Get_All); string[] enums = Enum.GetNames(typeof(WebAddressType)); // take off the None option from expected count Assert.That(dt.Rows.Count, Is.EqualTo(enums.Length - 1), "Total count of enums does not match database"); for (int i = 0; i < dt.Rows.Count; i++) { DataRow dr = dt.Rows[i]; string code = Convert.ToString(dr["DisplayText"]); int id = Convert.ToInt32(dr["WebAddressTypeId"]); Assert.That(Enum.Format(typeof(WebAddressType), id, "F"), Is.EqualTo(code), string.Format("id for {0} incorrect", code)); } } /// <summary> /// Scenario: Attempt to call GetWebAddressData with an invalid url /// Expected: Raises exceptions /// </summary> [Test] public void _015_GetWebAddressData_String_InvalidURL() { // null Assert.That(delegate { WebAddressData.GetWebAddressData(null); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); // empty Assert.That(delegate { WebAddressData.GetWebAddressData(string.Empty); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url is not specified")); // exceeds max length Assert.That(delegate { WebAddressData.GetWebAddressData("http:// THISADDRESSWILLNOTEXIST.Com"); }, Throws.InstanceOf<ArgumentException>().With.Message.EqualTo("url: http:// THISADDRESSWILLNOTEXIST.Com does not exist")); } /// <summary> /// Scenario: Attempt to call GetWebAddressData with an existing Id /// Expected: WebAddress data returned /// </summary> [Test] public void _016_GetWebAddressData_String_ExistingId() { DataTable dt = DbInterface.ExecuteQueryDataTable("membership", WebAddressDataQueries.WebAddressIdAndURL_Get_Random); int webAddressId = Convert.ToInt32(dt.Rows[0]["WebAddressId"]); string url = Convert.ToString(dt.Rows[0]["URL"]); DataTable dt2 = WebAddressData.GetWebAddressData(url); string urlActual = Convert.ToString(dt2.Rows[0]["URL"]); int webAddressIdActual = Convert.ToInt32(dt.Rows[0]["WebAddressId"]); Assert.That(urlActual, Is.EqualTo(url), "URLs do not match"); Assert.That(webAddressIdActual, Is.EqualTo(webAddressId), "URLs do not match"); } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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.Runtime.InteropServices; using System.ComponentModel; namespace Duality { /// <summary> /// Represents a Quaternion. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Quaternion : IEquatable<Quaternion> { #region Fields Vector3 xyz; float w; #endregion #region Constructors /// <summary> /// Construct a new Quaternion from vector and w components /// </summary> /// <param name="v">The vector part</param> /// <param name="w">The w part</param> public Quaternion(Vector3 v, float w) { this.xyz = v; this.w = w; } /// <summary> /// Construct a new Quaternion /// </summary> /// <param name="x">The x component</param> /// <param name="y">The y component</param> /// <param name="z">The z component</param> /// <param name="w">The w component</param> public Quaternion(float x, float y, float z, float w) : this(new Vector3(x, y, z), w) { } #endregion #region Public Members #region Properties /// <summary> /// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance. /// </summary> public Vector3 Xyz { get { return xyz; } set { xyz = value; } } /// <summary> /// Gets or sets the X component of this instance. /// </summary> public float X { get { return xyz.X; } set { xyz.X = value; } } /// <summary> /// Gets or sets the Y component of this instance. /// </summary> public float Y { get { return xyz.Y; } set { xyz.Y = value; } } /// <summary> /// Gets or sets the Z component of this instance. /// </summary> public float Z { get { return xyz.Z; } set { xyz.Z = value; } } /// <summary> /// Gets or sets the W component of this instance. /// </summary> public float W { get { return w; } set { w = value; } } #endregion #region Instance #region ToAxisAngle /// <summary> /// Convert the current quaternion to axis angle representation /// </summary> /// <param name="axis">The resultant axis</param> /// <param name="angle">The resultant angle</param> public void ToAxisAngle(out Vector3 axis, out float angle) { Vector4 result = ToAxisAngle(); axis = result.Xyz; angle = result.W; } /// <summary> /// Convert this instance to an axis-angle representation. /// </summary> /// <returns>A Vector4 that is the axis-angle representation of this quaternion.</returns> public Vector4 ToAxisAngle() { Quaternion q = this; if (Math.Abs(q.W) > 1.0f) q.Normalize(); Vector4 result = new Vector4(); result.W = 2.0f * (float)System.Math.Acos(q.W); // angle float den = (float)System.Math.Sqrt(1.0 - q.W * q.W); if (den > 0.0001f) { result.Xyz = q.Xyz / den; } else { // This occurs when the angle is zero. // Not a problem: just set an arbitrary normalized axis. result.Xyz = Vector3.UnitX; } return result; } #endregion #region public float Length /// <summary> /// Gets the length (magnitude) of the quaternion. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt(W * W + Xyz.LengthSquared); } } #endregion #region public float LengthSquared /// <summary> /// Gets the square of the quaternion length (magnitude). /// </summary> public float LengthSquared { get { return W * W + Xyz.LengthSquared; } } #endregion /// <summary> /// Returns a copy of the Quaternion scaled to unit length. /// </summary> public Quaternion Normalized() { Quaternion q = this; q.Normalize(); return q; } /// <summary> /// Reverses the rotation angle of this Quaterniond. /// </summary> public void Invert() { W = -W; } /// <summary> /// Returns a copy of this Quaterniond with its rotation angle reversed. /// </summary> public Quaternion Inverted() { var q = this; q.Invert(); return q; } #region public void Normalize() /// <summary> /// Scales the Quaternion to unit length. /// </summary> public void Normalize() { float scale = 1.0f / this.Length; Xyz *= scale; W *= scale; } #endregion #region public void Conjugate() /// <summary> /// Inverts the Vector3 component of this Quaternion. /// </summary> public void Conjugate() { Xyz = -Xyz; } #endregion #endregion #region Static #region Fields /// <summary> /// Defines the identity quaternion. /// </summary> public static readonly Quaternion Identity = new Quaternion(0, 0, 0, 1); #endregion #region Add /// <summary> /// Add two quaternions /// </summary> /// <param name="left">The first operand</param> /// <param name="right">The second operand</param> /// <returns>The result of the addition</returns> public static Quaternion Add(Quaternion left, Quaternion right) { return new Quaternion( left.Xyz + right.Xyz, left.W + right.W); } /// <summary> /// Add two quaternions /// </summary> /// <param name="left">The first operand</param> /// <param name="right">The second operand</param> /// <param name="result">The result of the addition</param> public static void Add(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( left.Xyz + right.Xyz, left.W + right.W); } #endregion #region Sub /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <returns>The result of the operation.</returns> public static Quaternion Sub(Quaternion left, Quaternion right) { return new Quaternion( left.Xyz - right.Xyz, left.W - right.W); } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left instance.</param> /// <param name="right">The right instance.</param> /// <param name="result">The result of the operation.</param> public static void Sub(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( left.Xyz - right.Xyz, left.W - right.W); } #endregion #region Mult /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>A new instance containing the result of the calculation.</returns> [Obsolete("Use Multiply instead.")] public static Quaternion Mult(Quaternion left, Quaternion right) { return new Quaternion( right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz), left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz)); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <param name="result">A new instance containing the result of the calculation.</param> [Obsolete("Use Multiply instead.")] public static void Mult(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz), left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz)); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion Multiply(Quaternion left, Quaternion right) { Quaternion result; Multiply(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <param name="result">A new instance containing the result of the calculation.</param> public static void Multiply(ref Quaternion left, ref Quaternion right, out Quaternion result) { result = new Quaternion( right.W * left.Xyz + left.W * right.Xyz + Vector3.Cross(left.Xyz, right.Xyz), left.W * right.W - Vector3.Dot(left.Xyz, right.Xyz)); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <param name="result">A new instance containing the result of the calculation.</param> public static void Multiply(ref Quaternion quaternion, float scale, out Quaternion result) { result = new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion Multiply(Quaternion quaternion, float scale) { return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } #endregion #region Conjugate /// <summary> /// Get the conjugate of the given quaternion /// </summary> /// <param name="q">The quaternion</param> /// <returns>The conjugate of the given quaternion</returns> public static Quaternion Conjugate(Quaternion q) { return new Quaternion(-q.Xyz, q.W); } /// <summary> /// Get the conjugate of the given quaternion /// </summary> /// <param name="q">The quaternion</param> /// <param name="result">The conjugate of the given quaternion</param> public static void Conjugate(ref Quaternion q, out Quaternion result) { result = new Quaternion(-q.Xyz, q.W); } #endregion #region Invert /// <summary> /// Get the inverse of the given quaternion /// </summary> /// <param name="q">The quaternion to invert</param> /// <returns>The inverse of the given quaternion</returns> public static Quaternion Invert(Quaternion q) { Quaternion result; Invert(ref q, out result); return result; } /// <summary> /// Get the inverse of the given quaternion /// </summary> /// <param name="q">The quaternion to invert</param> /// <param name="result">The inverse of the given quaternion</param> public static void Invert(ref Quaternion q, out Quaternion result) { float lengthSq = q.LengthSquared; if (lengthSq != 0.0) { float i = 1.0f / lengthSq; result = new Quaternion(q.Xyz * -i, q.W * i); } else { result = q; } } #endregion #region Normalize /// <summary> /// Scale the given quaternion to unit length /// </summary> /// <param name="q">The quaternion to normalize</param> /// <returns>The normalized quaternion</returns> public static Quaternion Normalize(Quaternion q) { Quaternion result; Normalize(ref q, out result); return result; } /// <summary> /// Scale the given quaternion to unit length /// </summary> /// <param name="q">The quaternion to normalize</param> /// <param name="result">The normalized quaternion</param> public static void Normalize(ref Quaternion q, out Quaternion result) { float scale = 1.0f / q.Length; result = new Quaternion(q.Xyz * scale, q.W * scale); } #endregion #region FromAxisAngle /// <summary> /// Build a quaternion from the given axis and angle /// </summary> /// <param name="axis">The axis to rotate about</param> /// <param name="angle">The rotation angle in radians</param> /// <returns>The equivalent quaternion</returns> public static Quaternion FromAxisAngle(Vector3 axis, float angle) { if (axis.LengthSquared == 0.0f) return Identity; Quaternion result = Identity; angle *= 0.5f; axis.Normalize(); result.Xyz = axis * (float)System.Math.Sin(angle); result.W = (float)System.Math.Cos(angle); return Normalize(result); } #endregion #region FromMatrix /// <summary> /// Builds a quaternion from the given rotation matrix /// </summary> /// <param name="matrix">A rotation matrix</param> /// <returns>The equivalent quaternion</returns> public static Quaternion FromMatrix(Matrix3 matrix) { Quaternion result; FromMatrix(ref matrix, out result); return result; } /// <summary> /// Builds a quaternion from the given rotation matrix /// </summary> /// <param name="matrix">A rotation matrix</param> /// <param name="result">The equivalent quaternion</param> public static void FromMatrix(ref Matrix3 matrix, out Quaternion result) { float trace = matrix.Trace; if (trace > 0) { float s = (float)Math.Sqrt(trace + 1) * 2; float invS = 1f / s; result.w = s * 0.25f; result.xyz.X = (matrix.Row2.Y - matrix.Row1.Z) * invS; result.xyz.Y = (matrix.Row0.Z - matrix.Row2.X) * invS; result.xyz.Z = (matrix.Row1.X - matrix.Row0.Y) * invS; } else { float m00 = matrix.Row0.X, m11 = matrix.Row1.Y, m22 = matrix.Row2.Z; if (m00 > m11 && m00 > m22) { float s = (float)Math.Sqrt(1 + m00 - m11 - m22) * 2; float invS = 1f / s; result.w = (matrix.Row2.Y - matrix.Row1.Z) * invS; result.xyz.X = s * 0.25f; result.xyz.Y = (matrix.Row0.Y + matrix.Row1.X) * invS; result.xyz.Z = (matrix.Row0.Z + matrix.Row2.X) * invS; } else if (m11 > m22) { float s = (float)Math.Sqrt(1 + m11 - m00 - m22) * 2; float invS = 1f / s; result.w = (matrix.Row0.Z - matrix.Row2.X) * invS; result.xyz.X = (matrix.Row0.Y + matrix.Row1.X) * invS; result.xyz.Y = s * 0.25f; result.xyz.Z = (matrix.Row1.Z + matrix.Row2.Y) * invS; } else { float s = (float)Math.Sqrt(1 + m22 - m00 - m11) * 2; float invS = 1f / s; result.w = (matrix.Row1.X - matrix.Row0.Y) * invS; result.xyz.X = (matrix.Row0.Z + matrix.Row2.X) * invS; result.xyz.Y = (matrix.Row1.Z + matrix.Row2.Y) * invS; result.xyz.Z = s * 0.25f; } } } #endregion #region Slerp /// <summary> /// Do Spherical linear interpolation between two quaternions /// </summary> /// <param name="q1">The first quaternion</param> /// <param name="q2">The second quaternion</param> /// <param name="blend">The blend factor</param> /// <returns>A smooth blend between the given quaternions</returns> public static Quaternion Slerp(Quaternion q1, Quaternion q2, float blend) { // if either input is zero, return the other. if (q1.LengthSquared == 0.0f) { if (q2.LengthSquared == 0.0f) { return Identity; } return q2; } else if (q2.LengthSquared == 0.0f) { return q1; } float cosHalfAngle = q1.W * q2.W + Vector3.Dot(q1.Xyz, q2.Xyz); if (cosHalfAngle >= 1.0f || cosHalfAngle <= -1.0f) { // angle = 0.0f, so just return one input. return q1; } else if (cosHalfAngle < 0.0f) { q2.Xyz = -q2.Xyz; q2.W = -q2.W; cosHalfAngle = -cosHalfAngle; } float blendA; float blendB; if (cosHalfAngle < 0.99f) { // do proper slerp for big angles float halfAngle = (float)System.Math.Acos(cosHalfAngle); float sinHalfAngle = (float)System.Math.Sin(halfAngle); float oneOverSinHalfAngle = 1.0f / sinHalfAngle; blendA = (float)System.Math.Sin(halfAngle * (1.0f - blend)) * oneOverSinHalfAngle; blendB = (float)System.Math.Sin(halfAngle * blend) * oneOverSinHalfAngle; } else { // do lerp if angle is really small. blendA = 1.0f - blend; blendB = blend; } Quaternion result = new Quaternion(blendA * q1.Xyz + blendB * q2.Xyz, blendA * q1.W + blendB * q2.W); if (result.LengthSquared > 0.0f) return Normalize(result); else return Identity; } #endregion #endregion #region Operators /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator +(Quaternion left, Quaternion right) { left.Xyz += right.Xyz; left.W += right.W; return left; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator -(Quaternion left, Quaternion right) { left.Xyz -= right.Xyz; left.W -= right.W; return left; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Quaternion operator *(Quaternion left, Quaternion right) { Multiply(ref left, ref right, out left); return left; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion operator *(Quaternion quaternion, float scale) { Multiply(ref quaternion, scale, out quaternion); return quaternion; } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="quaternion">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>A new instance containing the result of the calculation.</returns> public static Quaternion operator *(float scale, Quaternion quaternion) { return new Quaternion(quaternion.X * scale, quaternion.Y * scale, quaternion.Z * scale, quaternion.W * scale); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Quaternion left, Quaternion right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Quaternion left, Quaternion right) { return !left.Equals(right); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Quaternion. /// </summary> /// <returns></returns> public override string ToString() { return String.Format("V: {0}, W: {1}", Xyz, W); } #endregion #region public override bool Equals (object o) /// <summary> /// Compares this object instance to another object for equality. /// </summary> /// <param name="other">The other object to be used in the comparison.</param> /// <returns>True if both objects are Quaternions of equal value. Otherwise it returns false.</returns> public override bool Equals(object other) { if (other is Quaternion == false) return false; return this == (Quaternion)other; } #endregion #region public override int GetHashCode () /// <summary> /// Provides the hash code for this object. /// </summary> /// <returns>A hash code formed from the bitwise XOR of this objects members.</returns> public override int GetHashCode() { return Xyz.GetHashCode() ^ W.GetHashCode(); } #endregion #endregion #endregion #region IEquatable<Quaternion> Members /// <summary> /// Compares this Quaternion instance to another Quaternion for equality. /// </summary> /// <param name="other">The other Quaternion to be used in the comparison.</param> /// <returns>True if both instances are equal; false otherwise.</returns> public bool Equals(Quaternion other) { return Xyz == other.Xyz && W == other.W; } #endregion } }
//----------------------------------------------------------------------- // <copyright file="ModelClass" company="LoginRadius"> // Created by LoginRadius Development Team // Copyright 2019 LoginRadius Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------- using System.Collections.Generic; using Newtonsoft.Json; namespace LoginRadiusSDK.V2.Models.RequestModels { /// <summary> /// Model Class containing Definition of payload for Auth User Registration API /// </summary> public class AuthUserRegistrationModel { /// <summary> /// About value that need to be inserted /// </summary> [JsonProperty(PropertyName = "About")] public string About {get;set;} /// <summary> /// caption to accept the privacy policy /// </summary> [JsonProperty(PropertyName = "AcceptPrivacyPolicy")] public bool? AcceptPrivacyPolicy {get;set;} /// <summary> /// Array of objects,String represents address of user /// </summary> [JsonProperty(PropertyName = "Addresses")] public List<Address> Addresses {get;set;} /// <summary> /// User's Age /// </summary> [JsonProperty(PropertyName = "Age")] public string Age {get;set;} /// <summary> /// user's age range. /// </summary> [JsonProperty(PropertyName = "AgeRange")] public AgeRange AgeRange {get;set;} /// <summary> /// Organization a person is assosciated with /// </summary> [JsonProperty(PropertyName = "Associations")] public string Associations {get;set;} /// <summary> /// Array of Objects,String represents Id, Name and Issuer /// </summary> [JsonProperty(PropertyName = "Awards")] public List<Awards> Awards {get;set;} /// <summary> /// User's Badges. /// </summary> [JsonProperty(PropertyName = "Badges")] public List<Badges> Badges {get;set;} /// <summary> /// user's birthdate /// </summary> [JsonProperty(PropertyName = "BirthDate")] public string BirthDate {get;set;} /// <summary> /// Array of Objects,String represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Books")] public List<Books> Books {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Authority Number,StartDate,EndDate /// </summary> [JsonProperty(PropertyName = "Certifications")] public List<Certifications> Certifications {get;set;} /// <summary> /// user's city /// </summary> [JsonProperty(PropertyName = "City")] public string City {get;set;} /// <summary> /// users company name /// </summary> [JsonProperty(PropertyName = "Company")] public string Company {get;set;} /// <summary> /// List of Consents /// </summary> [JsonProperty(PropertyName = "Consents")] public ConsentSubmitModel Consents {get;set;} /// <summary> /// Country of the user /// </summary> [JsonProperty(PropertyName = "Country")] public Country Country {get;set;} /// <summary> /// users course information /// </summary> [JsonProperty(PropertyName = "Courses")] public List<Courses> Courses {get;set;} /// <summary> /// URL of the photo that need to be inserted /// </summary> [JsonProperty(PropertyName = "CoverPhoto")] public string CoverPhoto {get;set;} /// <summary> /// Currency /// </summary> [JsonProperty(PropertyName = "Currency")] public string Currency {get;set;} /// <summary> /// Array of Objects,String represents id ,Text ,Source and CreatedDate /// </summary> [JsonProperty(PropertyName = "CurrentStatus")] public List<CurrentStatus> CurrentStatus {get;set;} /// <summary> /// Custom fields as user set on LoginRadius Admin Console. /// </summary> [JsonProperty(PropertyName = "CustomFields")] public Dictionary<string,string> CustomFields {get;set;} /// <summary> /// Array of Objects,which represents the educations record /// </summary> [JsonProperty(PropertyName = "Educations")] public List<Education> Educations {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "Email")] public List<EmailModel> Email {get;set;} /// <summary> /// External User Login Id /// </summary> [JsonProperty(PropertyName = "ExternalUserLoginId")] public string ExternalUserLoginId {get;set;} /// <summary> /// user's family /// </summary> [JsonProperty(PropertyName = "Family")] public List<Family> Family {get;set;} /// <summary> /// URL of the favicon that need to be inserted /// </summary> [JsonProperty(PropertyName = "Favicon")] public string Favicon {get;set;} /// <summary> /// Array of Objects,strings represents Id ,Name ,Type /// </summary> [JsonProperty(PropertyName = "FavoriteThings")] public List<FavoriteThings> FavoriteThings {get;set;} /// <summary> /// user's first name /// </summary> [JsonProperty(PropertyName = "FirstName")] public string FirstName {get;set;} /// <summary> /// user's followers count /// </summary> [JsonProperty(PropertyName = "FollowersCount")] public int? FollowersCount {get;set;} /// <summary> /// users friends count /// </summary> [JsonProperty(PropertyName = "FriendsCount")] public int? FriendsCount {get;set;} /// <summary> /// Users complete name /// </summary> [JsonProperty(PropertyName = "FullName")] public string FullName {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Games")] public List<Games> Games {get;set;} /// <summary> /// user's gender /// </summary> [JsonProperty(PropertyName = "Gender")] public string Gender {get;set;} /// <summary> /// /// </summary> [JsonProperty(PropertyName = "GistsUrl")] public string GistsUrl {get;set;} /// <summary> /// URL of image that need to be inserted /// </summary> [JsonProperty(PropertyName = "GravatarImageUrl")] public string GravatarImageUrl {get;set;} /// <summary> /// boolean type value, default value is true /// </summary> [JsonProperty(PropertyName = "Hireable")] public bool? Hireable {get;set;} /// <summary> /// user's home town name /// </summary> [JsonProperty(PropertyName = "HomeTown")] public string HomeTown {get;set;} /// <summary> /// Awards lists from the social provider /// </summary> [JsonProperty(PropertyName = "Honors")] public string Honors {get;set;} /// <summary> /// URL of the Image that need to be inserted /// </summary> [JsonProperty(PropertyName = "HttpsImageUrl")] public string HttpsImageUrl {get;set;} /// <summary> /// Array of objects, String represents account type and account name. /// </summary> [JsonProperty(PropertyName = "IMAccounts")] public List<IMAccount> IMAccounts {get;set;} /// <summary> /// image URL should be absolute and has HTTPS domain /// </summary> [JsonProperty(PropertyName = "ImageUrl")] public string ImageUrl {get;set;} /// <summary> /// Industry name /// </summary> [JsonProperty(PropertyName = "Industry")] public string Industry {get;set;} /// <summary> /// Array of Objects,string represents Id and Name /// </summary> [JsonProperty(PropertyName = "InspirationalPeople")] public List<InspirationalPeople> InspirationalPeople {get;set;} /// <summary> /// array of string represents interest /// </summary> [JsonProperty(PropertyName = "InterestedIn")] public List<string> InterestedIn {get;set;} /// <summary> /// Array of objects, string shows InterestedType and InterestedName /// </summary> [JsonProperty(PropertyName = "Interests")] public List<Interests> Interests {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "IsEmailSubscribed")] public bool? IsEmailSubscribed {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "IsGeoEnabled")] public string IsGeoEnabled {get;set;} /// <summary> /// boolean type value, default is true /// </summary> [JsonProperty(PropertyName = "IsProtected")] public bool? IsProtected {get;set;} /// <summary> /// boolean type value, true if MFA enables otherwise false /// </summary> [JsonProperty(PropertyName = "IsTwoFactorAuthenticationEnabled")] public bool? IsTwoFactorAuthenticationEnabled {get;set;} /// <summary> /// Array of Objects,Strings,boolean,object represents IsApplied,ApplyTimestamp,IsSaved,SavedTimestamp,Job /// </summary> [JsonProperty(PropertyName = "JobBookmarks")] public List<JobBookmarks> JobBookmarks {get;set;} /// <summary> /// language known by user's /// </summary> [JsonProperty(PropertyName = "Languages")] public List<Languages> Languages {get;set;} /// <summary> /// user's last name /// </summary> [JsonProperty(PropertyName = "LastName")] public string LastName {get;set;} /// <summary> /// Local City of the user /// </summary> [JsonProperty(PropertyName = "LocalCity")] public string LocalCity {get;set;} /// <summary> /// Local country of the user /// </summary> [JsonProperty(PropertyName = "LocalCountry")] public string LocalCountry {get;set;} /// <summary> /// Local language of the user /// </summary> [JsonProperty(PropertyName = "LocalLanguage")] public string LocalLanguage {get;set;} /// <summary> /// Main address of the user /// </summary> [JsonProperty(PropertyName = "MainAddress")] public string MainAddress {get;set;} /// <summary> /// Array of Objects,String represents Url,UrlName /// </summary> [JsonProperty(PropertyName = "MemberUrlResources")] public List<Memberurlresources> MemberUrlResources {get;set;} /// <summary> /// user's middle name /// </summary> [JsonProperty(PropertyName = "MiddleName")] public string MiddleName {get;set;} /// <summary> /// Array of Objects,strings represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "Movies")] public List<Movies> Movies {get;set;} /// <summary> /// Array of Objects, strings represents Id,Name,FirstName,LastName,Birthday,Hometown,Link,Gender /// </summary> [JsonProperty(PropertyName = "MutualFriends")] public List<MutualFriends> MutualFriends {get;set;} /// <summary> /// Nick name of the user /// </summary> [JsonProperty(PropertyName = "NickName")] public string NickName {get;set;} /// <summary> /// Count for the user profile recommended /// </summary> [JsonProperty(PropertyName = "NumRecommenders")] public int? NumRecommenders {get;set;} /// <summary> /// Password for the email /// </summary> [JsonProperty(PropertyName = "Password")] public string Password {get;set;} /// <summary> /// Patents Registered /// </summary> [JsonProperty(PropertyName = "Patents")] public List<Patents> Patents {get;set;} /// <summary> /// Phone ID (Unique Phone Number Identifier of the user) /// </summary> [JsonProperty(PropertyName = "PhoneId")] public string PhoneId {get;set;} /// <summary> /// Users Phone Number /// </summary> [JsonProperty(PropertyName = "PhoneNumbers")] public List<Phone> PhoneNumbers {get;set;} /// <summary> /// PIN Info /// </summary> [JsonProperty(PropertyName = "PINInfo")] public PINModel PINInfo {get;set;} /// <summary> /// Array of Objects,strings Name and boolean IsPrimary /// </summary> [JsonProperty(PropertyName = "PlacesLived")] public List<PlacesLived> PlacesLived {get;set;} /// <summary> /// List of Political interest /// </summary> [JsonProperty(PropertyName = "Political")] public string Political {get;set;} /// <summary> /// Array of Objects,which represents the PositionSummary,StartDate,EndDate,IsCurrent,Company,Location /// </summary> [JsonProperty(PropertyName = "Positions")] public List<ProfessionalPosition> Positions {get;set;} /// <summary> /// Prefix for FirstName /// </summary> [JsonProperty(PropertyName = "Prefix")] public string Prefix {get;set;} /// <summary> /// user private Repository Urls /// </summary> [JsonProperty(PropertyName = "PrivateGists")] public int? PrivateGists {get;set;} /// <summary> /// This field provide by linkedin.contain our linkedin profile headline /// </summary> [JsonProperty(PropertyName = "ProfessionalHeadline")] public string ProfessionalHeadline {get;set;} /// <summary> /// ProfileCity value that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileCity")] public string ProfileCity {get;set;} /// <summary> /// ProfileCountry value that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileCountry")] public string ProfileCountry {get;set;} /// <summary> /// ProfileImageUrls that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileImageUrls")] public Dictionary<string,string> ProfileImageUrls {get;set;} /// <summary> /// ProfileName value field that need to be inserted /// </summary> [JsonProperty(PropertyName = "ProfileName")] public string ProfileName {get;set;} /// <summary> /// User profile url like facebook profile Url /// </summary> [JsonProperty(PropertyName = "ProfileUrl")] public string ProfileUrl {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Summary With StartDate,EndDate,IsCurrent /// </summary> [JsonProperty(PropertyName = "Projects")] public List<Projects> Projects {get;set;} /// <summary> /// Object,string represents AccessToken,TokenSecret /// </summary> [JsonProperty(PropertyName = "ProviderAccessCredential")] public ProviderAccessCredential ProviderAccessCredential {get;set;} /// <summary> /// Array of Objects,string represents Id,Title,Publisher,Authors,Date,Url,Summary /// </summary> [JsonProperty(PropertyName = "Publications")] public List<Publications> Publications {get;set;} /// <summary> /// gist is a Git repository, which means that it can be forked and cloned. /// </summary> [JsonProperty(PropertyName = "PublicGists")] public int? PublicGists {get;set;} /// <summary> /// user public Repository Urls /// </summary> [JsonProperty(PropertyName = "PublicRepository")] public string PublicRepository {get;set;} /// <summary> /// Quota /// </summary> [JsonProperty(PropertyName = "Quota")] public string Quota {get;set;} /// <summary> /// Array of Objects,string represents Id,RecommendationType,RecommendationText,Recommender /// </summary> [JsonProperty(PropertyName = "RecommendationsReceived")] public List<RecommendationsReceived> RecommendationsReceived {get;set;} /// <summary> /// Array of Objects,String represents Id,FirstName,LastName /// </summary> [JsonProperty(PropertyName = "RelatedProfileViews")] public List<RelatedProfileViews> RelatedProfileViews {get;set;} /// <summary> /// user's relationship status /// </summary> [JsonProperty(PropertyName = "RelationshipStatus")] public string RelationshipStatus {get;set;} /// <summary> /// String shows users religion /// </summary> [JsonProperty(PropertyName = "Religion")] public string Religion {get;set;} /// <summary> /// Repository URL /// </summary> [JsonProperty(PropertyName = "RepositoryUrl")] public string RepositoryUrl {get;set;} /// <summary> /// Valid JSON object of Unique Security Question ID and Answer of set Security Question /// </summary> [JsonProperty(PropertyName = "SecurityQuestionAnswer")] public Dictionary<string,string> SecurityQuestionAnswer {get;set;} /// <summary> /// Array of objects, String represents ID and Name /// </summary> [JsonProperty(PropertyName = "Skills")] public List<Skills> Skills {get;set;} /// <summary> /// Array of objects, String represents ID and Name /// </summary> [JsonProperty(PropertyName = "Sports")] public List<Sports> Sports {get;set;} /// <summary> /// Git users bookmark repositories /// </summary> [JsonProperty(PropertyName = "StarredUrl")] public string StarredUrl {get;set;} /// <summary> /// State of the user /// </summary> [JsonProperty(PropertyName = "State")] public string State {get;set;} /// <summary> /// Object,string represents Name,Space,PrivateRepos,Collaborators /// </summary> [JsonProperty(PropertyName = "Subscription")] public GitHubPlan Subscription {get;set;} /// <summary> /// Suffix for the User. /// </summary> [JsonProperty(PropertyName = "Suffix")] public string Suffix {get;set;} /// <summary> /// Object,array of objects represents CompaniestoFollow,IndustriestoFollow,NewssourcetoFollow,PeopletoFollow /// </summary> [JsonProperty(PropertyName = "Suggestions")] public Suggestions Suggestions {get;set;} /// <summary> /// Tagline that need to be inserted /// </summary> [JsonProperty(PropertyName = "TagLine")] public string TagLine {get;set;} /// <summary> /// Array of Objects,string represents Id,Name,Category,CreatedDate /// </summary> [JsonProperty(PropertyName = "TeleVisionShow")] public List<Television> TeleVisionShow {get;set;} /// <summary> /// URL for the Thumbnail /// </summary> [JsonProperty(PropertyName = "ThumbnailImageUrl")] public string ThumbnailImageUrl {get;set;} /// <summary> /// The Current Time Zone. /// </summary> [JsonProperty(PropertyName = "TimeZone")] public string TimeZone {get;set;} /// <summary> /// Total Private repository /// </summary> [JsonProperty(PropertyName = "TotalPrivateRepository")] public int? TotalPrivateRepository {get;set;} /// <summary> /// Count of Total status /// </summary> [JsonProperty(PropertyName = "TotalStatusesCount")] public int? TotalStatusesCount {get;set;} /// <summary> /// UID, the unified identifier for each user account /// </summary> [JsonProperty(PropertyName = "Uid")] public string Uid {get;set;} /// <summary> /// Username of the user /// </summary> [JsonProperty(PropertyName = "UserName")] public string UserName {get;set;} /// <summary> /// Array of Objects,string represents Id,Role,Organization,Cause /// </summary> [JsonProperty(PropertyName = "Volunteer")] public List<Volunteer> Volunteer {get;set;} /// <summary> /// Twitter, Facebook ProfileUrls /// </summary> [JsonProperty(PropertyName = "WebProfiles")] public Dictionary<string,string> WebProfiles {get;set;} /// <summary> /// Personal Website a User has /// </summary> [JsonProperty(PropertyName = "Website")] public string Website {get;set;} } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using DeOps.Services; using DeOps.Services.Location; using DeOps.Implementation.Dht; using DeOps.Implementation.Protocol.Net; namespace DeOps.Implementation.Transport { public delegate void SessionUpdateHandler(RudpSession session); public delegate void SessionDataHandler(RudpSession session, byte[] data); public delegate void KeepActiveHandler(Dictionary<ulong, bool> active); public class RudpHandler { // maintain connections to those needed by components (timer) // keep up to date with location changes / additions (locationdata index) // notify components on connection changes (event) // remove connections when components no longer interested in node (timer) public DhtNetwork Network; public Dictionary<ulong, RudpSession> SessionMap = new Dictionary<ulong, RudpSession>(); public Dictionary<ushort, RudpSocket> SocketMap = new Dictionary<ushort, RudpSocket>(); public SessionUpdateHandler SessionUpdate; public ServiceEvent<SessionDataHandler> SessionData = new ServiceEvent<SessionDataHandler>(); public KeepActiveHandler KeepActive; public RudpHandler(DhtNetwork network) { Network = network; } public void SecondTimer() { foreach (RudpSession session in SessionMap.Values) session.SecondTimer(); foreach (RudpSession session in SessionMap.Values.Where(s => s.Comm.State == RudpState.Closed).ToArray()) RemoveSession(session); // every 10 secs check for sessions no longer in use if (Network.Core.TimeNow.Second % 10 != 0) return; Dictionary<ulong, bool> active = new Dictionary<ulong, bool>(); if (KeepActive != null) foreach (KeepActiveHandler handler in KeepActive.GetInvocationList()) handler.Invoke(active); foreach (RudpSession session in SessionMap.Values) if (session.Status == SessionStatus.Active) if (active.ContainsKey(session.UserID)) session.Lingering = 0; else if (session.Lingering > 1) // ~10 secs to linger session.Send_Close("Not Active"); else session.Lingering++; } public void RemoveSession(RudpSession session) { lock (SocketMap) if (SocketMap.ContainsKey(session.Comm.PeerID)) SocketMap.Remove(session.Comm.PeerID); SessionMap.Remove(session.RoutingID); } public bool Connect(DhtClient client) { if (client.UserID == Network.Local.UserID && client.ClientID == Network.Local.ClientID) return false; // sessionmap and socketmap both need to have the same # of entries // if a session is fin or closed, we need to wait for fins to complete before re-assigning entry if(SessionMap.ContainsKey(client.RoutingID)) return SessionMap[client.RoutingID].Status != SessionStatus.Closed; RudpSession session = new RudpSession(this, client.UserID, client.ClientID, false); SessionMap[client.RoutingID] = session; if (Network.LightComm.Clients.ContainsKey(client.RoutingID)) foreach (RudpAddress address in Network.LightComm.Clients[client.RoutingID].Addresses) session.Comm.AddAddress(address); session.Connect(); return true; // indicates that we will eventually notify caller with close, so caller can clean up } public bool Connect(LocationData location) { if (location.UserID == Network.Local.UserID && location.Source.ClientID == Network.Local.ClientID) return false; ulong id = location.UserID ^ location.Source.ClientID; if (SessionMap.ContainsKey(id)) return SessionMap[id].Status != SessionStatus.Closed; RudpSession session = new RudpSession(this, location.UserID, location.Source.ClientID, false); SessionMap[id] = session; session.Comm.AddAddress(new RudpAddress(new DhtAddress(location.IP, location.Source))); foreach (DhtAddress address in location.Proxies) session.Comm.AddAddress(new RudpAddress(address)); foreach (DhtAddress server in location.TunnelServers) session.Comm.AddAddress(new RudpAddress(new DhtContact(location.Source, location.IP, location.TunnelClient, server))); session.Connect(); return true; } public List<RudpSession> GetActiveSessions(ulong key) { return (from session in SessionMap.Values where session.Status == SessionStatus.Active && session.UserID == key select session).ToList(); } public RudpSession GetActiveSession(DhtClient client) { return GetActiveSession(client.UserID, client.ClientID); } public RudpSession GetActiveSession(ulong key, ushort client) { return (from session in SessionMap.Values where session.Status == SessionStatus.Active && session.UserID == key && session.ClientID == client select session).FirstOrDefault(); } public bool IsConnectingOrActive(ulong key, ushort client) { int notClosed = (from session in SessionMap.Values where session.Status != SessionStatus.Closed && session.UserID == key && session.ClientID == client select session).Count(); return (notClosed > 0); } public bool IsConnected(ulong id) { int active = (from session in SessionMap.Values where session.Status == SessionStatus.Active && session.UserID == id select session).Count(); return (active > 0); } public void AnnounceProxy(TcpConnect tcp) { Debug.Assert(!Network.IsLookup); // function run bewteen cores if (Network.Core.InvokeRequired) { Network.Core.RunInCoreAsync(delegate() { AnnounceProxy(tcp); }); return; } foreach (RudpSession session in SessionMap.Values) if (session.Status == SessionStatus.Active) session.Send_ProxyUpdate(tcp); } public void Shutdown() { foreach (RudpSession session in SessionMap.Values) if (session.Status != SessionStatus.Closed) session.Send_Close("Going Offline"); } } public class ActiveSessions { List<ulong> AllSessions = new List<ulong>(); Dictionary<ulong, List<ushort>> Sessions = new Dictionary<ulong, List<ushort>>(); public ActiveSessions() { } public void Add(RudpSession rudp) { Add(rudp.UserID, rudp.ClientID); } public void Add(ulong key, ushort id) { if (!Sessions.ContainsKey(key)) Sessions[key] = new List<ushort>(); if (!Sessions[key].Contains(id)) Sessions[key].Add(id); } public void Add(ulong key) { if (AllSessions.Contains(key)) return; AllSessions.Add(key); } public bool Contains(RudpSession rudp) { if (AllSessions.Contains(rudp.UserID)) return true; if (!Sessions.ContainsKey(rudp.UserID)) return false; if (Sessions[rudp.UserID].Contains(rudp.ClientID)) return true; return false; } } }
namespace Cards { partial class Main { /// <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) { card.Dispose(); if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Main)); this.gameStatusBar = new System.Windows.Forms.StatusStrip(); this.gameStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.gameRoundStatusLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.gameToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.displayScoreToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.playerNamesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deckToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.animationSpeedToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fastToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mediumToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.slowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.guiUpdatebackgroundWorker = new System.ComponentModel.BackgroundWorker(); this.gameStatusBar.SuspendLayout(); this.menuStrip1.SuspendLayout(); this.SuspendLayout(); // // gameStatusBar // this.gameStatusBar.BackColor = System.Drawing.SystemColors.ActiveBorder; this.gameStatusBar.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.gameStatusBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.gameStatusLabel, this.gameRoundStatusLabel}); this.gameStatusBar.Location = new System.Drawing.Point(0, 455); this.gameStatusBar.Name = "gameStatusBar"; this.gameStatusBar.RenderMode = System.Windows.Forms.ToolStripRenderMode.Professional; this.gameStatusBar.Size = new System.Drawing.Size(581, 22); this.gameStatusBar.TabIndex = 0; this.gameStatusBar.Text = "statusStrip1"; // // gameStatusLabel // this.gameStatusLabel.Name = "gameStatusLabel"; this.gameStatusLabel.Size = new System.Drawing.Size(158, 17); this.gameStatusLabel.Text = "Select New to start the game"; // // gameRoundStatusLabel // this.gameRoundStatusLabel.Margin = new System.Windows.Forms.Padding(350, 3, 0, 2); this.gameRoundStatusLabel.Name = "gameRoundStatusLabel"; this.gameRoundStatusLabel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.gameRoundStatusLabel.Size = new System.Drawing.Size(0, 17); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.gameToolStripMenuItem, this.optionToolStripMenuItem, this.aboutToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(581, 24); this.menuStrip1.TabIndex = 1; this.menuStrip1.Text = "menuStrip1"; // // gameToolStripMenuItem // this.gameToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripMenuItem, this.displayScoreToolStripMenuItem, this.exitToolStripMenuItem}); this.gameToolStripMenuItem.Name = "gameToolStripMenuItem"; this.gameToolStripMenuItem.Size = new System.Drawing.Size(50, 20); this.gameToolStripMenuItem.Text = "&Game"; // // newToolStripMenuItem // this.newToolStripMenuItem.Name = "newToolStripMenuItem"; this.newToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.newToolStripMenuItem.Text = "&New"; this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click); // // displayScoreToolStripMenuItem // this.displayScoreToolStripMenuItem.Name = "displayScoreToolStripMenuItem"; this.displayScoreToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.displayScoreToolStripMenuItem.Text = "Display Score"; this.displayScoreToolStripMenuItem.Click += new System.EventHandler(this.displayScoreToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.exitToolStripMenuItem.Text = "&Exit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // optionToolStripMenuItem // this.optionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.playerNamesToolStripMenuItem, this.deckToolStripMenuItem, this.animationSpeedToolStripMenuItem}); this.optionToolStripMenuItem.Name = "optionToolStripMenuItem"; this.optionToolStripMenuItem.Size = new System.Drawing.Size(56, 20); this.optionToolStripMenuItem.Text = "&Option"; // // playerNamesToolStripMenuItem // this.playerNamesToolStripMenuItem.Name = "playerNamesToolStripMenuItem"; this.playerNamesToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.playerNamesToolStripMenuItem.Text = "&Player Names"; this.playerNamesToolStripMenuItem.Click += new System.EventHandler(this.playerNamesToolStripMenuItem_Click); // // deckToolStripMenuItem // this.deckToolStripMenuItem.Name = "deckToolStripMenuItem"; this.deckToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.deckToolStripMenuItem.Text = "&Deck"; this.deckToolStripMenuItem.Click += new System.EventHandler(this.deckToolStripMenuItem_Click); // // animationSpeedToolStripMenuItem // this.animationSpeedToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fastToolStripMenuItem, this.mediumToolStripMenuItem, this.slowToolStripMenuItem}); this.animationSpeedToolStripMenuItem.Name = "animationSpeedToolStripMenuItem"; this.animationSpeedToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.animationSpeedToolStripMenuItem.Text = "Animation Speed"; // // fastToolStripMenuItem // this.fastToolStripMenuItem.Name = "fastToolStripMenuItem"; this.fastToolStripMenuItem.Size = new System.Drawing.Size(119, 22); this.fastToolStripMenuItem.Text = "Fast"; this.fastToolStripMenuItem.Click += new System.EventHandler(this.fastToolStripMenuItem_Click); // // mediumToolStripMenuItem // this.mediumToolStripMenuItem.Checked = true; this.mediumToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.mediumToolStripMenuItem.Name = "mediumToolStripMenuItem"; this.mediumToolStripMenuItem.Size = new System.Drawing.Size(119, 22); this.mediumToolStripMenuItem.Text = "Medium"; this.mediumToolStripMenuItem.Click += new System.EventHandler(this.mediumToolStripMenuItem_Click); // // slowToolStripMenuItem // this.slowToolStripMenuItem.Name = "slowToolStripMenuItem"; this.slowToolStripMenuItem.Size = new System.Drawing.Size(119, 22); this.slowToolStripMenuItem.Text = "Slow"; this.slowToolStripMenuItem.Click += new System.EventHandler(this.slowToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(52, 20); this.aboutToolStripMenuItem.Text = "About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // Main // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoValidate = System.Windows.Forms.AutoValidate.Disable; this.BackColor = System.Drawing.Color.Green; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.CausesValidation = false; this.ClientSize = new System.Drawing.Size(581, 477); this.Controls.Add(this.gameStatusBar); this.Controls.Add(this.menuStrip1); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = System.Windows.Forms.ImeMode.Disable; this.MainMenuStrip = this.menuStrip1; this.MaximizeBox = false; this.Name = "Main"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Call Break"; this.Load += new System.EventHandler(this.Main_Load); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.Main_KeyDown); this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.Main_MouseClick); this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.Main_MouseDoubleClick); this.gameStatusBar.ResumeLayout(false); this.gameStatusBar.PerformLayout(); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public System.Windows.Forms.MenuStrip menuStrip1; public System.Windows.Forms.ToolStripMenuItem gameToolStripMenuItem; public System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem; public System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; public System.Windows.Forms.StatusStrip gameStatusBar; public System.Windows.Forms.ToolStripStatusLabel gameStatusLabel; private System.Windows.Forms.ToolStripMenuItem displayScoreToolStripMenuItem; public System.Windows.Forms.ToolStripStatusLabel gameRoundStatusLabel; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem playerNamesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem deckToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem animationSpeedToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fastToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem mediumToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem slowToolStripMenuItem; private System.ComponentModel.BackgroundWorker guiUpdatebackgroundWorker; } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class AsyncBlockExpression : BlockExpression { protected BlockExpression _block; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public AsyncBlockExpression CloneNode() { return (AsyncBlockExpression)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public AsyncBlockExpression CleanClone() { return (AsyncBlockExpression)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.AsyncBlockExpression; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnAsyncBlockExpression(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( AsyncBlockExpression)node; if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("AsyncBlockExpression._parameters"); if (!Node.Matches(_returnType, other._returnType)) return NoMatch("AsyncBlockExpression._returnType"); if (!Node.Matches(_body, other._body)) return NoMatch("AsyncBlockExpression._body"); if (!Node.Matches(_block, other._block)) return NoMatch("AsyncBlockExpression._block"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_parameters != null) { ParameterDeclaration item = existing as ParameterDeclaration; if (null != item) { ParameterDeclaration newItem = (ParameterDeclaration)newNode; if (_parameters.Replace(item, newItem)) { return true; } } } if (_returnType == existing) { this.ReturnType = (TypeReference)newNode; return true; } if (_body == existing) { this.Body = (Block)newNode; return true; } if (_block == existing) { this.Block = (BlockExpression)newNode; return true; } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { AsyncBlockExpression clone = new AsyncBlockExpression(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._expressionType = _expressionType; if (null != _parameters) { clone._parameters = _parameters.Clone() as ParameterDeclarationCollection; clone._parameters.InitializeParent(clone); } if (null != _returnType) { clone._returnType = _returnType.Clone() as TypeReference; clone._returnType.InitializeParent(clone); } if (null != _body) { clone._body = _body.Clone() as Block; clone._body.InitializeParent(clone); } if (null != _block) { clone._block = _block.Clone() as BlockExpression; clone._block.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; _expressionType = null; if (null != _parameters) { _parameters.ClearTypeSystemBindings(); } if (null != _returnType) { _returnType.ClearTypeSystemBindings(); } if (null != _body) { _body.ClearTypeSystemBindings(); } if (null != _block) { _block.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public BlockExpression Block { get { return _block; } set { if (_block != value) { _block = value; if (null != _block) { _block.InitializeParent(this); } } } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace MyTermsetCreator { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C11_City_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="C11_City_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="C10_City"/> collection. /// </remarks> [Serializable] public partial class C11_City_ReChild : BusinessBase<C11_City_ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="City_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name"); /// <summary> /// Gets or sets the CityRoads Child Name. /// </summary> /// <value>The CityRoads Child Name.</value> public string City_Child_Name { get { return GetProperty(City_Child_NameProperty); } set { SetProperty(City_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C11_City_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="C11_City_ReChild"/> object.</returns> internal static C11_City_ReChild NewC11_City_ReChild() { return DataPortal.CreateChild<C11_City_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="C11_City_ReChild"/> object, based on given parameters. /// </summary> /// <param name="city_ID2">The City_ID2 parameter of the C11_City_ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="C11_City_ReChild"/> object.</returns> internal static C11_City_ReChild GetC11_City_ReChild(int city_ID2) { return DataPortal.FetchChild<C11_City_ReChild>(city_ID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C11_City_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C11_City_ReChild() { // 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="C11_City_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="C11_City_ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="city_ID2">The City ID2.</param> protected void Child_Fetch(int city_ID2) { var args = new DataPortalHookArgs(city_ID2); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC11_City_ReChildDal>(); var data = dal.Fetch(city_ID2); Fetch(data); } OnFetchPost(args); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C11_City_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(City_Child_NameProperty, dr.GetString("City_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="C11_City_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(C10_City parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IC11_City_ReChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.City_ID, City_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="C11_City_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(C10_City parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IC11_City_ReChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.City_ID, City_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="C11_City_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(C10_City parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IC11_City_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.City_ID); } 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 } }
using System; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; using Skewworks.NETMF.Controls; namespace Skewworks.NETMF.Modal { public class Prompt { #region Variables private static ManualResetEvent _activeBlock; // Used to display Modal Forms private static Button[] _btns; private static PromptResult _result; private static int _iResult; #endregion #region Public Methods public static PromptResult Show(string title, string message, Font titleFont, Font messageFont, PromptType type = PromptType.OK, Bitmap icon = null) { int w, h, y, i; int xOffset = 0; Core.Screen.SetClippingRectangle(0, 0, Core.ScreenWidth, Core.ScreenHeight); Color cR1 = ColorUtility.ColorFromRGB(226, 92, 79); Color cR2 = ColorUtility.ColorFromRGB(202, 48, 53); IContainer prv = Core.ActiveContainer; var frmModal = new Form("modalAlertForm", Colors.Ghost); frmModal.TouchDown += frmModal_TouchDown; frmModal.TouchUp += frmModal_TouchUp; Core.SilentlyActivate(frmModal); // Determine required size titleFont.ComputeExtent(title, out w, out h); size sz = FontManager.ComputeExtentEx(messageFont, message); if (sz.Width > w) w = sz.Width; if (icon != null) { xOffset = icon.Width + 16; w += xOffset; } // Adjust for Buttons switch (type) { case PromptType.AbortContinue: i = FontManager.ComputeExtentEx(messageFont, "AbortContinue").Width + 30; break; case PromptType.AbortRetryContinue: i = FontManager.ComputeExtentEx(messageFont, "AbortRetryContinue").Width + 40; break; case PromptType.OKCancel: i = FontManager.ComputeExtentEx(messageFont, " OK Cancel").Width + 30; break; case PromptType.YesNo: i = FontManager.ComputeExtentEx(messageFont, " Yes No ").Width + 30; break; case PromptType.YesNoCancel: i = FontManager.ComputeExtentEx(messageFont, " Yes No Cancel").Width + 30; break; default: i = FontManager.ComputeExtentEx(messageFont, " OK ").Width + 20; break; } if (w < i) w = i; // Add Padding w += 32; // Now make sure we're within the screen width if (w > Core.ScreenWidth - 32) w = Core.ScreenWidth - 32; // Get height of the 2 strings messageFont.ComputeTextInRect(message, out y, out i, w - 32 - xOffset); if (icon != null && i < icon.Height) i = icon.Height; h = i + titleFont.Height + 74 + (messageFont.Height); // Check the height in screen if (h > Core.ScreenHeight - 32) h = Core.ScreenHeight - 32; // Center int x = Core.ScreenWidth / 2 - w / 2; y = Core.ScreenHeight / 2 - h / 2; Core.ShadowRegion(x, y, w, h); Core.Screen.DrawRectangle(0, 0, x, y, w, 1, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x, y + h - 1, w, 1, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x, y + 1, 1, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x + w - 1, y + 1, 1, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x + 1, y + 1, w - 2, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 256); Core.Screen.DrawRectangle(0, 0, x + 1, y + 1, w - 2, 1, 0, 0, Colors.White, 0, 0, Colors.White, 0, 0, 51); Core.Screen.DrawRectangle(0, 0, x + 1, y + 2, w - 2, 1, 0, 0, Colors.White, 0, 0, Colors.White, 0, 0, 26); // Tilebar text Core.Screen.DrawTextInRect(title, x + 16 + xOffset, y + 16, w - 32 - xOffset, titleFont.Height, Bitmap.DT_TrimmingCharacterEllipsis, Colors.CharcoalDust, titleFont); // Body text Core.Screen.DrawTextInRect(message, x + 16 + xOffset, y + 32 + titleFont.Height, w - 32 - xOffset, h - 74 - titleFont.Height, Bitmap.DT_TrimmingCharacterEllipsis + Bitmap.DT_WordWrap, Colors.CharcoalDust, messageFont); // Icon if (icon != null) Core.Screen.DrawImage(x + 16, y + 16, icon, 0, 0, icon.Width, icon.Height); // Buttons x = Core.ScreenWidth / 2 - w / 2; y = Core.ScreenHeight / 2 - h / 2; switch (type) { case PromptType.AbortContinue: _btns = new Button[2]; _btns[1] = new Button("btnContinue", "Continue", messageFont, 0, y + h - messageFont.Height - 26); _btns[0] = new Button("btnAbort", "Abort", messageFont, 0, _btns[1].Y, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed) { NormalColorTop = cR1, NormalColorBottom = cR2, PressedColorTop = cR2, PressedColorBottom = cR1 }; _btns[1].Tap += (sender, e) => EndModal(PromptResult.Continue); _btns[0].Tap += (sender, e) => EndModal(PromptResult.Abort); x = x + (w / 2) - ((_btns[1].Width + _btns[0].Width + 16) / 2); _btns[0].X = x; _btns[1].X = x + _btns[0].Width + 16; break; case PromptType.AbortRetryContinue: _btns = new Button[3]; _btns[2] = new Button("btnContinue", "Continue", messageFont, 0, y + h - messageFont.Height - 26); _btns[1] = new Button("btnRetry", "Retry", messageFont, 0, _btns[2].Y); _btns[0] = new Button("btnAbort", "Abort", messageFont, 0, _btns[1].Y, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed) { NormalColorTop = cR1, NormalColorBottom = cR2, PressedColorTop = cR2, PressedColorBottom = cR1 }; _btns[2].Tap += (sender, e) => EndModal(PromptResult.Continue); _btns[1].Tap += (sender, e) => EndModal(PromptResult.Retry); _btns[0].Tap += (sender, e) => EndModal(PromptResult.Abort); x = x + (w / 2) - ((_btns[2].Width + _btns[1].Width + _btns[0].Width + 32) / 2); _btns[0].X = x; _btns[1].X = x + _btns[0].Width + 16; _btns[2].X = x + _btns[0].Width + _btns[1].Width + 32; break; case PromptType.OKCancel: _btns = new Button[2]; _btns[1] = new Button("btnCancel", "Cancel", messageFont, 0, y + h - messageFont.Height - 26, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed) { NormalColorTop = cR1, NormalColorBottom = cR2, PressedColorTop = cR2, PressedColorBottom = cR1 }; _btns[0] = new Button("btnOK", " OK ", messageFont, 0, _btns[1].Y); _btns[1].Tap += (sender, e) => EndModal(PromptResult.Cancel); _btns[0].Tap += (sender, e) => EndModal(PromptResult.OK); x = x + (w / 2) - ((_btns[1].Width + _btns[0].Width + 16) / 2); _btns[0].X = x; _btns[1].X = x + _btns[0].Width + 16; break; case PromptType.YesNo: _btns = new Button[2]; _btns[1] = new Button("btnNo", " No ", messageFont, 0, y + h - messageFont.Height - 26, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed) { NormalColorTop = cR1, NormalColorBottom = cR2, PressedColorTop = cR2, PressedColorBottom = cR1 }; _btns[0] = new Button("btnYes", " Yes ", messageFont, 0, _btns[1].Y); _btns[1].Tap += (sender, e) => EndModal(PromptResult.No); _btns[0].Tap += (sender, e) => EndModal(PromptResult.Yes); x = x + (w / 2) - ((_btns[1].Width + _btns[0].Width + 16) / 2); _btns[0].X = x; _btns[1].X = x + _btns[0].Width + 16; break; case PromptType.YesNoCancel: _btns = new Button[3]; _btns[2] = new Button("btnCancel", "Cancel", messageFont, 0, y + h - messageFont.Height - 26, Colors.White, Colors.White, Colors.DarkRed, Colors.DarkRed) { NormalColorTop = cR1, NormalColorBottom = cR2, PressedColorTop = cR2, PressedColorBottom = cR1 }; _btns[1] = new Button("btnNo", " No ", messageFont, 0, y + h - messageFont.Height - 26); _btns[0] = new Button("btnYes", " Yes ", messageFont, 0, _btns[1].Y); _btns[2].Tap += (sender, e) => EndModal(PromptResult.Cancel); _btns[1].Tap += (sender, e) => EndModal(PromptResult.No); _btns[0].Tap += (sender, e) => EndModal(PromptResult.Yes); x = x + (w / 2) - ((_btns[2].Width + _btns[1].Width + _btns[0].Width + 32) / 2); _btns[0].X = x; _btns[1].X = x + _btns[0].Width + 16; _btns[2].X = x + _btns[0].Width + _btns[1].Width + 32; break; default: _btns = new Button[1]; _btns[0] = new Button("btnOK", " OK ", messageFont, 0, y + h - messageFont.Height - 26); _btns[0].Tap += (sender, e) => EndModal(PromptResult.OK); _btns[0].X = x + (w / 2) - (_btns[0].Width / 2); break; } // Add Buttons for (i = 0; i < _btns.Length; i++) frmModal.AddChild(_btns[i]); Core.Screen.Flush(); ModalBlock(); Core.ActiveContainer = prv; return _result; } public static int Show(string title, string message, string[] buttonOptions, Font titleFont, Font messageFont, Bitmap icon = null) { int w, h, y, i; int xOffset = 0; int btnsW = 16; // Create Buttons first this time _btns = new Button[buttonOptions.Length]; for (i = 0; i < _btns.Length; i++) { _btns[i] = new Button("btn" + i, buttonOptions[i], messageFont, 0, 0); btnsW += _btns[i].Width + 16; } Core.Screen.SetClippingRectangle(0, 0, Core.ScreenWidth, Core.ScreenHeight); //Color cR1 = ColorUtility.ColorFromRGB(226, 92, 79); //Color cR2 = ColorUtility.ColorFromRGB(202, 48, 53); IContainer prv = Core.ActiveContainer; var frmModal = new Form("modalAlertForm", Colors.Ghost); frmModal.TouchDown += frmModal_TouchDown; frmModal.TouchUp += frmModal_TouchUp; Core.SilentlyActivate(frmModal); // Determine required size titleFont.ComputeExtent(title, out w, out h); size sz = FontManager.ComputeExtentEx(messageFont, message); if (sz.Width > w) w = sz.Width; if (icon != null) { xOffset = icon.Width + 16; w += xOffset; } // Adjust for button sizes if (w < btnsW) w = btnsW; // Add Padding w += 32; // Now make sure we're within the screen width if (w > Core.ScreenWidth - 32) w = Core.ScreenWidth - 32; // Get height of the 2 strings messageFont.ComputeTextInRect(message, out y, out i, w - 32 - xOffset); if (icon != null && i < icon.Height) i = icon.Height; h = i + titleFont.Height + 74 + (messageFont.Height); // Check the height in screen if (h > Core.ScreenHeight - 32) h = Core.ScreenHeight - 32; // Center int x = Core.ScreenWidth / 2 - w / 2; y = Core.ScreenHeight / 2 - h / 2; Core.ShadowRegion(x, y, w, h); Core.Screen.DrawRectangle(0, 0, x, y, w, 1, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x, y + h - 1, w, 1, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x, y + 1, 1, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x + w - 1, y + 1, 1, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 179); Core.Screen.DrawRectangle(0, 0, x + 1, y + 1, w - 2, h - 2, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 256); Core.Screen.DrawRectangle(0, 0, x + 1, y + 1, w - 2, 1, 0, 0, Colors.White, 0, 0, Colors.White, 0, 0, 51); Core.Screen.DrawRectangle(0, 0, x + 1, y + 2, w - 2, 1, 0, 0, Colors.White, 0, 0, Colors.White, 0, 0, 26); // Tilebar text Core.Screen.DrawTextInRect(title, x + 16 + xOffset, y + 16, w - 32 - xOffset, titleFont.Height, Bitmap.DT_TrimmingCharacterEllipsis, Colors.CharcoalDust, titleFont); // Body text Core.Screen.DrawTextInRect(message, x + 16 + xOffset, y + 32 + titleFont.Height, w - 32 - xOffset, h - 74 - titleFont.Height, Bitmap.DT_TrimmingCharacterEllipsis + Bitmap.DT_WordWrap, Colors.CharcoalDust, messageFont); // Icon if (icon != null) Core.Screen.DrawImage(x + 16, y + 16, icon, 0, 0, icon.Width, icon.Height); // Position Buttons x = x + (w / 2) - (btnsW / 2); for (i = 0; i < _btns.Length; i++) { _btns[i].Tag = i; _btns[i].Y = y + h - 16 - _btns[i].Height; _btns[i].X = x; x += _btns[i].Width + 16; _btns[i].Tap += (sender, e) => EndModal((Button)sender); frmModal.AddChild(_btns[i]); } Core.Screen.Flush(); ModalBlock(); Core.ActiveContainer = prv; return _iResult; } #endregion #region Private Methods private static void EndModal(PromptResult result) { _result = result; _activeBlock.Set(); } private static void EndModal(Button result) { _iResult = (int)result.Tag; _activeBlock.Set(); } private static void frmModal_TouchDown(object sender, point e) { for (int i = _btns.Length - 1; i >= 0; i--) { if (_btns[i].Visible && _btns[i].HitTest(e)) { _btns[i].SendTouchDown(sender, new point(e.X - _btns[i].Left, e.Y - _btns[i].Top)); return; } } } private static void frmModal_TouchUp(object sender, point e) { for (int i = _btns.Length - 1; i >= 0; i--) _btns[i].SendTouchUp(sender, new point(e.X - _btns[i].Left, e.Y - _btns[i].Top)); } private static void ModalBlock() { var localBlocker = new ManualResetEvent(false); _activeBlock = localBlocker; // Wait for Result localBlocker.Reset(); while (!localBlocker.WaitOne(1000, false)) { } // Unblock _activeBlock = null; } #endregion } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using FluentAssertions.Equivalency; using Orleans.Runtime; using Orleans.Transactions.Abstractions; namespace Orleans.Transactions.TestKit { public abstract class TransactionalStateStorageTestRunner<TState> : TransactionTestRunnerBase where TState : class, new() { protected Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory; protected Func<int, TState> stateFactory; protected Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig; /// <summary> /// Constructor /// </summary> /// <param name="stateStorageFactory">factory to create ITransactionalStateStorage, the test runner are assuming the state /// in storage is empty when ITransactionalStateStorage was created </param> /// <param name="stateFactory">factory to create TState for test</param> /// <param name="grainFactory">grain Factory needed for test runner</param> /// <param name="testOutput">test output to helpful messages</param> /// <param name="assertConfig">A reference to the FluentAssertions.Equivalency.EquivalencyAssertionOptions`1 /// configuration object that can be used to influence the way the object graphs /// are compared</param> protected TransactionalStateStorageTestRunner(Func<Task<ITransactionalStateStorage<TState>>> stateStorageFactory, Func<int, TState> stateFactory, IGrainFactory grainFactory, Action<string> testOutput, Func<EquivalencyAssertionOptions<TState>, EquivalencyAssertionOptions<TState>> assertConfig = null) :base(grainFactory, testOutput) { this.stateStorageFactory = stateStorageFactory; this.stateFactory = stateFactory; this.assertConfig = assertConfig; } public virtual async Task FirstTime_Load_ShouldReturnEmptyLoadResponse() { var stateStorage = await this.stateStorageFactory(); var response = await stateStorage.Load(); var defaultStateValue = new TState(); //Assertion response.Should().NotBeNull(); response.ETag.Should().BeNull(); response.CommittedSequenceId.Should().Be(0); AssertTState(response.CommittedState, defaultStateValue); response.PendingStates.Should().BeEmpty(); } private static List<PendingTransactionState<TState>> emptyPendingStates = new List<PendingTransactionState<TState>>(); public virtual async Task StoreWithoutChanges() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store without any changes var etag1 = await stateStorage.Store(loadresponse.ETag, loadresponse.Metadata, emptyPendingStates, null, null); // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().Be(etag1); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update metadata, then write back var now = DateTime.UtcNow; var cr = MakeCommitRecords(2, 2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(etag1, metadata, emptyPendingStates, null, null); // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } public virtual async Task WrongEtags() { var stateStorage = await this.stateStorageFactory(); // load first time var loadresponse = await stateStorage.Load(); // store with wrong e-tag, must fail try { var etag1 = await stateStorage.Store("wrong-etag", loadresponse.Metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Should().BeEmpty(); loadresponse.ETag.Should().BeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); // update timestamp in metadata, then write back with correct e-tag var now = DateTime.UtcNow; var cr = MakeCommitRecords(2,2); var metadata = new TransactionalStateMetaData() { TimeStamp = now, CommitRecords = cr }; var etag2 = await stateStorage.Store(null, metadata, emptyPendingStates, null, null); // update timestamp in metadata, then write back with wrong e-tag, must fail try { var now2 = DateTime.UtcNow; var metadata2 = new TransactionalStateMetaData() { TimeStamp = now2, CommitRecords = MakeCommitRecords(3,3) }; await stateStorage.Store(null, metadata, emptyPendingStates, null, null); throw new Exception("storage did not catch e-tag mismatch"); } catch (Exception) { } // load again, check content loadresponse = await stateStorage.Load(); loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.Metadata.TimeStamp.Should().Be(now); loadresponse.Metadata.CommitRecords.Count.Should().Be(cr.Count); loadresponse.ETag.Should().Be(etag2); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Should().BeEmpty(); } private void AssertTState(TState actual, TState expected) { if(assertConfig == null) actual.ShouldBeEquivalentTo(expected); else actual.ShouldBeEquivalentTo(expected, assertConfig); } private PendingTransactionState<TState> MakePendingState(long seqno, TState val, bool tm) { var result = new PendingTransactionState<TState>() { SequenceId = seqno, TimeStamp = DateTime.UtcNow, TransactionId = Guid.NewGuid().ToString(), TransactionManager = tm ? default(ParticipantId) : MakeParticipantId(), State = new TState() }; result.State = val; return result; } private ParticipantId MakeParticipantId() { return new ParticipantId( "tm", null, // (GrainReference) grainFactory.GetGrain<ITransactionTestGrain>(Guid.NewGuid(), TransactionTestConstants.SingleStateTransactionalGrain), ParticipantId.Role.Resource | ParticipantId.Role.Manager); } private Dictionary<Guid, CommitRecord> MakeCommitRecords(int count, int size) { var result = new Dictionary<Guid, CommitRecord>(); for (int j = 0; j < size; j++) { var r = new CommitRecord() { Timestamp = DateTime.UtcNow, WriteParticipants = new List<ParticipantId>(), }; for (int i = 0; i < size; i++) { r.WriteParticipants.Add(MakeParticipantId()); } result.Add(Guid.NewGuid(), r); } return result; } private async Task PrepareOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState); } public virtual async Task ConfirmOne(bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate = MakePendingState(1, expectedState, false); if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); } else { etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, 1, null); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState, expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate = MakePendingState(1, this.stateFactory(123), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate }, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceOne() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState1 = this.stateFactory(123); var expectedState2 = this.stateFactory(456); var pendingstate1 = MakePendingState(1, expectedState1, false); var pendingstate2 = MakePendingState(1, expectedState2, false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1 }, null, null); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate2 }, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(1); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate2.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate2.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate2.TransactionId); AssertTState(loadresponse.PendingStates[0].State,expectedState2); } public virtual async Task ConfirmOneAndCancelOne(bool useTwoSteps = false, bool reverseOrder = false) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedState = this.stateFactory(123); var pendingstate1 = MakePendingState(1, expectedState, false); var pendingstate2 = MakePendingState(2, this.stateFactory(456), false); etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2 }, null, null); if (useTwoSteps) { if (reverseOrder) { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } else { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 1); } } else { etag = await stateStorage.Store(etag, metadata, emptyPendingStates, 1, 1); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(1); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedState); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task PrepareMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstates = new List<PendingTransactionState<TState>>(); var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i+1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State,expectedStates[i]); } } public virtual async Task ConfirmMany(int count, bool useTwoSteps) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } if (useTwoSteps) { etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, count, null); } else { etag = await stateStorage.Store(etag, metadata, pendingstates, count, null); } loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(count); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,expectedStates[count - 1]); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task CancelMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates.Add(this.stateFactory(i * 1000)); } var pendingstates = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates.Add(MakePendingState(i + 1, expectedStates[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates, null, null); etag = await stateStorage.Store(etag, metadata, emptyPendingStates, null, 0); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(0); AssertTState(loadresponse.CommittedState,initialstate); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); } public virtual async Task ReplaceMany(int count) { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var expectedStates1 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates1.Add(this.stateFactory(i * 1000 + 1)); } var expectedStates2 = new List<TState>(); for (int i = 0; i < count; i++) { expectedStates2.Add(this.stateFactory(i * 1000)); } var pendingstates1 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates1.Add(MakePendingState(i + 1, expectedStates1[i], false)); } var pendingstates2 = new List<PendingTransactionState<TState>>(); for (int i = 0; i < count; i++) { pendingstates2.Add(MakePendingState(i + 1, expectedStates2[i], false)); } etag = await stateStorage.Store(etag, metadata, pendingstates1, null, null); etag = await stateStorage.Store(etag, metadata, pendingstates2, null, null); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(count); for (int i = 0; i < count; i++) { loadresponse.PendingStates[i].SequenceId.Should().Be(i + 1); loadresponse.PendingStates[i].TimeStamp.Should().Be(pendingstates2[i].TimeStamp); loadresponse.PendingStates[i].TransactionManager.Should().Be(pendingstates2[i].TransactionManager); loadresponse.PendingStates[i].TransactionId.Should().Be(pendingstates2[i].TransactionId); AssertTState(loadresponse.PendingStates[i].State, expectedStates2[i]); } } public virtual async Task GrowingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate3b = MakePendingState(3, this.stateFactory(33), false); var pendingstate4b = MakePendingState(4, this.stateFactory(44), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var expectedState6 = this.stateFactory(66); var pendingstate6 = MakePendingState(6, expectedState6, false); var expectedState7 = this.stateFactory(77); var pendingstate7 = MakePendingState(7, expectedState7, false); var expectedState8 = this.stateFactory(88); var pendingstate8 = MakePendingState(8, expectedState8, false); // prepare 1,2,3a,4a etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a}, null, null); // replace 3b,4b, prepare 5, 6, 7, 8 confirm 1, 2, 3b, 4b, 5, 6 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, 6, 6); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(6); AssertTState(loadresponse.CommittedState, expectedState6); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(2); loadresponse.PendingStates[0].SequenceId.Should().Be(7); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate7.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate7.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate7.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState7); loadresponse.PendingStates[1].SequenceId.Should().Be(8); loadresponse.PendingStates[1].TimeStamp.Should().Be(pendingstate8.TimeStamp); loadresponse.PendingStates[1].TransactionManager.Should().Be(pendingstate8.TransactionManager); loadresponse.PendingStates[1].TransactionId.Should().Be(pendingstate8.TransactionId); AssertTState(loadresponse.PendingStates[1].State, expectedState8); } public virtual async Task ShrinkingBatch() { var stateStorage = await this.stateStorageFactory(); var loadresponse = await stateStorage.Load(); var etag = loadresponse.ETag; var metadata = loadresponse.Metadata; var initialstate = loadresponse.CommittedState; var pendingstate1 = MakePendingState(1, this.stateFactory(11), false); var pendingstate2 = MakePendingState(2, this.stateFactory(22), false); var pendingstate3a = MakePendingState(3, this.stateFactory(333), false); var pendingstate4a = MakePendingState(4, this.stateFactory(444), false); var pendingstate5 = MakePendingState(5, this.stateFactory(55), false); var pendingstate6 = MakePendingState(6, this.stateFactory(66), false); var pendingstate7 = MakePendingState(7, this.stateFactory(77), false); var pendingstate8 = MakePendingState(8, this.stateFactory(88), false); var expectedState3b = this.stateFactory(33); var pendingstate3b = MakePendingState(3, expectedState3b, false); var expectedState4b = this.stateFactory(44); var pendingstate4b = MakePendingState(4, expectedState4b, false); // prepare 1,2,3a,4a, 5, 6, 7, 8 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate1, pendingstate2, pendingstate3a, pendingstate4a, pendingstate5, pendingstate6, pendingstate7, pendingstate8 }, null, null); // replace 3b,4b, confirm 1, 2, 3b, cancel 5, 6, 7, 8 etag = await stateStorage.Store(etag, metadata, new List<PendingTransactionState<TState>>() { pendingstate3b, pendingstate4b }, 3, 4); loadresponse = await stateStorage.Load(); etag = loadresponse.ETag; metadata = loadresponse.Metadata; loadresponse.Should().NotBeNull(); loadresponse.Metadata.Should().NotBeNull(); loadresponse.CommittedSequenceId.Should().Be(3); AssertTState(loadresponse.CommittedState, expectedState3b); loadresponse.Metadata.TimeStamp.Should().Be(default(DateTime)); loadresponse.Metadata.CommitRecords.Count.Should().Be(0); loadresponse.PendingStates.Count.Should().Be(1); loadresponse.PendingStates[0].SequenceId.Should().Be(4); loadresponse.PendingStates[0].TimeStamp.Should().Be(pendingstate4b.TimeStamp); loadresponse.PendingStates[0].TransactionManager.Should().Be(pendingstate4b.TransactionManager); loadresponse.PendingStates[0].TransactionId.Should().Be(pendingstate4b.TransactionId); AssertTState(loadresponse.PendingStates[0].State, expectedState4b); } } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = "SolutionCrawler"; [Fact] public void RegisterService() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); } } [Fact, WorkItem(747226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747226")] public async Task SolutionAdded_Simple() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task SolutionAdded_Complex() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Clear() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.ClearSolution()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_AssemblyName_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName"); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Project_AnalyzerOptions_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project; var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Project_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [Fact] public async Task Document_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Document_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Documents[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Reanalyze() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id), highPriority: false); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_AdditionalFileChange() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation_MultipleTimes() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_InvocationReasons() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [Fact] public async Task Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; int position; string code; MarkupTestFile.GetPosition(markup, out code, out position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = (new Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService()).GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")] public async Task SemanticChange_Propagation() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); #if false Assert.True(1 == worker.SyntaxDocumentIds.Count, string.Format("Expected 1 SyntaxDocumentIds, Got {0}\n\n{1}", worker.SyntaxDocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); Assert.True(4 == worker.DocumentIds.Count, string.Format("Expected 4 DocumentIds, Got {0}\n\n{1}", worker.DocumentIds.Count, GetListenerTrace(workspace.ExportProvider))); #endif } } [Fact] public async Task ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { await WaitWaiterAsync(workspace.ExportProvider); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = await TestWorkspace.CreateAsync( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: code)) { var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); operation(workspace); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); return worker; } private async Task TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { await document.GetTextAsync(); await document.GetSyntaxRootAsync(); await document.GetSemanticModelAsync(); } } } private async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { await WaitWaiterAsync(workspace.ExportProvider); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private async Task WaitWaiterAsync(ExportProvider provider) { var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; await workspaceWaiter.CreateWaitTask(); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; await solutionCrawlerWaiter.CreateWaitTask(); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private static IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { internal SolutionCrawlerWaiter() { } } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { internal WorkspaceWaiter() { } } private class WorkCoordinatorWorkspace : TestWorkspace { private readonly IAsynchronousOperationWaiter _workspaceWaiter; private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter; public WorkCoordinatorWorkspace(string workspaceKind = null, bool disablePartialSolutions = true) : base(TestExportProvider.CreateExportProviderWithCSharpAndVisualBasic(), workspaceKind, disablePartialSolutions) { _workspaceWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; _solutionCrawlerWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); } protected override void Dispose(bool finalize) { base.Dispose(finalize); Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); } } private class AnalyzerProvider : IIncrementalAnalyzerProvider { private readonly Analyzer _analyzer; public AnalyzerProvider(Analyzer analyzer) { _analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return _analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return false; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspaceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #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.Reflection; using System.Collections.Generic; namespace System.Reflection.Runtime.BindingFlagSupport { internal static class MemberEnumerator { // // Enumerates members, optionally filtered by a name, in the given class and its base classes (but not implemented interfaces.) // Basically emulates the old Type.GetFoo(BindingFlags) api. // public static IEnumerable<M> GetMembers<M>(this Type type, Object nameFilterOrAnyName, BindingFlags bindingFlags) where M : MemberInfo { // Do all the up-front argument validation here so that the exception occurs on call rather than on the first move. if (type == null) { throw new ArgumentNullException(); } if (nameFilterOrAnyName == null) { throw new ArgumentNullException(); } String optionalNameFilter; if (nameFilterOrAnyName == AnyName) { optionalNameFilter = null; } else { optionalNameFilter = (String)nameFilterOrAnyName; } return GetMembersWorker<M>(type, optionalNameFilter, bindingFlags); } // // The iterator worker for GetMember<M>() // private static IEnumerable<M> GetMembersWorker<M>(Type type, String optionalNameFilter, BindingFlags bindingFlags) where M : MemberInfo { Type reflectedType = type; Type typeOfM = typeof(M); Type typeOfEventInfo = typeof(EventInfo); MemberPolicies<M> policies = MemberPolicies<M>.Default; bindingFlags = policies.ModifyBindingFlags(bindingFlags); LowLevelList<M> overridingMembers = new LowLevelList<M>(); StringComparison comparisonType = (0 != (bindingFlags & BindingFlags.IgnoreCase)) ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture; bool inBaseClass = false; bool nameFilterIsPrefix = false; if (optionalNameFilter != null && optionalNameFilter.EndsWith("*", StringComparison.Ordinal)) { nameFilterIsPrefix = true; optionalNameFilter = optionalNameFilter.Substring(0, optionalNameFilter.Length - 1); } while (type != null) { TypeInfo typeInfo = type.GetTypeInfo(); foreach (M member in policies.GetDeclaredMembers(typeInfo)) { if (optionalNameFilter != null) { if (nameFilterIsPrefix) { if (!member.Name.StartsWith(optionalNameFilter, comparisonType)) { continue; } } else if (!member.Name.Equals(optionalNameFilter, comparisonType)) { continue; } } MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); BindingFlags memberBindingFlags = (BindingFlags)0; memberBindingFlags |= (isStatic ? BindingFlags.Static : BindingFlags.Instance); memberBindingFlags |= ((visibility == MethodAttributes.Public) ? BindingFlags.Public : BindingFlags.NonPublic); if ((bindingFlags & memberBindingFlags) != memberBindingFlags) { continue; } bool passesVisibilityScreen = true; if (inBaseClass && visibility == MethodAttributes.Private) { passesVisibilityScreen = false; } bool passesStaticScreen = true; if (inBaseClass && isStatic && (0 == (bindingFlags & BindingFlags.FlattenHierarchy))) { passesStaticScreen = false; } // // Desktop compat: The order in which we do checks is important. // if (!passesVisibilityScreen) { continue; } if ((!passesStaticScreen) && !(typeOfM.Equals(typeOfEventInfo))) { continue; } bool isImplicitlyOverridden = false; if (isVirtual) { if (isNewSlot) { // A new virtual member definition. for (int i = 0; i < overridingMembers.Count; i++) { if (policies.AreNamesAndSignatureEqual(member, overridingMembers[i])) { // This member is overridden by a more derived class. isImplicitlyOverridden = true; overridingMembers.RemoveAt(i); break; } } } else { for (int i = 0; i < overridingMembers.Count; i++) { if (policies.AreNamesAndSignatureEqual(overridingMembers[i], member)) { // This member overrides another, *and* is overridden by yet another method. isImplicitlyOverridden = true; break; } } if (!isImplicitlyOverridden) { // This member overrides another and is the most derived instance of it we've found. overridingMembers.Add(member); } } } if (isImplicitlyOverridden) { continue; } if (!passesStaticScreen) { continue; } if (inBaseClass) { yield return policies.GetInheritedMemberInfo(member, reflectedType); } else { yield return member; } } if (0 != (bindingFlags & BindingFlags.DeclaredOnly)) { break; } inBaseClass = true; type = typeInfo.BaseType; } } // // If member is a virtual member that implicitly overrides a member in a base class, return the overridden member. // Otherwise, return null. // // - MethodImpls ignored. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // - Implemented interfaces ignores. (I didn't say it made sense, this is just how the desktop api we're porting behaves.) // public static M GetImplicitlyOverriddenBaseClassMember<M>(this M member) where M : MemberInfo { MemberPolicies<M> policies = MemberPolicies<M>.Default; MethodAttributes visibility; bool isStatic; bool isVirtual; bool isNewSlot; policies.GetMemberAttributes(member, out visibility, out isStatic, out isVirtual, out isNewSlot); if (isNewSlot || !isVirtual) { return null; } String name = member.Name; TypeInfo typeInfo = member.DeclaringType.GetTypeInfo(); for (; ;) { Type baseType = typeInfo.BaseType; if (baseType == null) { return null; } typeInfo = baseType.GetTypeInfo(); foreach (M candidate in policies.GetDeclaredMembers(typeInfo)) { if (candidate.Name != name) { continue; } MethodAttributes candidateVisibility; bool isCandidateStatic; bool isCandidateVirtual; bool isCandidateNewSlot; policies.GetMemberAttributes(member, out candidateVisibility, out isCandidateStatic, out isCandidateVirtual, out isCandidateNewSlot); if (!isCandidateVirtual) { continue; } if (!policies.AreNamesAndSignatureEqual(member, candidate)) { continue; } return candidate; } } } // Uniquely allocated sentinel "string" // - can't use null as that may be an app-supplied null, which we have to throw ArgumentNullException for. // - risky to use a proper String as the FX or toolchain can unexpectedly give you back a shared string // even when you'd swear you were allocating a new one. public static readonly Object AnyName = new Object(); } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Gaming.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGameServerDeploymentsServiceClientTest { [xunit::FactAttribute] public void GetGameServerDeploymentRequestObject() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment response = client.GetGameServerDeployment(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentRequestObjectAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerDeployment() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment response = client.GetGameServerDeployment(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerDeploymentResourceNames() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeployment(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment response = client.GetGameServerDeployment(request.GameServerDeploymentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentResourceNamesAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeployment expectedResponse = new GameServerDeployment { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), Labels = { { "key8a0b6e3c", "value60c16320" }, }, Etag = "etage8ad7218", Description = "description2cf9da67", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeployment>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeployment responseCallSettings = await client.GetGameServerDeploymentAsync(request.GameServerDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeployment responseCancellationToken = await client.GetGameServerDeploymentAsync(request.GameServerDeploymentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerDeploymentRolloutRequestObject() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentRolloutRequestObjectAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerDeploymentRollout() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentRolloutAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetGameServerDeploymentRolloutResourceNames() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout response = client.GetGameServerDeploymentRollout(request.GameServerDeploymentName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGameServerDeploymentRolloutResourceNamesAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; GameServerDeploymentRollout expectedResponse = new GameServerDeploymentRollout { GameServerDeploymentRolloutName = GameServerDeploymentRolloutName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), CreateTime = new wkt::Timestamp(), UpdateTime = new wkt::Timestamp(), DefaultGameServerConfig = "default_game_server_config2214de2f", GameServerConfigOverrides = { new GameServerConfigOverride(), }, Etag = "etage8ad7218", }; mockGrpcClient.Setup(x => x.GetGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerDeploymentRollout>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); GameServerDeploymentRollout responseCallSettings = await client.GetGameServerDeploymentRolloutAsync(request.GameServerDeploymentName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GameServerDeploymentRollout responseCancellationToken = await client.GetGameServerDeploymentRolloutAsync(request.GameServerDeploymentName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PreviewGameServerDeploymentRolloutRequestObject() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new wkt::FieldMask(), PreviewTime = new wkt::Timestamp(), }; PreviewGameServerDeploymentRolloutResponse expectedResponse = new PreviewGameServerDeploymentRolloutResponse { Unavailable = { "unavailable48e06070", }, Etag = "etage8ad7218", TargetState = new TargetState(), }; mockGrpcClient.Setup(x => x.PreviewGameServerDeploymentRollout(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); PreviewGameServerDeploymentRolloutResponse response = client.PreviewGameServerDeploymentRollout(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PreviewGameServerDeploymentRolloutRequestObjectAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new wkt::FieldMask(), PreviewTime = new wkt::Timestamp(), }; PreviewGameServerDeploymentRolloutResponse expectedResponse = new PreviewGameServerDeploymentRolloutResponse { Unavailable = { "unavailable48e06070", }, Etag = "etage8ad7218", TargetState = new TargetState(), }; mockGrpcClient.Setup(x => x.PreviewGameServerDeploymentRolloutAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewGameServerDeploymentRolloutResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); PreviewGameServerDeploymentRolloutResponse responseCallSettings = await client.PreviewGameServerDeploymentRolloutAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PreviewGameServerDeploymentRolloutResponse responseCancellationToken = await client.PreviewGameServerDeploymentRolloutAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void FetchDeploymentStateRequestObject() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "name1c9368b0", }; FetchDeploymentStateResponse expectedResponse = new FetchDeploymentStateResponse { ClusterState = { new FetchDeploymentStateResponse.Types.DeployedClusterState(), }, Unavailable = { "unavailable48e06070", }, }; mockGrpcClient.Setup(x => x.FetchDeploymentState(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); FetchDeploymentStateResponse response = client.FetchDeploymentState(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task FetchDeploymentStateRequestObjectAsync() { moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient> mockGrpcClient = new moq::Mock<GameServerDeploymentsService.GameServerDeploymentsServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "name1c9368b0", }; FetchDeploymentStateResponse expectedResponse = new FetchDeploymentStateResponse { ClusterState = { new FetchDeploymentStateResponse.Types.DeployedClusterState(), }, Unavailable = { "unavailable48e06070", }, }; mockGrpcClient.Setup(x => x.FetchDeploymentStateAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<FetchDeploymentStateResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GameServerDeploymentsServiceClient client = new GameServerDeploymentsServiceClientImpl(mockGrpcClient.Object, null); FetchDeploymentStateResponse responseCallSettings = await client.FetchDeploymentStateAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); FetchDeploymentStateResponse responseCancellationToken = await client.FetchDeploymentStateAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Certificates. /// </summary> internal partial class CertificatesOperations : IServiceOperations<ApiManagementClient>, ICertificatesOperations { /// <summary> /// Initializes a new instance of the CertificatesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal CertificatesOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Creates new or update existing certificate. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the subscription. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='etag'> /// Optional. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateOrUpdateAsync(string resourceGroupName, string serviceName, string certificateId, CertificateCreateOrUpdateParameters parameters, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (certificateId == null) { throw new ArgumentNullException("certificateId"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // 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("serviceName", serviceName); tracingParameters.Add("certificateId", certificateId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certificateId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-02-14"); 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.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject certificateCreateOrUpdateParametersValue = new JObject(); requestDoc = certificateCreateOrUpdateParametersValue; if (parameters.Data != null) { certificateCreateOrUpdateParametersValue["data"] = parameters.Data; } if (parameters.Password != null) { certificateCreateOrUpdateParametersValue["password"] = parameters.Password; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // 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.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes specific certificate. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string certificateId, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (certificateId == null) { throw new ArgumentNullException("certificateId"); } if (etag == null) { throw new ArgumentNullException("etag"); } // 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("serviceName", serviceName); tracingParameters.Add("certificateId", certificateId); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certificateId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-02-14"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // 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 && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets specific certificate. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='certificateId'> /// Required. Identifier of the certificate. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Certificate operation response details. /// </returns> public async Task<CertificateGetResponse> GetAsync(string resourceGroupName, string serviceName, string certificateId, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (certificateId == null) { throw new ArgumentNullException("certificateId"); } // 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("serviceName", serviceName); tracingParameters.Add("certificateId", certificateId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(certificateId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-02-14"); 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 CertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CertificateGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { CertificateContract valueInstance = new CertificateContract(); result.Value = valueInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); valueInstance.IdPath = idInstance; } JToken subjectValue = responseDoc["subject"]; if (subjectValue != null && subjectValue.Type != JTokenType.Null) { string subjectInstance = ((string)subjectValue); valueInstance.Subject = subjectInstance; } JToken thumbprintValue = responseDoc["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); valueInstance.Thumbprint = thumbprintInstance; } JToken expirationDateValue = responseDoc["expirationDate"]; if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null) { DateTime expirationDateInstance = ((DateTime)expirationDateValue); valueInstance.ExpirationDate = expirationDateInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } 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='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public async Task<CertificateListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // 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("serviceName", serviceName); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-02-14"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.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 // 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 CertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CertificateListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { CertificatePaged resultInstance = new CertificatePaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { CertificateContract certificateContractInstance = new CertificateContract(); resultInstance.Values.Add(certificateContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); certificateContractInstance.IdPath = idInstance; } JToken subjectValue = valueValue["subject"]; if (subjectValue != null && subjectValue.Type != JTokenType.Null) { string subjectInstance = ((string)subjectValue); certificateContractInstance.Subject = subjectInstance; } JToken thumbprintValue = valueValue["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); certificateContractInstance.Thumbprint = thumbprintInstance; } JToken expirationDateValue = valueValue["expirationDate"]; if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null) { DateTime expirationDateInstance = ((DateTime)expirationDateValue); certificateContractInstance.ExpirationDate = expirationDateInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.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> /// List all certificates of the Api Management service instance. /// </summary> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List Certificates operation response details. /// </returns> public async Task<CertificateListResponse> 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 CertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new CertificateListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { CertificatePaged resultInstance = new CertificatePaged(); result.Result = resultInstance; JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { CertificateContract certificateContractInstance = new CertificateContract(); resultInstance.Values.Add(certificateContractInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); certificateContractInstance.IdPath = idInstance; } JToken subjectValue = valueValue["subject"]; if (subjectValue != null && subjectValue.Type != JTokenType.Null) { string subjectInstance = ((string)subjectValue); certificateContractInstance.Subject = subjectInstance; } JToken thumbprintValue = valueValue["thumbprint"]; if (thumbprintValue != null && thumbprintValue.Type != JTokenType.Null) { string thumbprintInstance = ((string)thumbprintValue); certificateContractInstance.Thumbprint = thumbprintInstance; } JToken expirationDateValue = valueValue["expirationDate"]; if (expirationDateValue != null && expirationDateValue.Type != JTokenType.Null) { DateTime expirationDateInstance = ((DateTime)expirationDateValue); certificateContractInstance.ExpirationDate = expirationDateInstance; } } } JToken countValue = responseDoc["count"]; if (countValue != null && countValue.Type != JTokenType.Null) { long countInstance = ((long)countValue); resultInstance.TotalCount = countInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); resultInstance.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(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using System.Text; using Xunit; namespace System.PrivateUri.Tests { /// <summary> /// These tests attempt to verify the transitivity of Uri.MakeRelativeUri with new Uri(base, rel). /// Specifically these tests address the use of Unicode and Iri with explicit and implicit file Uris. /// Note: Many of the test only partially pass with the current Uri implementation. Known discrepancies /// have been marked as expected so that we can still track changes. /// </summary> public class IriRelativeFileResolutionTest { private static readonly bool s_isWindowsSystem = PlatformDetection.IsWindows; [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitFileWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeImplicitTestFile = s_isWindowsSystem ? @"c:\path\path3\test.txt" : "/path/path3/test.txt"; string nonUnicodeImplicitFileBase = s_isWindowsSystem ? @"c:\path\file.txt" : "/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(nonUnicodeImplicitTestFile, nonUnicodeImplicitFileBase, out testResults); Assert.True((errorCount == 0), testResults); } [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitFileWithReservedChar_AllPropertiesTheSame() { string nonUnicodeImplicitTestFile = s_isWindowsSystem ? @"c:\path\path3\test.txt%25%" : "/path/path3/test.txt%25%"; string nonUnicodeImplicitFileBase = s_isWindowsSystem ? @"c:\path\file.txt" : "/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(nonUnicodeImplicitTestFile, nonUnicodeImplicitFileBase, out testResults); Assert.True((errorCount == 4), testResults); // AbsolutePath, AbsoluteUri, LocalPath, PathAndQuery } [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitFileWithUnicodeIriOn_AllPropertiesTheSame() { string unicodeImplicitTestFile = s_isWindowsSystem ? @"c:\path\\u30AF\path3\\u30EB\u30DE.text" : "/path//u30AF/path3//u30EB/u30DE.text"; string nonUnicodeImplicitFileBase = s_isWindowsSystem ? @"c:\path\file.txt" : "/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(unicodeImplicitTestFile, nonUnicodeImplicitFileBase, out testResults); Assert.True((errorCount == 0), testResults); } [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitFileWithUnicodeAndReservedCharIriOn_AllPropertiesTheSame() { string unicodeImplicitTestFile = s_isWindowsSystem ? @"c:\path\\u30AF\path3\\u30EB\u30DE.text%25%" : "/path//u30AF/path3//u30EB/u30DE.text%25%"; string nonUnicodeImplicitFileBase = s_isWindowsSystem ? @"c:\path\file.txt" : "/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(unicodeImplicitTestFile, nonUnicodeImplicitFileBase, out testResults); Assert.True((errorCount == (s_isWindowsSystem ? 4 : 0)), testResults); // AbsolutePath, AbsoluteUri, LocalPath, PathAndQuery } [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitUncWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeImplicitTestUnc = @"\\c\path\path3\test.txt"; string nonUnicodeImplicitUncBase = @"\\c/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(nonUnicodeImplicitTestUnc, nonUnicodeImplicitUncBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unc paths must start with '\' on Unix public void IriRelativeResolution_CompareImplcitAndExplicitUncForwardSlashesWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeImplicitTestUnc = @"//c/path/path3/test.txt"; string nonUnicodeImplicitUncBase = @"//c/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(nonUnicodeImplicitTestUnc, nonUnicodeImplicitUncBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareImplcitAndExplicitUncWithUnicodeIriOn_AllPropertiesTheSame() { string unicodeImplicitTestUnc = @"\\c\path\\u30AF\path3\\u30EB\u30DE.text"; string nonUnicodeImplicitUncBase = @"\\c\path\file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareImplicitVsExplicitFiles(unicodeImplicitTestUnc, nonUnicodeImplicitUncBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } public static int RelatavizeRestoreCompareImplicitVsExplicitFiles(string original, string baseString, out string errors) { string fileSchemePrefix = s_isWindowsSystem ? "file:///" : "file://"; Uri implicitTestUri = new Uri(original); Uri implicitBaseUri = new Uri(baseString); Uri explicitBaseUri = new Uri(fileSchemePrefix + baseString); Uri rel = implicitBaseUri.MakeRelativeUri(implicitTestUri); Uri implicitResultUri = new Uri(implicitBaseUri, rel); Uri explicitResultUri = new Uri(explicitBaseUri, rel); Type uriType = typeof(Uri); PropertyInfo[] infoList = uriType.GetProperties(); StringBuilder testResults = new StringBuilder(); int errorCount = 0; foreach (PropertyInfo info in infoList) { string implicitValue = info.GetValue(implicitResultUri, null).ToString(); string explicitValue = info.GetValue(explicitResultUri, null).ToString(); if (!(implicitValue.Equals(explicitValue) || (fileSchemePrefix + implicitValue).Equals(explicitValue))) { errorCount++; testResults.Append("Property mismatch: " + info.Name + ", implicit value: " + implicitValue + ", explicit value: " + explicitValue + "; "); } } string implicitString = implicitResultUri.ToString(); string explicitString = explicitResultUri.ToString(); if (!implicitString.Equals(explicitString)) { errorCount++; testResults.Append("ToString mismatch; implicit value: " + implicitString + ", explicit value: " + explicitString); } errors = testResults.ToString(); return errorCount; } [Fact] public void IriRelativeResolution_CompareImplcitAndOriginalFileWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeImplicitTestFile = s_isWindowsSystem ? @"c:\path\path3\test.txt" : "/path/path3/test.txt"; string nonUnicodeImplicitFileBase = s_isWindowsSystem ? @"c:\path\file.txt" : "/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(nonUnicodeImplicitTestFile, nonUnicodeImplicitFileBase, out testResults); Assert.True((errorCount == (s_isWindowsSystem ? 1 : 0)), testResults); if (s_isWindowsSystem) { Assert.True(IsOriginalString(testResults), testResults); } } [Fact] public void IriRelativeResolution_CompareUncAndOriginalFileWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeUncTestFile = @"\\c\path\path3\test.txt"; string nonUnicodeUncFileBase = @"\\c\path\file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(nonUnicodeUncTestFile, nonUnicodeUncFileBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Unc paths must start with '\' on Unix public void IriRelativeResolution_CompareUncForwardSlashesAndOriginalFileWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeUncTestFile = @"//c/path/path3/test.txt"; string nonUnicodeUncFileBase = @"//c/path/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(nonUnicodeUncTestFile, nonUnicodeUncFileBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithNoUnicode_AllPropertiesTheSame() { string nonUnicodeTest = @"http://user:password@host.com:9090/path/path3/test.txt"; string nonUnicodeBase = @"http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(nonUnicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 0), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithNoUnicodeAndReservedChar_AllPropertiesTheSame() { string nonUnicodeTest = @"http://user:password@host.com:9090/path/path3/test.txt%25%"; string nonUnicodeBase = @"http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(nonUnicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithUnicodeIriOff_AllPropertiesTheSame() { string unicodeTest = "http://user:password@host.com:9090/path\u30AF/path3/\u30EBtest.txt"; string nonUnicodeBase = "http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(unicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithUnicodeAndReservedCharIriOff_AllPropertiesTheSame() { string unicodeTest = "http://user:password@host.com:9090/path\u30AF/path3/\u30EBtest.txt%25%"; string nonUnicodeBase = "http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(unicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithUnicodeIriOn_AllPropertiesTheSame() { string unicodeTest = "http://user:password@host.com:9090/path\u30AF/path3/\u30EBtest.txt"; string nonUnicodeBase = "http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(unicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } [Fact] public void IriRelativeResolution_CompareRelativeAndOriginalHttpWithUnicodeAndReservedCharIriOn_AllPropertiesTheSame() { string unicodeTest = "http://user:password@host.com:9090/path\u30AF/path3/\u30EBtest.txt%25%"; string nonUnicodeBase = "http://user:password@host.com:9090/path2/file.txt"; string testResults; int errorCount = RelatavizeRestoreCompareVsOriginal(unicodeTest, nonUnicodeBase, out testResults); Assert.True((errorCount == 1), testResults); Assert.True(IsOriginalString(testResults), testResults); } public static int RelatavizeRestoreCompareVsOriginal(string original, string baseString, out string errors) { Uri startUri = new Uri(original); string abs = startUri.AbsolutePath; Uri baseUri = new Uri(baseString); Uri rel = baseUri.MakeRelativeUri(startUri); //string relString = rel.ToString(); // For debugging Uri stage2Uri = new Uri(baseUri, rel); // Test for true transitivity with an extra cycle rel = baseUri.MakeRelativeUri(stage2Uri); Uri resultUri = new Uri(baseUri, rel); Type uriType = typeof(Uri); PropertyInfo[] infoList = uriType.GetProperties(); StringBuilder testResults = new StringBuilder(); int errorCount = 0; foreach (PropertyInfo info in infoList) { string resultValue = info.GetValue(resultUri, null).ToString(); string startValue = info.GetValue(startUri, null).ToString(); if (!resultValue.Equals(startValue)) { errorCount++; testResults.Append("Property mismatch: " + info.Name + ", result value: " + resultValue + ", start value: " + startValue + "; "); } } string resultString = resultUri.ToString(); string startString = startUri.ToString(); if (!resultString.Equals(startString)) { errorCount++; testResults.Append("ToString mismatch; result value: " + resultString + ", start value: " + startString); } errors = testResults.ToString(); return errorCount; } private static bool IsOriginalString(string error) { return error.StartsWith("Property mismatch: OriginalString,"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ComponentModel { public partial class ArrayConverter : System.ComponentModel.CollectionConverter { public ArrayConverter() { } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public abstract partial class BaseNumberConverter : System.ComponentModel.TypeConverter { protected BaseNumberConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type t) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class BooleanConverter : System.ComponentModel.TypeConverter { public BooleanConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } } public partial class ByteConverter : System.ComponentModel.BaseNumberConverter { public ByteConverter() { } } public partial class CharConverter : System.ComponentModel.TypeConverter { public CharConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class CollectionConverter : System.ComponentModel.TypeConverter { public CollectionConverter() { } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class DateTimeConverter : System.ComponentModel.TypeConverter { public DateTimeConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class DateTimeOffsetConverter : System.ComponentModel.TypeConverter { public DateTimeOffsetConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class DecimalConverter : System.ComponentModel.BaseNumberConverter { public DecimalConverter() { } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class DoubleConverter : System.ComponentModel.BaseNumberConverter { public DoubleConverter() { } } public partial class EnumConverter : System.ComponentModel.TypeConverter { public EnumConverter(System.Type type) { } protected System.Type EnumType { get { return default(System.Type); } } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class GuidConverter : System.ComponentModel.TypeConverter { public GuidConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class Int16Converter : System.ComponentModel.BaseNumberConverter { public Int16Converter() { } } public partial class Int32Converter : System.ComponentModel.BaseNumberConverter { public Int32Converter() { } } public partial class Int64Converter : System.ComponentModel.BaseNumberConverter { public Int64Converter() { } } public partial interface ITypeDescriptorContext : System.IServiceProvider { System.ComponentModel.IContainer Container { get; } object Instance { get; } System.ComponentModel.PropertyDescriptor PropertyDescriptor { get; } void OnComponentChanged(); bool OnComponentChanging(); } public partial class MultilineStringConverter : System.ComponentModel.TypeConverter { public MultilineStringConverter() { } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class NullableConverter : System.ComponentModel.TypeConverter { public NullableConverter(System.Type type) { } public System.Type NullableType { get { return default(System.Type); } } public System.Type UnderlyingType { get { return default(System.Type); } } public System.ComponentModel.TypeConverter UnderlyingTypeConverter { get { return default(System.ComponentModel.TypeConverter); } } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public abstract partial class PropertyDescriptor { internal PropertyDescriptor() { } } public partial class SByteConverter : System.ComponentModel.BaseNumberConverter { public SByteConverter() { } } public partial class SingleConverter : System.ComponentModel.BaseNumberConverter { public SingleConverter() { } } public partial class StringConverter : System.ComponentModel.TypeConverter { public StringConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } } public partial class TimeSpanConverter : System.ComponentModel.TypeConverter { public TimeSpanConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class TypeConverter { public TypeConverter() { } public virtual bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public bool CanConvertFrom(System.Type sourceType) { return default(bool); } public virtual bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public bool CanConvertTo(System.Type destinationType) { return default(bool); } public virtual object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public object ConvertFrom(object value) { return default(object); } public object ConvertFromInvariantString(string text) { return default(object); } public object ConvertFromString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, string text) { return default(object); } public object ConvertFromString(string text) { return default(object); } public virtual object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } public object ConvertTo(object value, System.Type destinationType) { return default(object); } public string ConvertToInvariantString(object value) { return default(string); } public string ConvertToString(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(string); } public string ConvertToString(object value) { return default(string); } protected System.Exception GetConvertFromException(object value) { return default(System.Exception); } protected System.Exception GetConvertToException(object value, System.Type destinationType) { return default(System.Exception); } } [System.AttributeUsageAttribute((System.AttributeTargets)(32767))] public sealed partial class TypeConverterAttribute : System.Attribute { public TypeConverterAttribute(string typeName) { } public TypeConverterAttribute(System.Type type) { } public string ConverterTypeName { get { return default(string); } } public override bool Equals(object obj) { return default(bool); } public override int GetHashCode() { return default(int); } } public sealed partial class TypeDescriptor { internal TypeDescriptor() { } public static System.ComponentModel.TypeConverter GetConverter(System.Type type) { return default(System.ComponentModel.TypeConverter); } } public abstract partial class TypeListConverter : System.ComponentModel.TypeConverter { protected TypeListConverter(System.Type[] types) { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } public partial class UInt16Converter : System.ComponentModel.BaseNumberConverter { public UInt16Converter() { } } public partial class UInt32Converter : System.ComponentModel.BaseNumberConverter { public UInt32Converter() { } } public partial class UInt64Converter : System.ComponentModel.BaseNumberConverter { public UInt64Converter() { } } } namespace System { public partial class UriTypeConverter : System.ComponentModel.TypeConverter { public UriTypeConverter() { } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type sourceType) { return default(bool); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return default(bool); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return default(object); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { return default(object); } } }
using System; using System.Globalization; using System.Text; using Google.GData.Client; namespace Google.GData.Analytics { /// <summary> /// A subclass of FeedQuery, to create an Analytics Data query URI. /// </summary> public class DataQuery : FeedQuery { public const string dataFeedUrl = "https://www.google.com/analytics/feeds/data"; /// <summary> Row keys.</summary> private string dimensions; /// <summary> Last day for which to retrieve data in form YYYY-MM-DD.</summary> private string endDate; /// <summary> Dimension value filters.</summary> private string filters; /// <summary> Google Analytics profile ID, prefixed by 'ga:'.</summary> private string ids; /// <summary> Comma separated list of numeric value fields.</summary> private string metrics; /// <summary> Optional. Adds extra whitespace to the feed XML to make it more readable.</summary> private bool? prettyPrint; /// <summary> Advanced Segment, either dynamic or by index</summary> private string segment; /// <summary> Comma separated list of sort keys in order of importance.</summary> private string sort; /// <summary> First day for which to retrieve data in form YYYY-MM-DD.</summary> private string startDate; /// <summary> /// default constructor, constructs a query to the default analytics feed with no parameters /// </summary> public DataQuery() : base(dataFeedUrl) { } /// <summary> /// base constructor, with initial queryUri /// </summary> /// <param name="queryUri">the query to use</param> public DataQuery(string queryUri) : base(queryUri) { } /// <summary> /// overloaded constructor /// </summary> /// <param name="ids">the account id</param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public DataQuery(string id, DateTime startDate, DateTime endDate) : base(dataFeedUrl) { Ids = id; GAStartDate = startDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); GAEndDate = endDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); } /// <summary> /// overloaded constructor /// </summary> /// <param name="ids">the account id</param> /// <param name="metric"></param> /// <param name="dimension"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <returns></returns> public DataQuery(string id, DateTime startDate, DateTime endDate, string metric, string dimension) : this(id, startDate, endDate) { Metrics = metric; Dimensions = dimension; } /// <summary> /// overloaded constructor /// </summary> /// <param name="ids">the account id</param> /// <param name="metric"></param> /// <param name="dimension"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="sorting"></param> /// <returns></returns> public DataQuery(string id, DateTime startDate, DateTime endDate, string metric, string dimension, string sorting) : this(id, startDate, endDate, metric, dimension) { Sort = sorting; } /// <summary> /// overloaded constructor /// </summary> /// <param name="ids">the account id</param> /// <param name="metric"></param> /// <param name="dimension"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="sorting"></param> /// <param name="filters"></param> /// <returns></returns> public DataQuery(string id, DateTime startDate, DateTime endDate, string metric, string dimension, string sorting, string filters) : this(id, startDate, endDate, metric, dimension, sorting) { Filters = filters; } /// <summary> /// overloaded constructor /// </summary> /// <param name="ids">the account id</param> /// <param name="metric"></param> /// <param name="dimension"></param> /// <param name="startDate"></param> /// <param name="endDate"></param> /// <param name="sorting"></param> /// <param name="filters"></param> /// <returns></returns> public DataQuery(string id, DateTime startDate, DateTime endDate, string metric, string dimension, string sorting, string filters, string segment) : this(id, startDate, endDate, metric, dimension, sorting, filters) { Segment = segment; } /// <summary>The primary data keys from which Analytics reports /// are constructed. Like metrics, dimensions are also categorized by type. /// For example, ga:pageTitle and ga:page are two Content report dimensions /// and ga:browser, ga:city, and ga:pageDepth are two visitor dimensions.</summary> /// <returns>Dimensions</returns> public string Dimensions { get { return dimensions; } set { dimensions = value; } } /// <summary>Indicates the last day for which to retrieve data /// in form YYYY-MM-DD.</summary> /// <returns>EndDate</returns> public string GAEndDate { get { return endDate; } set { endDate = value; } } /// <summary>Indicates the dimension value filters.</summary> /// <returns>Filters</returns> public string Filters { get { return filters; } set { filters = value; } } /// <summary>Indicates the Segments.</summary> /// <returns>Segments</returns> public string Segment { get { return segment; } set { segment = value; } } /// <summary>Indicates the Google Analytics profile ID, /// prefixed by 'ga:'.</summary> /// <returns>Ids</returns> public string Ids { get { return ids; } set { ids = value; } } /// <summary>Indicates the comma separated list of numeric value /// fields.The aggregated statistics for user activity in a profile, /// categorized by type. Examples of metrics include ga:clicks or ga:pageviews. /// When queried by themselves, metrics provide an aggregate measure of user /// activity for your profile, such as overall page views or bounce rate. /// However, when paired with dimensions, they provide information in the context /// of the dimension. For example, when pageviews are combined with /// ga:countryOrTerritory, you see how many pageviews come from each country.</summary> /// <returns>Metrics</returns> public string Metrics { get { return metrics; } set { metrics = value; } } /// <summary>Indicates the comma separated list of sort keys /// in order of importance.</summary> /// <returns>Sort</returns> public string Sort { get { return sort; } set { sort = value; } } /// <summary>Indicates the first day for which to retrieve data /// in form YYYY-MM-DD.</summary> /// <returns>StartDate</returns> public string GAStartDate { get { return startDate; } set { startDate = value; } } /// <summary>Adds extra whitespace to the feed XML to make it /// more readable. This can be set to true or false, where the /// default is false.</summary> /// <returns>PrettyPrint</returns> public bool? PrettyPrint { get { return prettyPrint; } set { prettyPrint = value; } } /// <summary>protected void ParseUri</summary> /// <param name="targetUri">takes an incoming Uri string and parses /// all the properties out of it</param> /// <returns>throws a query exception when it finds something /// wrong with the input, otherwise returns a baseuri</returns> protected override Uri ParseUri(Uri targetUri) { base.ParseUri(targetUri); if (targetUri != null) { char[] deli = {'?', '&'}; string source = HttpUtility.UrlDecode(targetUri.Query); TokenCollection tokens = new TokenCollection(source, deli); foreach (string token in tokens) { if (token.Length > 0) { char[] otherDeli = {'='}; string[] parameters = token.Split(otherDeli, 2); switch (parameters[0]) { case "dimensions": dimensions = parameters[1]; break; case "end-date": endDate = parameters[1]; break; case "filters": filters = parameters[1]; break; case "segment": segment = parameters[1]; break; case "ids": ids = parameters[1]; break; case "metrics": metrics = parameters[1]; break; case "sort": sort = parameters[1]; break; case "start-date": startDate = parameters[1]; break; case "prettyprint": prettyPrint = bool.Parse(parameters[1]); break; } } } } return Uri; } /// <summary>Creates the partial URI query string based on all /// set properties.</summary> /// <returns> string => the query part of the URI </returns> protected override string CalculateQuery(string basePath) { string path = base.CalculateQuery(basePath); StringBuilder newPath = new StringBuilder(path, 2048); char paramInsertion = InsertionParameter(path); paramInsertion = AppendQueryPart(Dimensions, "dimensions", paramInsertion, newPath); paramInsertion = AppendQueryPart(GAEndDate, "end-date", paramInsertion, newPath); paramInsertion = AppendQueryPart(Filters, "filters", paramInsertion, newPath); paramInsertion = AppendQueryPart(Ids, "ids", paramInsertion, newPath); paramInsertion = AppendQueryPart(Metrics, "metrics", paramInsertion, newPath); paramInsertion = AppendQueryPart(Sort, "sort", paramInsertion, newPath); paramInsertion = AppendQueryPart(GAStartDate, "start-date", paramInsertion, newPath); paramInsertion = AppendQueryPart(Segment, "segment", paramInsertion, newPath); if (PrettyPrint.HasValue && (bool) PrettyPrint) { paramInsertion = AppendQueryPart("true", "prettyprint", paramInsertion, newPath); } return newPath.ToString(); } } }
// Copyright 2008-2009 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using Spark.Compiler; using NUnit.Framework; using Spark.Compiler.CSharp; using Spark.Tests.Models; using Spark.Tests.Stubs; namespace Spark.Tests.Compiler { [TestFixture] public class CSharpViewCompilerTester { [SetUp] public void Init() { } private static void DoCompileView(ViewCompiler compiler, IList<Chunk> chunks) { compiler.CompileView(new[] { chunks }, new[] { chunks }); } [Test] public void MakeAndCompile() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new[] { new SendLiteralChunk { Text = "hello world" } }); var instance = compiler.CreateInstance(); string contents = instance.RenderView(); Assert.That(contents.Contains("hello world")); } [Test] public void UnsafeLiteralCharacters() { var text = "hello\t\r\n\"world"; var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new[] { new SendLiteralChunk { Text = text } }); Assert.That(compiler.SourceCode.Contains("Write(\"hello\\t\\r\\n\\\"world\")")); var instance = compiler.CreateInstance(); string contents = instance.RenderView(); Assert.AreEqual(text, contents); } [Test] public void SimpleOutput() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new[] { new SendExpressionChunk { Code = "3 + 4" } }); var instance = compiler.CreateInstance(); string contents = instance.RenderView(); Assert.AreEqual("7", contents); } [Test] public void LocalVariableDecl() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new Chunk[] { new LocalVariableChunk { Name = "i", Value = "5" }, new SendExpressionChunk { Code = "i" } }); var instance = compiler.CreateInstance(); string contents = instance.RenderView(); Assert.AreEqual("5", contents); } [Test] public void ForEachLoop() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new Chunk[] { new LocalVariableChunk {Name = "data", Value = "new[]{3,4,5}"}, new SendLiteralChunk {Text = "<ul>"}, new ForEachChunk { Code = "var item in data", Body = new Chunk[] { new SendLiteralChunk {Text = "<li>"}, new SendExpressionChunk {Code = "item"}, new SendLiteralChunk {Text = "</li>"} } }, new SendLiteralChunk {Text = "</ul>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<ul><li>3</li><li>4</li><li>5</li></ul>", contents); } [Test] public void GlobalVariables() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; DoCompileView(compiler, new Chunk[] { new SendExpressionChunk{Code="title"}, new AssignVariableChunk{ Name="item", Value="8"}, new SendLiteralChunk{ Text=":"}, new SendExpressionChunk{Code="item"}, new GlobalVariableChunk{ Name="title", Value="\"hello world\""}, new GlobalVariableChunk{ Name="item", Value="3"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("hello world:8", contents); } [Test] public void TargetNamespace() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase", Descriptor = new SparkViewDescriptor { TargetNamespace = "Testing.Target.Namespace" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk { Text = "Hello" } }); var instance = compiler.CreateInstance(); Assert.AreEqual("Testing.Target.Namespace", instance.GetType().Namespace); } [Test] public void ProvideFullException() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; Assert.That(() => DoCompileView(compiler, new Chunk[] { new SendExpressionChunk {Code = "NoSuchVariable"} }), Throws.TypeOf<BatchCompilerException>()); } [Test] public void IfTrueCondition() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk {Text = "<p>"}, new LocalVariableChunk{Name="arg", Value="5"}, new ConditionalChunk{Type=ConditionalType.If, Condition="arg==5", Body=trueChunks}, new SendLiteralChunk {Text = "</p>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<p>wastrue</p>", contents); } [Test] public void IfFalseCondition() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk {Text = "<p>"}, new LocalVariableChunk{Name="arg", Value="5"}, new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, new SendLiteralChunk {Text = "</p>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<p></p>", contents); } [Test] public void IfElseFalseCondition() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; var falseChunks = new Chunk[] { new SendLiteralChunk { Text = "wasfalse" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk {Text = "<p>"}, new LocalVariableChunk{Name="arg", Value="5"}, new ConditionalChunk{Type=ConditionalType.If, Condition="arg==6", Body=trueChunks}, new ConditionalChunk{Type=ConditionalType.Else, Body=falseChunks}, new SendLiteralChunk {Text = "</p>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<p>wasfalse</p>", contents); } [Test] public void UnlessTrueCondition() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk {Text = "<p>"}, new LocalVariableChunk{Name="arg", Value="5"}, new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==5", Body=trueChunks}, new SendLiteralChunk {Text = "</p>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<p></p>", contents); } [Test] public void UnlessFalseCondition() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var trueChunks = new Chunk[] { new SendLiteralChunk { Text = "wastrue" } }; DoCompileView(compiler, new Chunk[] { new SendLiteralChunk {Text = "<p>"}, new LocalVariableChunk{Name="arg", Value="5"}, new ConditionalChunk{Type=ConditionalType.Unless, Condition="arg==6", Body=trueChunks}, new SendLiteralChunk {Text = "</p>"} }); var instance = compiler.CreateInstance(); var contents = instance.RenderView(); Assert.AreEqual("<p>wastrue</p>", contents); } [Test] public void LenientSilentNullDoesNotCauseWarningCS0168() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Lenient }; var chunks = new Chunk[] { new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, new SendExpressionChunk {Code = "comment.Text", SilentNulls = true} }; compiler.CompileView(new[] { chunks }, new[] { chunks }); Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); } [Test] public void LenientOutputNullDoesNotCauseWarningCS0168() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Lenient }; var chunks = new Chunk[] { new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} }; compiler.CompileView(new[] { chunks }, new[] { chunks }); Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException)")); } [Test] public void StrictNullUsesException() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Strict }; var chunks = new Chunk[] { new ViewDataChunk { Name="comment", Type="Spark.Tests.Models.Comment"}, new SendExpressionChunk {Code = "comment.Text", SilentNulls = false} }; compiler.CompileView(new[] { chunks }, new[] { chunks }); Assert.That(compiler.SourceCode.Contains("catch(System.NullReferenceException ex)")); Assert.That(compiler.SourceCode.Contains("ArgumentNullException(")); Assert.That(compiler.SourceCode.Contains(", ex);")); } [Test] public void PageBaseTypeOverridesBaseClass() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Strict }; DoCompileView(compiler, new Chunk[] { new PageBaseTypeChunk { BaseClass="Spark.Tests.Stubs.StubSparkView2"}, new SendLiteralChunk{ Text = "Hello world"} }); var instance = compiler.CreateInstance(); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); } [Test] public void PageBaseTypeWorksWithOptionalModel() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Strict }; DoCompileView(compiler, new Chunk[] { new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView2"}, new ViewDataModelChunk {TModel = "Spark.Tests.Models.Comment"}, new SendLiteralChunk {Text = "Hello world"} }); var instance = compiler.CreateInstance(); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2<Comment>))); } [Test] public void PageBaseTypeWorksWithGenericParametersIncluded() { var compiler = new CSharpViewCompiler() { BaseClass = "Spark.Tests.Stubs.StubSparkView", NullBehaviour = NullBehaviour.Strict }; DoCompileView(compiler, new Chunk[] { new PageBaseTypeChunk {BaseClass = "Spark.Tests.Stubs.StubSparkView3<Spark.Tests.Models.Comment, string>"}, new SendLiteralChunk {Text = "Hello world"} }); var instance = compiler.CreateInstance(); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2))); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView2<Comment>))); Assert.That(instance, Is.InstanceOf(typeof(StubSparkView3<Comment, string>))); } [Test] public void Markdown() { var compiler = new CSharpViewCompiler { BaseClass = "Spark.SparkViewBase" }; var innerChunks = new Chunk[] { new SendLiteralChunk { Text = "*test*" } }; DoCompileView(compiler, new Chunk[] { new MarkdownChunk {Body = innerChunks} }); Assert.That(compiler.SourceCode, Is.StringContaining("using(MarkdownOutputScope())")); Assert.That(compiler.SourceCode, Is.StringContaining("Output.Write(\"*test*\");")); var instance = compiler.CreateInstance(); var contents = instance.RenderView().Trim(); Assert.That(contents, Is.EqualTo("<p><em>test</em></p>")); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ServiceStack.Extensions; using ServiceStack.IO; using ServiceStack.Text; namespace ServiceStack.Script { public class SharpPage { /// <summary> /// Whether to evaluate as Template block or code block /// </summary> public ScriptLanguage ScriptLanguage { get; set; } public IVirtualFile File { get; } public ReadOnlyMemory<char> FileContents { get; private set; } public ReadOnlyMemory<char> BodyContents { get; private set; } public Dictionary<string, object> Args { get; protected set; } public SharpPage LayoutPage { get; set; } public PageFragment[] PageFragments { get; set; } public DateTime LastModified { get; set; } public DateTime LastModifiedCheck { get; private set; } public bool HasInit { get; private set; } public bool IsLayout { get; private set; } public bool IsImmutable { get; private set; } public ScriptContext Context { get; } public PageFormat Format { get; } private readonly object semaphore = new object(); public bool IsTempFile => File.Directory.VirtualPath == ScriptConstants.TempFilePath; public string VirtualPath => IsTempFile ? "{temp file}" : File.VirtualPath; public SharpPage(ScriptContext context, IVirtualFile file, PageFormat format=null) { Context = context ?? throw new ArgumentNullException(nameof(context)); ScriptLanguage = context.DefaultScriptLanguage; File = file ?? throw new ArgumentNullException(nameof(file)); Format = format ?? Context.GetFormat(File.Extension); if (Format == null) throw new ArgumentException($"File with extension '{File.Extension}' is not a registered PageFormat in Context.PageFormats", nameof(file)); } public SharpPage(ScriptContext context, PageFragment[] body) { Context = context ?? throw new ArgumentNullException(nameof(context)); PageFragments = body ?? throw new ArgumentNullException(nameof(body)); Format = Context.PageFormats[0]; ScriptLanguage = context.DefaultScriptLanguage; Args = TypeConstants.EmptyObjectDictionary; File = context.EmptyFile; HasInit = true; IsImmutable = true; } public virtual async Task<SharpPage> Init() { if (IsImmutable) return this; if (HasInit) { var skipCheck = !Context.DebugMode && (Context.CheckForModifiedPagesAfter != null ? DateTime.UtcNow - LastModifiedCheck < Context.CheckForModifiedPagesAfter.Value : !Context.CheckForModifiedPages) && (Context.InvalidateCachesBefore == null || LastModifiedCheck > Context.InvalidateCachesBefore.Value); if (skipCheck) return this; File.Refresh(); LastModifiedCheck = DateTime.UtcNow; if (File.LastModified == LastModified) return this; } return await Load(); } public async Task<SharpPage> Load() { if (IsImmutable) return this; string contents; using (var stream = File.OpenRead()) { contents = await stream.ReadToEndAsync(); } foreach (var preprocessor in Context.Preprocessors) { contents = preprocessor(contents); } var lastModified = File.LastModified; var fileContents = contents.AsMemory(); var pageVars = new Dictionary<string, object>(); var pos = 0; var bodyContents = fileContents; fileContents.AdvancePastWhitespace().TryReadLine(out ReadOnlyMemory<char> line, ref pos); var lineComment = ScriptLanguage.LineComment; if (line.StartsWith(Format.ArgsPrefix) || (lineComment != null && line.StartsWith(lineComment + Format.ArgsPrefix))) { while (fileContents.TryReadLine(out line, ref pos)) { if (line.Trim().Length == 0) continue; if (line.StartsWith(Format.ArgsSuffix) || (lineComment != null && line.StartsWith(lineComment + Format.ArgsSuffix))) break; if (lineComment != null && line.StartsWith(lineComment)) line = line.Slice(lineComment.Length).TrimStart(); var colonPos = line.IndexOf(':'); var spacePos = line.IndexOf(' '); var bracePos = line.IndexOf('{'); var sep = colonPos >= 0 ? ':' : ' '; if (bracePos > 0 && spacePos > 0 && colonPos > spacePos) sep = ' '; line.SplitOnFirst(sep, out var first, out var last); var key = first.Trim().ToString(); pageVars[key] = !last.IsEmpty ? last.Trim().ToString() : ""; } //When page has variables body starts from first non whitespace after variables end var argsSuffixPos = line.LastIndexOf(Format.ArgsSuffix); if (argsSuffixPos >= 0) { //Start back from the end of the ArgsSuffix pos -= line.Length - argsSuffixPos - Format.ArgsSuffix.Length; } bodyContents = fileContents.SafeSlice(pos).AdvancePastWhitespace(); } var pageFragments = pageVars.TryGetValue("ignore", out object ignore) && ("page".Equals(ignore.ToString()) || "template".Equals(ignore.ToString())) ? new List<PageFragment> { new PageStringFragment(bodyContents) } : ScriptLanguage.Parse(Context, bodyContents); foreach (var fragment in pageFragments) { if (fragment is PageVariableFragment var && var.Binding == ScriptConstants.Page) { IsLayout = true; break; } } lock (semaphore) { LastModified = lastModified; LastModifiedCheck = DateTime.UtcNow; FileContents = fileContents; Args = pageVars; BodyContents = bodyContents; PageFragments = pageFragments.ToArray(); HasInit = true; LayoutPage = Format.ResolveLayout(this); } if (LayoutPage != null) { if (!LayoutPage.HasInit) { await LayoutPage.Load(); } else { if (Context.DebugMode || Context.CheckForModifiedPagesAfter != null && DateTime.UtcNow - LayoutPage.LastModifiedCheck >= Context.CheckForModifiedPagesAfter.Value) { LayoutPage.File.Refresh(); LayoutPage.LastModifiedCheck = DateTime.UtcNow; if (LayoutPage.File.LastModified != LayoutPage.LastModified) await LayoutPage.Load(); } } } return this; } } public class SharpPartialPage : SharpPage { private static readonly MemoryVirtualFiles TempFiles = new MemoryVirtualFiles(); private static readonly InMemoryVirtualDirectory TempDir = new InMemoryVirtualDirectory(TempFiles, ScriptConstants.TempFilePath); static IVirtualFile CreateFile(string name, string format) => new InMemoryVirtualFile(TempFiles, TempDir) { FilePath = name + "." + format, TextContents = "", }; public SharpPartialPage(ScriptContext context, string name, IEnumerable<PageFragment> body, string format, Dictionary<string,object> args=null) : base(context, CreateFile(name, format), context.GetFormat(format)) { PageFragments = body.ToArray(); Args = args ?? new Dictionary<string, object>(); } public override Task<SharpPage> Init() => ((SharpPage)this).InTask(); } }
// *********************************************************************** // Copyright (c) 2009 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.Collections.Generic; using NUnit.Framework.Internal; using NUnit.Framework.Interfaces; namespace NUnit.Framework.Attributes { public class TestMethodBuilderTests { #region TestAttribute [Test] public void TestAttribute_NoArgs_Runnable() { var method = GetMethod("MethodWithoutArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestAttribute_WithArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); TestMethod test = new TestAttribute().BuildFrom(method, null); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseAttribute [Test] public void TestCaseAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseAttribute(5, 42, 99).BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TestCaseSourceAttribute [Test] public void TestCaseSourceAttribute_NoArgs_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_NoArgs_NoData_NotRunnable() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("ZeroData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(1)); Assert.That(tests[0].RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void TestCaseSourceAttribute_RightArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("GoodData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void TestCaseSourceAttribute_WrongArgs_NotRunnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TestCaseSourceAttribute("BadData").BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } #endregion #region TheoryAttribute [Test] public void TheoryAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void TheoryAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntArgs"); List<TestMethod> tests = new List<TestMethod>(new TheoryAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(9)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void CombinatorialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new CombinatorialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void PairwiseAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new PairwiseAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(6)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region SequentialAttribute [Test] public void SequentialAttribute_NoArgs_NoCases() { var method = GetMethod("MethodWithoutArgs"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(0)); } [Test] public void SequentialAttribute_WithArgs_Runnable() { var method = GetMethod("MethodWithIntValues"); List<TestMethod> tests = new List<TestMethod>(new SequentialAttribute().BuildFrom(method, null)); Assert.That(tests.Count, Is.EqualTo(3)); foreach (var test in tests) Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region Helper Methods and Data private FixtureMethod GetMethod(string methodName) { return GetType().GetFixtureMethod(methodName); } public static void MethodWithoutArgs() { } public static void MethodWithIntArgs(int x, int y) { } public static void MethodWithIntValues( [Values(1, 2, 3)]int x, [Values(10, 20)]int y) { } static object[] ZeroData = new object[0]; static object[] GoodData = new object[] { new object[] { 12, 3 }, new object[] { 12, 4 }, new object[] { 12, 6 } }; static object[] BadData = new object[] { new object[] { 12, 3, 4 }, new object[] { 12, 4, 3 }, new object[] { 12, 6, 2 } }; [DatapointSource] int[] ints = new int[] { 1, 2, 3 }; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; internal static class IOInputs { public static bool SupportsSettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } } public static bool SupportsGettingCreationTime { get { return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | RuntimeInformation.IsOSPlatform(OSPlatform.OSX); } } // Max path length (minus trailing \0). Unix values vary system to system; just using really long values here likely to be more than on the average system. public static readonly int MaxPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? 259 : 10000; // Windows specific, this is the maximum length that can be passed using extended syntax. Does not include the trailing \0. public static readonly int MaxExtendedPath = short.MaxValue - 1; // Same as MaxPath on Unix public static readonly int MaxLongPath = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? MaxExtendedPath : MaxPath; // Windows specific, this is the maximum length that can be passed to APIs taking directory names, such as Directory.CreateDirectory & Directory.Move. // Does not include the trailing \0. // We now do the appropriate wrapping to allow creating longer directories. Like MaxPath, this is a legacy restriction. public static readonly int MaxDirectory = 247; public const int MaxComponent = 255; public const string ExtendedPrefix = @"\\?\"; public const string ExtendedUncPrefix = @"\\?\UNC\"; public static IEnumerable<string> GetValidPathComponentNames() { yield return Path.GetRandomFileName(); yield return "!@#$%^&"; yield return "\x65e5\x672c\x8a9e"; yield return "A"; yield return " A"; yield return " A"; yield return "FileName"; yield return "FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return " FileName"; yield return " FileName.txt"; yield return "This is a valid component name"; yield return "This is a valid component name.txt"; yield return "V1.0.0.0000"; } // These are the WhiteSpace characters we used to trim for paths: // // (char)0x9, // Horizontal tab '\t' // (char)0xA, // Line feed '\n' // (char)0xB, // Vertical tab '\v' // (char)0xC, // Form feed '\f' // (char)0xD, // Carriage return '\r' // (char)0x20, // Space ' ' // (char)0x85, // Next line '\u0085' // (char)0xA0 // Non breaking space '\u00A0' public static IEnumerable<string> GetControlWhiteSpace() { yield return "\t"; yield return "\t\t"; yield return "\t\t\t"; yield return "\n"; yield return "\n\n"; yield return "\n\n\n"; yield return "\t\n"; yield return "\t\n\t\n"; yield return "\n\t\n"; yield return "\n\t\n\t"; // Add other control chars yield return "\v\f\r"; } public static IEnumerable<string> GetSimpleWhiteSpace() { yield return " "; yield return " "; yield return " "; yield return " "; yield return " "; } /// <summary> /// Whitespace characters that arent in the traditional control set (e.g. less than 0x20) /// and aren't space (e.g. 0x20). /// </summary> public static IEnumerable<string> GetNonControlWhiteSpace() { yield return "\u0085"; // Next Line (.NET used to trim) yield return "\u00A0"; // Non breaking space (.NET used to trim) yield return "\u2028"; // Line separator yield return "\u2029"; // Paragraph separator yield return "\u2003"; // EM space yield return "\u2008"; // Punctuation space } /// <summary> /// Whitespace characters other than space (includes some Unicode whitespace characters we /// did not traditionally trim. /// </summary> public static IEnumerable<string> GetNonSpaceWhiteSpace() { return GetControlWhiteSpace().Concat(GetNonControlWhiteSpace()); } /// <summary> /// This is the Whitespace we used to trim from paths /// </summary> public static IEnumerable<string> GetWhiteSpace() { return GetControlWhiteSpace().Concat(GetSimpleWhiteSpace()); } public static IEnumerable<string> GetUncPathsWithoutShareName() { foreach (char slash in new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar }) { if (!PlatformDetection.IsWindows && slash == '/') // Unc paths must start with '\' on Unix { continue; } string slashes = new string(slash, 2); yield return slashes; yield return slashes + " "; yield return slashes + new string(slash, 5); yield return slashes + "S"; yield return slashes + "S "; yield return slashes + "LOCALHOST"; yield return slashes + "LOCALHOST " + slash; yield return slashes + "LOCALHOST " + new string(slash, 2); yield return slashes + "LOCALHOST" + slash + " "; yield return slashes + "LOCALHOST" + slash + slash + " "; } } public static IEnumerable<string> GetPathsWithReservedDeviceNames() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); foreach (string deviceName in GetReservedDeviceNames()) { yield return deviceName; yield return Path.Combine(root, deviceName); yield return Path.Combine(root, "Directory", deviceName); yield return Path.Combine(new string(Path.DirectorySeparatorChar, 2), "LOCALHOST", deviceName); } } public static IEnumerable<string> GetPathsWithColons() { yield return @"AA:"; yield return @"AAA:"; yield return @"AA:A"; yield return @"AAA:A"; yield return @"AA:AA"; yield return @"AAA:AA"; yield return @"AA:AAA"; yield return @"AAA:AAA"; yield return @"AA:FileName"; yield return @"AAA:FileName"; yield return @"AA:FileName.txt"; yield return @"AAA:FileName.txt"; yield return @"A:FileName.txt:"; yield return @"AA:FileName.txt:AA"; yield return @"AAA:FileName.txt:AAA"; yield return @"C:\:"; yield return @"C:\:FileName"; yield return @"C:\:FileName.txt"; yield return @"C:\fileName:"; yield return @"C:\fileName:FileName.txt"; yield return @"C:\fileName:FileName.txt:"; yield return @"C:\fileName:FileName.txt:AA"; yield return @"C:\fileName:FileName.txt:AAA"; yield return @"ftp://fileName:FileName.txt:AAA"; } public static IEnumerable<string> GetPathsWithComponentLongerThanMaxComponent() { // While paths themselves can be up to and including 32,000 characters, most volumes // limit each component of the path to a total of 255 characters. string component = new string('s', MaxComponent + 1); yield return string.Format(@"C:\{0}", component); yield return string.Format(@"C:\{0}\Filename.txt", component); yield return string.Format(@"C:\{0}\Filename.txt\", component); yield return string.Format(@"\\{0}\Share", component); yield return string.Format(@"\\LOCALHOST\{0}", component); yield return string.Format(@"\\LOCALHOST\{0}\FileName.txt", component); yield return string.Format(@"\\LOCALHOST\Share\{0}", component); } public static IEnumerable<string> GetPathsLongerThanMaxDirectory(string rootPath) { yield return GetLongPath(rootPath, MaxDirectory + 1); yield return GetLongPath(rootPath, MaxDirectory + 2); yield return GetLongPath(rootPath, MaxDirectory + 3); } public static IEnumerable<string> GetPathsLongerThanMaxPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 2, useExtendedSyntax); yield return GetLongPath(rootPath, MaxPath + 3, useExtendedSyntax); } public static IEnumerable<string> GetPathsLongerThanMaxLongPath(string rootPath, bool useExtendedSyntax = false) { yield return GetLongPath(rootPath, MaxExtendedPath + 1, useExtendedSyntax); yield return GetLongPath(rootPath, MaxExtendedPath + 2, useExtendedSyntax); } private static string GetLongPath(string rootPath, int characterCount, bool extended = false) { return IOServices.GetPath(rootPath, characterCount, extended); } public static IEnumerable<string> GetReservedDeviceNames() { // See: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file yield return "CON"; yield return "AUX"; yield return "NUL"; yield return "PRN"; yield return "COM1"; yield return "COM2"; yield return "COM3"; yield return "COM4"; yield return "COM5"; yield return "COM6"; yield return "COM7"; yield return "COM8"; yield return "COM9"; yield return "LPT1"; yield return "LPT2"; yield return "LPT3"; yield return "LPT4"; yield return "LPT5"; yield return "LPT6"; yield return "LPT7"; yield return "LPT8"; yield return "LPT9"; } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Linq; using System.Net; using System.Net.Sockets; using System.Net.NetworkInformation; using System.Runtime.CompilerServices; using System.Xml; using System.Data; using System.Collections.Specialized; using System.Collections.Generic; using System.Text; using WebsitePanel.Providers.Common; using WebsitePanel.Providers.EnterpriseStorage; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.OS; using WebsitePanel.Providers.RemoteDesktopServices; using WebsitePanel.Providers.Web; using System.Net.Mail; using System.Collections; using WebsitePanel.EnterpriseServer.Base.RDS; namespace WebsitePanel.EnterpriseServer { public class RemoteDesktopServicesController { private RemoteDesktopServicesController() { } public static int GetRemoteDesktopServiceId(int itemId) { return GetRdsServiceId(itemId); } public static RdsCollection GetRdsCollection(int collectionId) { return GetRdsCollectionInternal(collectionId); } public static RdsCollectionSettings GetRdsCollectionSettings(int collectionId) { return GetRdsCollectionSettingsInternal(collectionId); } public static List<RdsCollection> GetOrganizationRdsCollections(int itemId) { return GetOrganizationRdsCollectionsInternal(itemId); } public static int AddRdsCollection(int itemId, RdsCollection collection) { return AddRdsCollectionInternal(itemId, collection); } public static ResultObject EditRdsCollection(int itemId, RdsCollection collection) { return EditRdsCollectionInternal(itemId, collection); } public static ResultObject EditRdsCollectionSettings(int itemId, RdsCollection collection) { return EditRdsCollectionSettingsInternal(itemId, collection); } public static RdsCollectionPaged GetRdsCollectionsPaged(int itemId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return GetRdsCollectionsPagedInternal(itemId, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static ResultObject RemoveRdsCollection(int itemId, RdsCollection collection) { return RemoveRdsCollectionInternal(itemId, collection); } public static List<StartMenuApp> GetAvailableRemoteApplications(int itemId, string collectionName) { return GetAvailableRemoteApplicationsInternal(itemId, collectionName); } public static RdsServersPaged GetRdsServersPaged(string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return GetRdsServersPagedInternal(filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static List<RdsUserSession> GetRdsUserSessions(int collectionId) { return GetRdsUserSessionsInternal(collectionId); } public static RdsServersPaged GetFreeRdsServersPaged(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return GetFreeRdsServersPagedInternal(packageId, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static RdsServersPaged GetOrganizationRdsServersPaged(int itemId, int? collectionId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return GetOrganizationRdsServersPagedInternal(itemId, collectionId, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static RdsServersPaged GetOrganizationFreeRdsServersPaged(int itemId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return GetOrganizationFreeRdsServersPagedInternal(itemId, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static RdsServer GetRdsServer(int rdsSeverId) { return GetRdsServerInternal(rdsSeverId); } public static ResultObject SetRDServerNewConnectionAllowed(int itemId, bool newConnectionAllowed, int rdsSeverId) { return SetRDServerNewConnectionAllowedInternal(itemId, newConnectionAllowed, rdsSeverId); } public static List<RdsServer> GetCollectionRdsServers(int collectionId) { return GetCollectionRdsServersInternal(collectionId); } public static List<RdsServer> GetOrganizationRdsServers(int itemId) { return GetOrganizationRdsServersInternal(itemId); } public static ResultObject AddRdsServer(RdsServer rdsServer) { return AddRdsServerInternal(rdsServer); } public static ResultObject AddRdsServerToCollection(int itemId, RdsServer rdsServer, RdsCollection rdsCollection) { return AddRdsServerToCollectionInternal(itemId, rdsServer, rdsCollection); } public static ResultObject AddRdsServerToOrganization(int itemId, int serverId) { return AddRdsServerToOrganizationInternal(itemId, serverId); } public static ResultObject RemoveRdsServer(int rdsServerId) { return RemoveRdsServerInternal(rdsServerId); } public static ResultObject RemoveRdsServerFromCollection(int itemId, RdsServer rdsServer, RdsCollection rdsCollection) { return RemoveRdsServerFromCollectionInternal(itemId, rdsServer, rdsCollection); } public static ResultObject RemoveRdsServerFromOrganization(int itemId, int rdsServerId) { return RemoveRdsServerFromOrganizationInternal(itemId, rdsServerId); } public static ResultObject UpdateRdsServer(RdsServer rdsServer) { return UpdateRdsServerInternal(rdsServer); } public static List<OrganizationUser> GetRdsCollectionUsers(int collectionId) { return GetRdsCollectionUsersInternal(collectionId); } public static ResultObject SetUsersToRdsCollection(int itemId, int collectionId, List<OrganizationUser> users) { return SetUsersToRdsCollectionInternal(itemId, collectionId, users); } public static ResultObject AddRemoteApplicationToCollection(int itemId, RdsCollection collection, RemoteApplication application) { return AddRemoteApplicationToCollectionInternal(itemId, collection, application); } public static List<RemoteApplication> GetCollectionRemoteApplications(int itemId, string collectionName) { return GetCollectionRemoteApplicationsInternal(itemId, collectionName); } public static ResultObject RemoveRemoteApplicationFromCollection(int itemId, RdsCollection collection, RemoteApplication application) { return RemoveRemoteApplicationFromCollectionInternal(itemId, collection, application); } public static ResultObject SetRemoteApplicationsToRdsCollection(int itemId, int collectionId, List<RemoteApplication> remoteApps) { return SetRemoteApplicationsToRdsCollectionInternal(itemId, collectionId, remoteApps); } public static ResultObject DeleteRemoteDesktopService(int itemId) { return DeleteRemoteDesktopServiceInternal(itemId); } public static int GetOrganizationRdsUsersCount(int itemId) { return GetOrganizationRdsUsersCountInternal(itemId); } public static int GetOrganizationRdsServersCount(int itemId) { return GetOrganizationRdsServersCountInternal(itemId); } public static int GetOrganizationRdsCollectionsCount(int itemId) { return GetOrganizationRdsCollectionsCountInternal(itemId); } public static List<string> GetApplicationUsers(int itemId, int collectionId, RemoteApplication remoteApp) { return GetApplicationUsersInternal(itemId, collectionId, remoteApp); } public static ResultObject SetApplicationUsers(int itemId, int collectionId, RemoteApplication remoteApp, List<string> users) { return SetApplicationUsersInternal(itemId, collectionId, remoteApp, users); } public static ResultObject LogOffRdsUser(int itemId, string unifiedSessionId, string hostServer) { return LogOffRdsUserInternal(itemId, unifiedSessionId, hostServer); } public static List<string> GetRdsCollectionSessionHosts(int collectionId) { return GetRdsCollectionSessionHostsInternal(collectionId); } public static RdsServerInfo GetRdsServerInfo(int? itemId, string fqdnName) { return GetRdsServerInfoInternal(itemId, fqdnName); } public static string GetRdsServerStatus(int? itemId, string fqdnName) { return GetRdsServerStatusInternal(itemId, fqdnName); } public static ResultObject ShutDownRdsServer(int? itemId, string fqdnName) { return ShutDownRdsServerInternal(itemId, fqdnName); } public static ResultObject RestartRdsServer(int? itemId, string fqdnName) { return RestartRdsServerInternal(itemId, fqdnName); } public static List<OrganizationUser> GetRdsCollectionLocalAdmins(int collectionId) { return GetRdsCollectionLocalAdminsInternal(collectionId); } public static ResultObject SaveRdsCollectionLocalAdmins(OrganizationUser[] users, int collectionId) { return SaveRdsCollectionLocalAdminsInternal(users, collectionId); } public static ResultObject InstallSessionHostsCertificate(RdsServer rdsServer) { return InstallSessionHostsCertificateInternal(rdsServer); } public static RdsCertificate GetRdsCertificateByServiceId(int serviceId) { return GetRdsCertificateByServiceIdInternal(serviceId); } public static RdsCertificate GetRdsCertificateByItemId(int? itemId) { return GetRdsCertificateByItemIdInternal(itemId); } public static ResultObject AddRdsCertificate(RdsCertificate certificate) { return AddRdsCertificateInternal(certificate); } public static List<ServiceInfo> GetRdsServices() { return GetRdsServicesInternal(); } public static string GetRdsSetupLetter(int itemId, int? accountId) { return GetRdsSetupLetterInternal(itemId, accountId); } public static int SendRdsSetupLetter(int itemId, int? accountId, string to, string cc) { return SendRdsSetupLetterInternal(itemId, accountId, to, cc); } public static RdsServerSettings GetRdsServerSettings(int serverId, string settingsName) { return GetRdsServerSettingsInternal(serverId, settingsName); } public static int UpdateRdsServerSettings(int serverId, string settingsName, RdsServerSettings settings) { return UpdateRdsServerSettingsInternal(serverId, settingsName, settings); } public static ResultObject ShadowSession(int itemId, string sessionId, bool control, string fqdName) { return ShadowSessionInternal(itemId, sessionId, control, fqdName); } public static ResultObject ImportCollection(int itemId, string collectionName) { return ImportCollectionInternal(itemId, collectionName); } public static ResultObject SendMessage(RdsMessageRecipient[] recipients, string text, int itemId, int rdsCollectionId, string userName) { return SendMessageInternal(recipients, text, itemId, rdsCollectionId, userName); } public static List<RdsMessage> GetRdsMessagesByCollectionId(int rdsCollectionId) { return GetRdsMessagesByCollectionIdInternal(rdsCollectionId); } private static ResultObject SendMessageInternal(RdsMessageRecipient[] recipients, string text, int itemId, int rdsCollectionId, string userName) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SEND_MESSAGE"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("SEND_MESSAGE", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.SendMessage(recipients, text); DataProvider.AddRDSMessage(rdsCollectionId, text, userName); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SHADOW_RDS_SESSION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static List<RdsMessage> GetRdsMessagesByCollectionIdInternal(int rdsCollectionId) { return ObjectUtils.CreateListFromDataSet<RdsMessage>(DataProvider.GetRDSMessagesByCollectionId(rdsCollectionId)); } private static ResultObject ImportCollectionInternal(int itemId, string collectionName) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "IMPORT_RDS_COLLECTION"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("IMPORT_RDS_COLLECTION", new NullReferenceException("Organization not found")); return result; } var existingCollections = GetRdsCollectionsPaged(itemId, "", "", "", 0, Int32.MaxValue).Collections; if (existingCollections.Select(e => e.Name.ToLower()).Contains(collectionName.ToLower())) { result.IsSuccess = false; throw new InvalidOperationException(string.Format("Collection {0} already exists in database", collectionName)); } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var collection = rds.GetExistingCollection(collectionName); var newCollection = new RdsCollection { Name = collection.CollectionName, Description = collection.Description, DisplayName = collection.CollectionName }; newCollection.Id = DataProvider.AddRDSCollection(itemId, newCollection.Name, newCollection.Description, newCollection.DisplayName); newCollection.Settings = RemoteDesktopServicesHelpers.ParseCollectionSettings(collection.CollectionSettings); newCollection.Settings.RdsCollectionId = newCollection.Id; newCollection.Settings.Id = DataProvider.AddRdsCollectionSettings(newCollection.Settings); var existingSessionHosts = GetRdsServersPagedInternal("", "", "", 1, 1000).Servers; RemoteDesktopServicesHelpers.FillSessionHosts(collection.SessionHosts, existingSessionHosts, newCollection.Id, itemId); newCollection.Servers = ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(newCollection.Id)).ToList(); UserInfo user = PackageController.GetPackageOwner(org.PackageId); var organizationUsers = OrganizationController.GetOrganizationUsersPaged(itemId, null, null, null, 0, Int32.MaxValue).PageUsers.Select(u => u.SamAccountName.Split('\\').Last().ToLower()); var newUsers = organizationUsers.Where(x => collection.UserGroups.Select(a => a.PropertyValue.ToString().Split('\\').Last().ToLower()).Contains(x)); rds.ImportCollection(org.OrganizationId, newCollection, newUsers.ToArray()); var emptySettings = RemoteDesktopServicesHelpers.GetEmptyGpoSettings(); string xml = RemoteDesktopServicesHelpers.GetSettingsXml(emptySettings); DataProvider.UpdateRdsServerSettings(newCollection.Id, string.Format("Collection-{0}-Settings", newCollection.Id), xml); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject ShadowSessionInternal(int itemId, string sessionId, bool control, string fqdName) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SHADOW_RDS_SESSION"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("SHADOW_RDS_SESSION", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.ShadowSession(sessionId, fqdName, control); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SHADOW_RDS_SESSION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsServerSettings GetRdsServerSettingsInternal(int serverId, string settingsName) { IDataReader reader = DataProvider.GetRdsServerSettings(serverId, settingsName); var settings = new RdsServerSettings(); settings.ServerId = serverId; settings.SettingsName = settingsName; while (reader.Read()) { settings.Settings.Add(new RdsServerSetting { PropertyName = (string)reader["PropertyName"], PropertyValue = (string)reader["PropertyValue"], ApplyAdministrators = Convert.ToBoolean(reader["ApplyAdministrators"]), ApplyUsers = Convert.ToBoolean(reader["ApplyUsers"]) }); } reader.Close(); return settings; } private static int UpdateRdsServerSettingsInternal(int serverId, string settingsName, RdsServerSettings settings) { TaskManager.StartTask("REMOTE_DESKTOP_SERVICES", "UPDATE_SETTINGS"); try { var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(serverId)); var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(GetRdsServiceId(collection.ItemId)); Organization org = OrganizationController.GetOrganization(collection.ItemId); rds.ApplyGPO(org.OrganizationId, collection.Name, settings); string xml = RemoteDesktopServicesHelpers.GetSettingsXml(settings); DataProvider.UpdateRdsServerSettings(serverId, settingsName, xml); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } private static string GetRdsSetupLetterInternal(int itemId, int? accountId) { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return null; } UserInfo user = PackageController.GetPackageOwner(org.PackageId); UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.RDS_SETUP_LETTER); string settingName = user.HtmlMail ? "HtmlBody" : "TextBody"; string body = settings[settingName]; if (String.IsNullOrEmpty(body)) { return null; } string result = RemoteDesktopServicesHelpers.EvaluateMailboxTemplate(body, org, accountId, itemId); return user.HtmlMail ? result : result.Replace("\n", "<br/>"); } private static int SendRdsSetupLetterInternal(int itemId, int? accountId, string to, string cc) { int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) { return accountCheck; } Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return -1; } UserInfo user = PackageController.GetPackageOwner(org.PackageId); UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.RDS_SETUP_LETTER); string from = settings["From"]; if (cc == null) { cc = settings["CC"]; } string subject = settings["Subject"]; string body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"]; bool isHtml = user.HtmlMail; MailPriority priority = MailPriority.Normal; if (!String.IsNullOrEmpty(settings["Priority"])) { priority = (MailPriority)Enum.Parse(typeof(MailPriority), settings["Priority"], true); } if (String.IsNullOrEmpty(body)) { return 0; } if (to == null) { to = user.Email; } subject = RemoteDesktopServicesHelpers.EvaluateMailboxTemplate(subject, org, accountId, itemId); body = RemoteDesktopServicesHelpers.EvaluateMailboxTemplate(body, org, accountId, itemId); return MailHelper.SendMessage(from, to, cc, subject, body, priority, isHtml); } private static ResultObject InstallSessionHostsCertificateInternal(RdsServer rdsServer) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "INSTALL_CERTIFICATE"); try { int serviceId = GetRdsServiceId(rdsServer.ItemId); var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); var certificate = GetRdsCertificateByServiceIdInternal(serviceId); var array = Convert.FromBase64String(certificate.Hash); char[] chars = new char[array.Length / sizeof(char)]; System.Buffer.BlockCopy(array, 0, chars, 0, array.Length); string password = new string(chars); byte[] content = Convert.FromBase64String(certificate.Content); rds.InstallCertificate(content, password, new string[] {rdsServer.FqdName}); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsCertificate GetRdsCertificateByServiceIdInternal(int serviceId) { var result = ObjectUtils.FillObjectFromDataReader<RdsCertificate>(DataProvider.GetRdsCertificateByServiceId(serviceId)); return result; } private static RdsCertificate GetRdsCertificateByItemIdInternal(int? itemId) { int serviceId = GetRdsServiceId(itemId); var result = ObjectUtils.FillObjectFromDataReader<RdsCertificate>(DataProvider.GetRdsCertificateByServiceId(serviceId)); return result; } private static ResultObject AddRdsCertificateInternal(RdsCertificate certificate) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_RDS_SERVER"); try { byte[] hash = new byte[certificate.Hash.Length * sizeof(char)]; System.Buffer.BlockCopy(certificate.Hash.ToCharArray(), 0, hash, 0, hash.Length); certificate.Id = DataProvider.AddRdsCertificate(certificate.ServiceId, certificate.Content, hash, certificate.FileName, certificate.ValidFrom, certificate.ExpiryDate); } catch (Exception ex) { if (ex.InnerException != null) { result.AddError("Unable to add RDS Certificate", ex.InnerException); } else { result.AddError("Unable to add RDS Certificate", ex); } } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsCollection GetRdsCollectionInternal(int collectionId) { var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); var collectionSettings = ObjectUtils.FillObjectFromDataReader<RdsCollectionSettings>(DataProvider.GetRdsCollectionSettingsByCollectionId(collectionId)); collection.Settings = collectionSettings; var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "GET_RDS_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(collection.ItemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.GetCollection(collection.Name); FillRdsCollection(collection); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_RDS_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return collection; } private static List<OrganizationUser> GetRdsCollectionLocalAdminsInternal(int collectionId) { var result = new List<OrganizationUser>(); var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); var servers = ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(collection.Id)).ToList(); Organization org = OrganizationController.GetOrganization(collection.ItemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var organizationUsers = OrganizationController.GetOrganizationUsersPaged(collection.ItemId, null, null, null, 0, Int32.MaxValue).PageUsers; var organizationAdmins = rds.GetRdsCollectionLocalAdmins(org.OrganizationId, collection.Name); return organizationUsers.Where(o => organizationAdmins.Select(a => a.ToLower()).Contains(o.SamAccountName.ToLower())).ToList(); } private static ResultObject SaveRdsCollectionLocalAdminsInternal(OrganizationUser[] users, int collectionId) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SAVE_LOCAL_ADMINS"); try { var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); Organization org = OrganizationController.GetOrganization(collection.ItemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var servers = ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(collection.Id)).ToList(); rds.SaveRdsCollectionLocalAdmins(users.Select(u => u.AccountName).ToArray(), servers.Select(s => s.FqdName).ToArray(), org.OrganizationId, collection.Name); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsCollectionSettings GetRdsCollectionSettingsInternal(int collectionId) { var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); var settings = ObjectUtils.FillObjectFromDataReader<RdsCollectionSettings>(DataProvider.GetRdsCollectionSettingsByCollectionId(collectionId)); if (settings != null) { if (settings.SecurityLayer == null) { settings.SecurityLayer = SecurityLayerValues.Negotiate.ToString(); } if (settings.EncryptionLevel == null) { settings.EncryptionLevel = EncryptionLevel.ClientCompatible.ToString(); } if (settings.AuthenticateUsingNLA == null) { settings.AuthenticateUsingNLA = true; } } return settings; } private static List<RdsCollection> GetOrganizationRdsCollectionsInternal(int itemId) { var collections = ObjectUtils.CreateListFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionsByItemId(itemId)); foreach (var rdsCollection in collections) { FillRdsCollection(rdsCollection); } return collections; } private static int AddRdsCollectionInternal(int itemId, RdsCollection collection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_RDS_COLLECTION"); var domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return -1; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); foreach(var server in collection.Servers) { if (!server.FqdName.EndsWith(domainName, StringComparison.CurrentCultureIgnoreCase)) { throw TaskManager.WriteError(new Exception("Fully Qualified Domain Name not valid.")); } if (!rds.CheckRDSServerAvaliable(server.FqdName)) { throw TaskManager.WriteError(new Exception(string.Format("Unable to connect to {0} server.", server.FqdName))); } } collection.Name = RemoteDesktopServicesHelpers.GetFormattedCollectionName(collection.DisplayName, org.OrganizationId); collection.Settings = RemoteDesktopServicesHelpers.GetDefaultCollectionSettings(); rds.CreateCollection(org.OrganizationId, collection); var defaultGpoSettings = RemoteDesktopServicesHelpers.GetDefaultGpoSettings(); rds.ApplyGPO(org.OrganizationId, collection.Name, defaultGpoSettings); collection.Id = DataProvider.AddRDSCollection(itemId, collection.Name, collection.Description, collection.DisplayName); string xml = RemoteDesktopServicesHelpers.GetSettingsXml(defaultGpoSettings); DataProvider.UpdateRdsServerSettings(collection.Id, string.Format("Collection-{0}-Settings", collection.Id), xml); collection.Settings.RdsCollectionId = collection.Id; int settingsId = DataProvider.AddRdsCollectionSettings(collection.Settings); collection.Settings.Id = settingsId; foreach (var server in collection.Servers) { DataProvider.AddRDSServerToCollection(server.Id, collection.Id); } } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return collection.Id; } private static ResultObject EditRdsCollectionInternal(int itemId, RdsCollection collection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "EDIT_RDS_COLLECTION"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var existingServers = ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(collection.Id)).ToList(); var removedServers = existingServers.Where(x => !collection.Servers.Select(y => y.Id).Contains(x.Id)); var newServers = collection.Servers.Where(x => !existingServers.Select(y => y.Id).Contains(x.Id)); foreach(var server in removedServers) { DataProvider.RemoveRDSServerFromCollection(server.Id); } rds.AddSessionHostServersToCollection(org.OrganizationId, collection.Name, newServers.ToArray()); rds.MoveSessionHostsToCollectionOU(collection.Servers.ToArray(), collection.Name, org.OrganizationId); foreach (var server in newServers) { DataProvider.AddRDSServerToCollection(server.Id, collection.Id); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_RDS_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject EditRdsCollectionSettingsInternal(int itemId, RdsCollection collection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "EDIT_RDS_COLLECTION_SETTINGS"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.EditRdsCollectionSettings(collection); var collectionSettings = ObjectUtils.FillObjectFromDataReader<RdsCollectionSettings>(DataProvider.GetRdsCollectionSettingsByCollectionId(collection.Id)); if (collectionSettings == null) { DataProvider.AddRdsCollectionSettings(collection.Settings); } else { DataProvider.UpdateRDSCollectionSettings(collection.Settings); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_RDS_COLLECTION", ex); throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsCollectionPaged GetRdsCollectionsPagedInternal(int itemId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { DataSet ds = DataProvider.GetRDSCollectionsPaged(itemId, filterColumn, filterValue, sortColumn, startRow, maximumRows); var result = new RdsCollectionPaged { RecordsCount = (int)ds.Tables[0].Rows[0][0] }; List<RdsCollection> tmpCollections = new List<RdsCollection>(); ObjectUtils.FillCollectionFromDataView(tmpCollections, ds.Tables[1].DefaultView); foreach (var collection in tmpCollections) { collection.Servers = GetCollectionRdsServersInternal(collection.Id); } result.Collections = tmpCollections.ToArray(); return result; } private static ResultObject RemoveRdsCollectionInternal(int itemId, RdsCollection collection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "REMOVE_RDS_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var servers = ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(collection.Id)).ToArray(); rds.RemoveCollection(org.OrganizationId, collection.Name, servers); DataProvider.DeleteRDSServerSettings(collection.Id); DataProvider.DeleteRDSCollection(collection.Id); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_REMOVE_RDS_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static List<StartMenuApp> GetAvailableRemoteApplicationsInternal(int itemId, string collectionName) { var result = new List<StartMenuApp>(); var taskResult = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "GET_AVAILABLE_REMOTE_APPLICATIOBNS"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); result.AddRange(rds.GetAvailableRemoteApplications(collectionName)); } catch (Exception ex) { taskResult.AddError("REMOTE_DESKTOP_SERVICES_ADD_RDS_COLLECTION", ex); } finally { if (!taskResult.IsSuccess) { TaskManager.CompleteResultTask(taskResult); } else { TaskManager.CompleteResultTask(); } } return result; } private static RdsServersPaged GetRdsServersPagedInternal(string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { DataSet ds = DataProvider.GetRDSServersPaged(null, null, filterColumn, filterValue, sortColumn, startRow, maximumRows, true, true); RdsServersPaged result = new RdsServersPaged(); result.RecordsCount = (int)ds.Tables[0].Rows[0][0]; List<RdsServer> tmpServers = new List<RdsServer>(); ObjectUtils.FillCollectionFromDataView(tmpServers, ds.Tables[1].DefaultView); foreach (var tmpServer in tmpServers) { RemoteDesktopServicesHelpers.FillRdsServerData(tmpServer); } result.Servers = tmpServers.ToArray(); return result; } private static List<RdsUserSession> GetRdsUserSessionsInternal(int collectionId) { var result = new List<RdsUserSession>(); var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); var organization = OrganizationController.GetOrganization(collection.ItemId); if (organization == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(organization.PackageId)); var userSessions = rds.GetRdsUserSessions(collection.Name).ToList(); var organizationUsers = OrganizationController.GetOrganizationUsersPaged(collection.ItemId, null, null, null, 0, Int32.MaxValue).PageUsers; foreach(var userSession in userSessions) { var organizationUser = organizationUsers.FirstOrDefault(o => o.SamAccountName.Equals(userSession.SamAccountName, StringComparison.CurrentCultureIgnoreCase)); if (organizationUser != null) { userSession.IsVip = organizationUser.IsVIP; result.Add(userSession); } } return result; } private static RdsServersPaged GetFreeRdsServersPagedInternal(int itemId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { RdsServersPaged result = new RdsServersPaged(); Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var existingServers = rds.GetServersExistingInCollections(); DataSet ds = DataProvider.GetRDSServersPaged(null, null, filterColumn, filterValue, sortColumn, startRow, maximumRows); result.RecordsCount = (int)ds.Tables[0].Rows[0][0]; List<RdsServer> tmpServers = new List<RdsServer>(); ObjectUtils.FillCollectionFromDataView(tmpServers, ds.Tables[1].DefaultView); tmpServers = tmpServers.Where(x => !existingServers.Select(y => y.ToUpper()).Contains(x.FqdName.ToUpper())).ToList(); result.Servers = tmpServers.ToArray(); return result; } private static List<string> GetRdsCollectionSessionHostsInternal(int collectionId) { var result = new List<string>(); var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); Organization org = OrganizationController.GetOrganization(collection.ItemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); result = rds.GetRdsCollectionSessionHosts(collection.Name).ToList(); return result; } private static RdsServersPaged GetOrganizationRdsServersPagedInternal(int itemId, int? collectionId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { DataSet ds = DataProvider.GetRDSServersPaged(itemId, collectionId, filterColumn, filterValue, sortColumn, startRow, maximumRows, ignoreRdsCollectionId: !collectionId.HasValue); RdsServersPaged result = new RdsServersPaged(); result.RecordsCount = (int)ds.Tables[0].Rows[0][0]; List<RdsServer> tmpServers = new List<RdsServer>(); ObjectUtils.FillCollectionFromDataView(tmpServers, ds.Tables[1].DefaultView); result.Servers = tmpServers.ToArray(); return result; } private static RdsServersPaged GetOrganizationFreeRdsServersPagedInternal(int itemId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { DataSet ds = DataProvider.GetRDSServersPaged(itemId, null, filterColumn, filterValue, sortColumn, startRow, maximumRows); RdsServersPaged result = new RdsServersPaged(); result.RecordsCount = (int)ds.Tables[0].Rows[0][0]; List<RdsServer> tmpServers = new List<RdsServer>(); ObjectUtils.FillCollectionFromDataView(tmpServers, ds.Tables[1].DefaultView); result.Servers = tmpServers.ToArray(); return result; } private static RdsServer GetRdsServerInternal(int rdsSeverId) { return ObjectUtils.FillObjectFromDataReader<RdsServer>(DataProvider.GetRDSServerById(rdsSeverId)); } private static ResultObject SetRDServerNewConnectionAllowedInternal(int itemId, bool newConnectionAllowed, int rdsSeverId) { ResultObject result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SET_RDS_SERVER_NEW_CONNECTIONS_ALLOWED"); ; try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var rdsServer = GetRdsServer(rdsSeverId); if (rdsServer == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("RDS Server not found")); return result; } rds.SetRDServerNewConnectionAllowed(newConnectionAllowed, rdsServer); rdsServer.ConnectionEnabled = newConnectionAllowed; DataProvider.UpdateRDSServer(rdsServer); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SET_RDS_SERVER_NEW_CONNECTIONS_ALLOWED", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject AddRdsServerInternal(RdsServer rdsServer) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_RDS_SERVER"); try { int serviceId = GetRdsMainServiceId(); var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); if (rds.CheckRDSServerAvaliable(rdsServer.FqdName)) { var domainName = IPGlobalProperties.GetIPGlobalProperties().DomainName; if (rdsServer.FqdName.EndsWith(domainName, StringComparison.CurrentCultureIgnoreCase)) { rds.AddSessionHostFeatureToServer(rdsServer.FqdName); rds.MoveSessionHostToRdsOU(rdsServer.Name); rdsServer.Id = DataProvider.AddRDSServer(rdsServer.Name, rdsServer.FqdName, rdsServer.Description); } else { throw TaskManager.WriteError(new Exception("Fully Qualified Domain Name not valid.")); } } else { throw TaskManager.WriteError(new Exception(string.Format("Unable to connect to {0} server. Please double check Server Full Name setting and retry.", rdsServer.FqdName))); } } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject AddRdsServerToCollectionInternal(int itemId, RdsServer rdsServer, RdsCollection rdsCollection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_RDS_SERVER_TO_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); if (!rds.CheckSessionHostFeatureInstallation(rdsServer.FqdName)) { rds.AddSessionHostFeatureToServer(rdsServer.FqdName); } rds.AddSessionHostServerToCollection(org.OrganizationId, rdsCollection.Name, rdsServer); DataProvider.AddRDSServerToCollection(rdsServer.Id, rdsCollection.Id); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_RDS_SERVER_TO_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject RemoveRdsServerFromCollectionInternal(int itemId, RdsServer rdsServer, RdsCollection rdsCollection) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "REMOVE_RDS_SERVER_FROM_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.RemoveSessionHostServerFromCollection(org.OrganizationId, rdsCollection.Name, rdsServer); DataProvider.RemoveRDSServerFromCollection(rdsServer.Id); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_REMOVE_RDS_SERVER_FROM_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject UpdateRdsServerInternal(RdsServer rdsServer) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "UPDATE_RDS_SERVER"); try { DataProvider.UpdateRDSServer(rdsServer); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_UPDATE_RDS_SERVER", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject AddRdsServerToOrganizationInternal(int itemId, int serverId) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_RDS_SERVER_TO_ORGANIZATION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); RdsServer rdsServer = GetRdsServer(serverId); rds.MoveRdsServerToTenantOU(rdsServer.FqdName, org.OrganizationId); DataProvider.AddRDSServerToOrganization(itemId, serverId); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject RemoveRdsServerFromOrganizationInternal(int itemId, int rdsServerId) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "REMOVE_RDS_SERVER_FROM_ORGANIZATION"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rdsServer = ObjectUtils.FillObjectFromDataReader<RdsServer>(DataProvider.GetRDSServerById(rdsServerId)); var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.RemoveRdsServerFromTenantOU(rdsServer.FqdName, org.OrganizationId); DataProvider.RemoveRDSServerFromOrganization(rdsServerId); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject RemoveRdsServerInternal(int rdsServerId) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "REMOVE_RDS_SERVER"); try { DataProvider.DeleteRDSServer(rdsServerId); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_REMOVE_RDS_SERVER", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static List<OrganizationUser> GetRdsCollectionUsersInternal(int collectionId) { return ObjectUtils.CreateListFromDataReader<OrganizationUser>(DataProvider.GetRDSCollectionUsersByRDSCollectionId(collectionId)); } private static ResultObject SetUsersToRdsCollectionInternal(int itemId, int collectionId, List<OrganizationUser> users) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_USER_TO_RDS_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var collection = GetRdsCollection(collectionId); if (collection == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Collection not found")); return result; } foreach(var user in users) { var account = OrganizationController.GetAccountByAccountName(itemId, user.AccountName); user.AccountId = account.AccountId; } var usersInDb = GetRdsCollectionUsers(collectionId); var accountNames = users.Select(x => x.AccountName).ToList(); //Set on server rds.SetUsersInCollection(org.OrganizationId, collection.Name, users.Select(x => x.AccountName).ToArray()); //Remove from db foreach (var userInDb in usersInDb) { if (!accountNames.Contains(userInDb.AccountName)) { DataProvider.RemoveRDSUserFromRDSCollection(collectionId, userInDb.AccountId); } } //Add to db foreach (var user in users) { if (!usersInDb.Select(x => x.AccountName).Contains(user.AccountName)) { DataProvider.AddRDSUserToRDSCollection(collectionId, user.AccountId); } } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_USER_TO_RDS_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static List<string> GetApplicationUsersInternal(int itemId, int collectionId, RemoteApplication remoteApp) { var result = new List<string>(); Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); string alias = ""; if (remoteApp != null) { alias = remoteApp.Alias; } var users = rds.GetApplicationUsers(collection.Name, alias); result.AddRange(users); return result; } private static ResultObject SetApplicationUsersInternal(int itemId, int collectionId, RemoteApplication remoteApp, List<string> users) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SET_REMOTE_APP_USERS"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var collection = ObjectUtils.FillObjectFromDataReader<RdsCollection>(DataProvider.GetRDSCollectionById(collectionId)); var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.SetApplicationUsers(collection.Name, remoteApp, users.ToArray()); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SET_REMOTE_APP_USERS", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject LogOffRdsUserInternal(int itemId, string unifiedSessionId, string hostServer) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "LOG_OFF_RDS_USER"); try { Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("LOG_OFF_RDS_USER", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.LogOffRdsUser(unifiedSessionId, hostServer); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_LOG_OFF_RDS_USER", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject AddRemoteApplicationToCollectionInternal(int itemId, RdsCollection collection, RemoteApplication remoteApp) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "ADD_REMOTE_APP_TO_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); if (!string.IsNullOrEmpty(remoteApp.Alias)) { remoteApp.Alias = remoteApp.DisplayName; } remoteApp.ShowInWebAccess = true; rds.AddRemoteApplication(collection.Name, remoteApp); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_ADD_REMOTE_APP_TO_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject ShutDownRdsServerInternal(int? itemId, string fqdnName) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SHUTDOWN_RDS_SERVER"); try { int serviceId = GetRdsServiceId(itemId); if (serviceId != -1) { var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); rds.ShutDownRdsServer(fqdnName); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SHUTDOWN_RDS_SERVER", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject RestartRdsServerInternal(int? itemId, string fqdnName) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "RESTART_RDS_SERVER"); try { int serviceId = GetRdsServiceId(itemId); if (serviceId != -1) { var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); rds.RestartRdsServer(fqdnName); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_RESTART_RDS_SERVER", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static List<RemoteApplication> GetCollectionRemoteApplicationsInternal(int itemId, string collectionName) { var result = new List<RemoteApplication>(); // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); result.AddRange(rds.GetCollectionRemoteApplications(collectionName)); return result; } private static ResultObject RemoveRemoteApplicationFromCollectionInternal(int itemId, RdsCollection collection, RemoteApplication application) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "REMOVE_REMOTE_APP_FROM_COLLECTION"); try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); rds.RemoveRemoteApplication(collection.Name, application); } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_REMOVE_REMOTE_APP_FROM_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject SetRemoteApplicationsToRdsCollectionInternal(int itemId, int collectionId, List<RemoteApplication> remoteApps) { ResultObject result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "SET_APPS_TO_RDS_COLLECTION"); ; try { // load organization Organization org = OrganizationController.GetOrganization(itemId); if (org == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Organization not found")); return result; } var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId)); var collection = GetRdsCollection(collectionId); if (collection == null) { result.IsSuccess = false; result.AddError("", new NullReferenceException("Collection not found")); return result; } List<RemoteApplication> existingCollectionApps = GetCollectionRemoteApplications(itemId, collection.Name); List<RemoteApplication> remoteAppsToAdd = remoteApps.Where(x => !existingCollectionApps.Select(p => p.Alias).Contains(x.Alias)).ToList(); foreach (var app in remoteAppsToAdd) { app.ShowInWebAccess = true; AddRemoteApplicationToCollection(itemId, collection, app); } List<RemoteApplication> remoteAppsToRemove = existingCollectionApps.Where(x => !remoteApps.Select(p => p.Alias).Contains(x.Alias)).ToList(); foreach (var app in remoteAppsToRemove) { RemoveRemoteApplicationFromCollection(itemId, collection, app); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_SET_APPS_TO_RDS_COLLECTION", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static ResultObject DeleteRemoteDesktopServiceInternal(int itemId) { var result = TaskManager.StartResultTask<ResultObject>("REMOTE_DESKTOP_SERVICES", "CLEANUP"); try { var collections = GetOrganizationRdsCollections(itemId); foreach (var collection in collections) { RemoveRdsCollection(itemId, collection); } var servers = GetOrganizationRdsServers(itemId); foreach (var server in servers) { RemoveRdsServerFromOrganization(itemId, server.Id); } } catch (Exception ex) { result.AddError("REMOTE_DESKTOP_SERVICES_CLEANUP", ex); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return result; } private static int GetOrganizationRdsUsersCountInternal(int itemId) { return DataProvider.GetOrganizationRdsUsersCount(itemId); } private static int GetOrganizationRdsServersCountInternal(int itemId) { return DataProvider.GetOrganizationRdsServersCount(itemId); } private static int GetOrganizationRdsCollectionsCountInternal(int itemId) { return DataProvider.GetOrganizationRdsCollectionsCount(itemId); } private static List<RdsServer> GetCollectionRdsServersInternal(int collectionId) { return ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByCollectionId(collectionId)).ToList(); } private static List<RdsServer> GetOrganizationRdsServersInternal(int itemId) { return ObjectUtils.CreateListFromDataReader<RdsServer>(DataProvider.GetRDSServersByItemId(itemId)).ToList(); } private static List<ServiceInfo> GetRdsServicesInternal() { return ObjectUtils.CreateListFromDataSet<ServiceInfo>(DataProvider.GetServicesByGroupName(SecurityContext.User.UserId, ResourceGroups.RDS)); } protected static int GetRdsMainServiceId() { var settings = SystemController.GetSystemSettings(WebsitePanel.EnterpriseServer.SystemSettings.RDS_SETTINGS); if (!string.IsNullOrEmpty(settings["RdsMainController"])) { return Convert.ToInt32(settings["RdsMainController"]); } var rdsServices = GetRdsServicesInternal(); if (rdsServices.Any()) { return rdsServices.First().ServiceId; } return -1; } protected static RdsCollection FillRdsCollection(RdsCollection collection) { collection.Servers = GetCollectionRdsServersInternal(collection.Id) ?? new List<RdsServer>(); return collection; } protected static int GetRdsServiceId(int? itemId) { int serviceId = -1; if (itemId.HasValue) { Organization org = OrganizationController.GetOrganization(itemId.Value); if (org == null) { return serviceId; } serviceId = RemoteDesktopServicesHelpers.GetRemoteDesktopServiceID(org.PackageId); } else { serviceId = GetRdsMainServiceId(); } return serviceId; } private static RdsServerInfo GetRdsServerInfoInternal(int? itemId, string fqdnName) { int serviceId = GetRdsServiceId(itemId); var result = new RdsServerInfo(); if (serviceId != -1) { var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); result = rds.GetRdsServerInfo(fqdnName); } return result; } private static string GetRdsServerStatusInternal(int? itemId, string fqdnName) { var result = "Unavailable"; var serviceId = GetRdsServiceId(itemId); try { if (serviceId != -1) { var rds = RemoteDesktopServicesHelpers.GetRemoteDesktopServices(serviceId); result = rds.GetRdsServerStatus(fqdnName); } } catch { } return result; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Expiry; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Query; using Apache.Ignite.Core.Impl.Cache.Query.Continuous; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native cache wrapper. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class CacheImpl<TK, TV> : PlatformTarget, ICache<TK, TV> { /** Duration: unchanged. */ private const long DurUnchanged = -2; /** Duration: eternal. */ private const long DurEternal = -1; /** Duration: zero. */ private const long DurZero = 0; /** Ignite instance. */ private readonly Ignite _ignite; /** Flag: skip store. */ private readonly bool _flagSkipStore; /** Flag: keep binary. */ private readonly bool _flagKeepBinary; /** Flag: async mode.*/ private readonly bool _flagAsync; /** Flag: no-retries.*/ private readonly bool _flagNoRetries; /** Async instance. */ private readonly Lazy<CacheImpl<TK, TV>> _asyncInstance; /// <summary> /// Constructor. /// </summary> /// <param name="grid">Grid.</param> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="flagSkipStore">Skip store flag.</param> /// <param name="flagKeepBinary">Keep binary flag.</param> /// <param name="flagAsync">Async mode flag.</param> /// <param name="flagNoRetries">No-retries mode flag.</param> public CacheImpl(Ignite grid, IUnmanagedTarget target, Marshaller marsh, bool flagSkipStore, bool flagKeepBinary, bool flagAsync, bool flagNoRetries) : base(target, marsh) { _ignite = grid; _flagSkipStore = flagSkipStore; _flagKeepBinary = flagKeepBinary; _flagAsync = flagAsync; _flagNoRetries = flagNoRetries; _asyncInstance = new Lazy<CacheImpl<TK, TV>>(() => new CacheImpl<TK, TV>(this)); } /// <summary> /// Initializes a new async instance. /// </summary> /// <param name="cache">The cache.</param> private CacheImpl(CacheImpl<TK, TV> cache) : base(UU.CacheWithAsync(cache.Target), cache.Marshaller) { _ignite = cache._ignite; _flagSkipStore = cache._flagSkipStore; _flagKeepBinary = cache._flagKeepBinary; _flagAsync = true; _flagNoRetries = cache._flagNoRetries; } /** <inheritDoc /> */ public IIgnite Ignite { get { return _ignite; } } /** <inheritDoc /> */ private bool IsAsync { get { return _flagAsync; } } /// <summary> /// Gets and resets task for previous asynchronous operation. /// </summary> /// <param name="lastAsyncOp">The last async op id.</param> /// <returns> /// Task for previous asynchronous operation. /// </returns> private Task GetTask(CacheOp lastAsyncOp) { return GetTask<object>(lastAsyncOp); } /// <summary> /// Gets and resets task for previous asynchronous operation. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="lastAsyncOp">The last async op id.</param> /// <param name="converter">The converter.</param> /// <returns> /// Task for previous asynchronous operation. /// </returns> private Task<TResult> GetTask<TResult>(CacheOp lastAsyncOp, Func<BinaryReader, TResult> converter = null) { Debug.Assert(_flagAsync); return GetFuture((futId, futTypeId) => UU.TargetListenFutureForOperation(Target, futId, futTypeId, (int) lastAsyncOp), _flagKeepBinary, converter).Task; } /** <inheritDoc /> */ public string Name { get { return DoInOp<string>((int)CacheOp.GetName); } } /** <inheritDoc /> */ public bool IsEmpty() { return GetSize() == 0; } /** <inheritDoc /> */ public ICache<TK, TV> WithSkipStore() { if (_flagSkipStore) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithSkipStore(Target), Marshaller, true, _flagKeepBinary, _flagAsync, true); } /// <summary> /// Skip store flag getter. /// </summary> internal bool IsSkipStore { get { return _flagSkipStore; } } /** <inheritDoc /> */ public ICache<TK1, TV1> WithKeepBinary<TK1, TV1>() { if (_flagKeepBinary) { var result = this as ICache<TK1, TV1>; if (result == null) throw new InvalidOperationException( "Can't change type of binary cache. WithKeepBinary has been called on an instance of " + "binary cache with incompatible generic arguments."); return result; } return new CacheImpl<TK1, TV1>(_ignite, UU.CacheWithKeepBinary(Target), Marshaller, _flagSkipStore, true, _flagAsync, _flagNoRetries); } /** <inheritDoc /> */ public ICache<TK, TV> WithExpiryPolicy(IExpiryPolicy plc) { IgniteArgumentCheck.NotNull(plc, "plc"); long create = ConvertDuration(plc.GetExpiryForCreate()); long update = ConvertDuration(plc.GetExpiryForUpdate()); long access = ConvertDuration(plc.GetExpiryForAccess()); IUnmanagedTarget cache0 = UU.CacheWithExpiryPolicy(Target, create, update, access); return new CacheImpl<TK, TV>(_ignite, cache0, Marshaller, _flagSkipStore, _flagKeepBinary, _flagAsync, _flagNoRetries); } /// <summary> /// Convert TimeSpan to duration recognizable by Java. /// </summary> /// <param name="dur">.Net duration.</param> /// <returns>Java duration in milliseconds.</returns> private static long ConvertDuration(TimeSpan? dur) { if (dur.HasValue) { if (dur.Value == TimeSpan.MaxValue) return DurEternal; long dur0 = (long)dur.Value.TotalMilliseconds; return dur0 > 0 ? dur0 : DurZero; } return DurUnchanged; } /** <inheritDoc /> */ public bool IsKeepBinary { get { return _flagKeepBinary; } } /** <inheritDoc /> */ public void LoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LoadCache); } /** <inheritDoc /> */ public Task LoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { AsyncInstance.LoadCache(p, args); return AsyncInstance.GetTask(CacheOp.LoadCache); } /** <inheritDoc /> */ public void LocalLoadCache(ICacheEntryFilter<TK, TV> p, params object[] args) { LoadCache0(p, args, (int)CacheOp.LocLoadCache); } /** <inheritDoc /> */ public Task LocalLoadCacheAsync(ICacheEntryFilter<TK, TV> p, params object[] args) { AsyncInstance.LocalLoadCache(p, args); return AsyncInstance.GetTask(CacheOp.LocLoadCache); } /// <summary> /// Loads the cache. /// </summary> private void LoadCache0(ICacheEntryFilter<TK, TV> p, object[] args, int opId) { DoOutOp(opId, writer => { if (p != null) { var p0 = new CacheEntryFilterHolder(p, (k, v) => p.Invoke(new CacheEntry<TK, TV>((TK) k, (TV) v)), Marshaller, IsKeepBinary); writer.WriteObject(p0); } else writer.WriteObject<CacheEntryFilterHolder>(null); writer.WriteArray(args); }); } /** <inheritDoc /> */ public bool ContainsKey(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.ContainsKey, key) == True; } /** <inheritDoc /> */ public Task<bool> ContainsKeyAsync(TK key) { AsyncInstance.ContainsKey(key); return AsyncInstance.GetTask<bool>(CacheOp.ContainsKey); } /** <inheritDoc /> */ public bool ContainsKeys(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutOp((int)CacheOp.ContainsKeys, writer => WriteEnumerable(writer, keys)) == True; } /** <inheritDoc /> */ public Task<bool> ContainsKeysAsync(IEnumerable<TK> keys) { AsyncInstance.ContainsKeys(keys); return AsyncInstance.GetTask<bool>(CacheOp.ContainsKeys); } /** <inheritDoc /> */ public TV LocalPeek(TK key, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); TV res; if (TryLocalPeek(key, out res)) return res; throw GetKeyNotFoundException(); } /** <inheritDoc /> */ public bool TryLocalPeek(TK key, out TV value, params CachePeekMode[] modes) { IgniteArgumentCheck.NotNull(key, "key"); var res = DoOutInOpNullable<TV>((int)CacheOp.Peek, writer => { writer.Write(key); writer.WriteInt(EncodePeekModes(modes)); }); value = res.Success ? res.Value : default(TV); return res.Success; } /** <inheritDoc /> */ public TV this[TK key] { get { if (IsAsync) throw new InvalidOperationException("Indexer can't be used in async mode."); return Get(key); } set { if (IsAsync) throw new InvalidOperationException("Indexer can't be used in async mode."); Put(key, value); } } /** <inheritDoc /> */ public TV Get(TK key) { IgniteArgumentCheck.NotNull(key, "key"); var result = DoOutInOpNullable<TK, TV>((int) CacheOp.Get, key); if (!IsAsync) { if (!result.Success) throw GetKeyNotFoundException(); return result.Value; } Debug.Assert(!result.Success); return default(TV); } /** <inheritDoc /> */ public Task<TV> GetAsync(TK key) { AsyncInstance.Get(key); return AsyncInstance.GetTask(CacheOp.Get, reader => { if (reader != null) return reader.ReadObject<TV>(); throw GetKeyNotFoundException(); }); } /** <inheritDoc /> */ public bool TryGet(TK key, out TV value) { IgniteArgumentCheck.NotNull(key, "key"); if (IsAsync) throw new InvalidOperationException("TryGet can't be used in async mode."); var res = DoOutInOpNullable<TK, TV>((int) CacheOp.Get, key); value = res.Value; return res.Success; } /** <inheritDoc /> */ public Task<CacheResult<TV>> TryGetAsync(TK key) { IgniteArgumentCheck.NotNull(key, "key"); AsyncInstance.Get(key); return AsyncInstance.GetTask(CacheOp.Get, GetCacheResult); } /** <inheritDoc /> */ public IDictionary<TK, TV> GetAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.GetAll, writer => WriteEnumerable(writer, keys), input => { var reader = Marshaller.StartUnmarshal(input, _flagKeepBinary); return ReadGetAllDictionary(reader); }); } /** <inheritDoc /> */ public Task<IDictionary<TK, TV>> GetAllAsync(IEnumerable<TK> keys) { AsyncInstance.GetAll(keys); return AsyncInstance.GetTask(CacheOp.GetAll, r => r == null ? null : ReadGetAllDictionary(r)); } /** <inheritdoc /> */ public void Put(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); DoOutOp((int)CacheOp.Put, key, val); } /** <inheritDoc /> */ public Task PutAsync(TK key, TV val) { AsyncInstance.Put(key, val); return AsyncInstance.GetTask(CacheOp.Put); } /** <inheritDoc /> */ public CacheResult<TV> GetAndPut(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int)CacheOp.GetAndPut, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutAsync(TK key, TV val) { AsyncInstance.GetAndPut(key, val); return AsyncInstance.GetTask(CacheOp.GetAndPut, GetCacheResult); } /** <inheritDoc /> */ public CacheResult<TV> GetAndReplace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int) CacheOp.GetAndReplace, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndReplaceAsync(TK key, TV val) { AsyncInstance.GetAndReplace(key, val); return AsyncInstance.GetTask(CacheOp.GetAndReplace, GetCacheResult); } /** <inheritDoc /> */ public CacheResult<TV> GetAndRemove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOpNullable<TK, TV>((int)CacheOp.GetAndRemove, key); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndRemoveAsync(TK key) { AsyncInstance.GetAndRemove(key); return AsyncInstance.GetTask(CacheOp.GetAndRemove, GetCacheResult); } /** <inheritdoc /> */ public bool PutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int) CacheOp.PutIfAbsent, key, val) == True; } /** <inheritDoc /> */ public Task<bool> PutIfAbsentAsync(TK key, TV val) { AsyncInstance.PutIfAbsent(key, val); return AsyncInstance.GetTask<bool>(CacheOp.PutIfAbsent); } /** <inheritdoc /> */ public CacheResult<TV> GetAndPutIfAbsent(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutInOpNullable<TK, TV, TV>((int)CacheOp.GetAndPutIfAbsent, key, val); } /** <inheritDoc /> */ public Task<CacheResult<TV>> GetAndPutIfAbsentAsync(TK key, TV val) { AsyncInstance.GetAndPutIfAbsent(key, val); return AsyncInstance.GetTask(CacheOp.GetAndPutIfAbsent, GetCacheResult); } /** <inheritdoc /> */ public bool Replace(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int) CacheOp.Replace2, key, val) == True; } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV val) { AsyncInstance.Replace(key, val); return AsyncInstance.GetTask<bool>(CacheOp.Replace2); } /** <inheritdoc /> */ public bool Replace(TK key, TV oldVal, TV newVal) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(oldVal, "oldVal"); IgniteArgumentCheck.NotNull(newVal, "newVal"); return DoOutOp((int)CacheOp.Replace3, key, oldVal, newVal) == True; } /** <inheritDoc /> */ public Task<bool> ReplaceAsync(TK key, TV oldVal, TV newVal) { AsyncInstance.Replace(key, oldVal, newVal); return AsyncInstance.GetTask<bool>(CacheOp.Replace3); } /** <inheritdoc /> */ public void PutAll(IDictionary<TK, TV> vals) { IgniteArgumentCheck.NotNull(vals, "vals"); DoOutOp((int) CacheOp.PutAll, writer => WriteDictionary(writer, vals)); } /** <inheritDoc /> */ public Task PutAllAsync(IDictionary<TK, TV> vals) { AsyncInstance.PutAll(vals); return AsyncInstance.GetTask(CacheOp.PutAll); } /** <inheritdoc /> */ public void LocalEvict(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int) CacheOp.LocEvict, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public void Clear() { UU.CacheClear(Target); } /** <inheritDoc /> */ public Task ClearAsync() { AsyncInstance.Clear(); return AsyncInstance.GetTask(); } /** <inheritdoc /> */ public void Clear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int) CacheOp.Clear, key); } /** <inheritDoc /> */ public Task ClearAsync(TK key) { AsyncInstance.Clear(key); return AsyncInstance.GetTask(CacheOp.Clear); } /** <inheritdoc /> */ public void ClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.ClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task ClearAllAsync(IEnumerable<TK> keys) { AsyncInstance.ClearAll(keys); return AsyncInstance.GetTask(CacheOp.ClearAll); } /** <inheritdoc /> */ public void LocalClear(TK key) { IgniteArgumentCheck.NotNull(key, "key"); DoOutOp((int) CacheOp.LocalClear, key); } /** <inheritdoc /> */ public void LocalClearAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocalClearAll, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public bool Remove(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int) CacheOp.RemoveObj, key) == True; } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key) { AsyncInstance.Remove(key); return AsyncInstance.GetTask<bool>(CacheOp.RemoveObj); } /** <inheritDoc /> */ public bool Remove(TK key, TV val) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(val, "val"); return DoOutOp((int)CacheOp.RemoveBool, key, val) == True; } /** <inheritDoc /> */ public Task<bool> RemoveAsync(TK key, TV val) { AsyncInstance.Remove(key, val); return AsyncInstance.GetTask<bool>(CacheOp.RemoveBool); } /** <inheritDoc /> */ public void RemoveAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.RemoveAll, writer => WriteEnumerable(writer, keys)); } /** <inheritDoc /> */ public Task RemoveAllAsync(IEnumerable<TK> keys) { AsyncInstance.RemoveAll(keys); return AsyncInstance.GetTask(CacheOp.RemoveAll); } /** <inheritDoc /> */ public void RemoveAll() { UU.CacheRemoveAll(Target); } /** <inheritDoc /> */ public Task RemoveAllAsync() { AsyncInstance.RemoveAll(); return AsyncInstance.GetTask(); } /** <inheritDoc /> */ public int GetLocalSize(params CachePeekMode[] modes) { return Size0(true, modes); } /** <inheritDoc /> */ public int GetSize(params CachePeekMode[] modes) { return Size0(false, modes); } /** <inheritDoc /> */ public Task<int> GetSizeAsync(params CachePeekMode[] modes) { AsyncInstance.GetSize(modes); return AsyncInstance.GetTask<int>(); } /// <summary> /// Internal size routine. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="modes">peek modes</param> /// <returns>Size.</returns> private int Size0(bool loc, params CachePeekMode[] modes) { int modes0 = EncodePeekModes(modes); return UU.CacheSize(Target, modes0, loc); } /** <inheritDoc /> */ public void LocalPromote(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); DoOutOp((int)CacheOp.LocPromote, writer => WriteEnumerable(writer, keys)); } /** <inheritdoc /> */ public TRes Invoke<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(key, "key"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOp((int)CacheOp.Invoke, writer => { writer.Write(key); writer.Write(holder); }, input => GetResultOrThrow<TRes>(Unmarshal<object>(input))); } /** <inheritDoc /> */ public Task<TRes> InvokeAsync<TArg, TRes>(TK key, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { AsyncInstance.Invoke(key, processor, arg); return AsyncInstance.GetTask(CacheOp.Invoke, r => { if (r == null) return default(TRes); var hasError = r.ReadBoolean(); if (hasError) throw ReadException(r.Stream); return r.ReadObject<TRes>(); }); } /** <inheritdoc /> */ public IDictionary<TK, ICacheEntryProcessorResult<TRes>> InvokeAll<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { IgniteArgumentCheck.NotNull(keys, "keys"); IgniteArgumentCheck.NotNull(processor, "processor"); var holder = new CacheEntryProcessorHolder(processor, arg, (e, a) => processor.Process((IMutableCacheEntry<TK, TV>)e, (TArg)a), typeof(TK), typeof(TV)); return DoOutInOp((int) CacheOp.InvokeAll, writer => { WriteEnumerable(writer, keys); writer.Write(holder); }, input => ReadInvokeAllResults<TRes>(input)); } /** <inheritDoc /> */ public Task<IDictionary<TK, ICacheEntryProcessorResult<TRes>>> InvokeAllAsync<TArg, TRes>(IEnumerable<TK> keys, ICacheEntryProcessor<TK, TV, TArg, TRes> processor, TArg arg) { AsyncInstance.InvokeAll(keys, processor, arg); return AsyncInstance.GetTask(CacheOp.InvokeAll, reader => ReadInvokeAllResults<TRes>(reader.Stream)); } /** <inheritdoc /> */ public ICacheLock Lock(TK key) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutInOp((int)CacheOp.Lock, writer => { writer.Write(key); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public ICacheLock LockAll(IEnumerable<TK> keys) { IgniteArgumentCheck.NotNull(keys, "keys"); return DoOutInOp((int)CacheOp.LockAll, writer => { WriteEnumerable(writer, keys); }, input => new CacheLock(input.ReadInt(), Target)); } /** <inheritdoc /> */ public bool IsLocalLocked(TK key, bool byCurrentThread) { IgniteArgumentCheck.NotNull(key, "key"); return DoOutOp((int)CacheOp.IsLocalLocked, writer => { writer.Write(key); writer.WriteBoolean(byCurrentThread); }) == True; } /** <inheritDoc /> */ public ICacheMetrics GetMetrics() { return DoInOp((int)CacheOp.Metrics, stream => { IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); return new CacheMetricsImpl(reader); }); } /** <inheritDoc /> */ public Task Rebalance() { return GetFuture<object>((futId, futTyp) => UU.CacheRebalance(Target, futId)).Task; } /** <inheritDoc /> */ public ICache<TK, TV> WithNoRetries() { if (_flagNoRetries) return this; return new CacheImpl<TK, TV>(_ignite, UU.CacheWithNoRetries(Target), Marshaller, _flagSkipStore, _flagKeepBinary, _flagAsync, true); } /// <summary> /// Gets the asynchronous instance. /// </summary> private CacheImpl<TK, TV> AsyncInstance { get { return _asyncInstance.Value; } } #region Queries /** <inheritDoc /> */ public IQueryCursor<IList> QueryFields(SqlFieldsQuery qry) { IgniteArgumentCheck.NotNull(qry, "qry"); if (string.IsNullOrEmpty(qry.Sql)) throw new ArgumentException("Sql cannot be null or empty"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); writer.WriteBoolean(qry.Local); writer.WriteString(qry.Sql); writer.WriteInt(qry.PageSize); WriteQueryArgs(writer, qry.Arguments); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int) CacheOp.QrySqlFields, stream.SynchronizeOutput()); } return new FieldsQueryCursor(cursor, Marshaller, _flagKeepBinary); } /** <inheritDoc /> */ public IQueryCursor<ICacheEntry<TK, TV>> Query(QueryBase qry) { IgniteArgumentCheck.NotNull(qry, "qry"); IUnmanagedTarget cursor; using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); qry.Write(writer, IsKeepBinary); FinishMarshal(writer); cursor = UU.CacheOutOpQueryCursor(Target, (int)qry.OpId, stream.SynchronizeOutput()); } return new QueryCursor<TK, TV>(cursor, Marshaller, _flagKeepBinary); } /// <summary> /// Write query arguments. /// </summary> /// <param name="writer">Writer.</param> /// <param name="args">Arguments.</param> private static void WriteQueryArgs(BinaryWriter writer, object[] args) { if (args == null) writer.WriteInt(0); else { writer.WriteInt(args.Length); foreach (var arg in args) writer.WriteObject(arg); } } /** <inheritdoc /> */ public IContinuousQueryHandle QueryContinuous(ContinuousQuery<TK, TV> qry) { IgniteArgumentCheck.NotNull(qry, "qry"); return QueryContinuousImpl(qry, null); } /** <inheritdoc /> */ public IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuous(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { IgniteArgumentCheck.NotNull(qry, "qry"); IgniteArgumentCheck.NotNull(initialQry, "initialQry"); return QueryContinuousImpl(qry, initialQry); } /// <summary> /// QueryContinuous implementation. /// </summary> private IContinuousQueryHandle<ICacheEntry<TK, TV>> QueryContinuousImpl(ContinuousQuery<TK, TV> qry, QueryBase initialQry) { qry.Validate(); var hnd = new ContinuousQueryHandleImpl<TK, TV>(qry, Marshaller, _flagKeepBinary); using (var stream = IgniteManager.Memory.Allocate().GetStream()) { var writer = Marshaller.StartMarshal(stream); hnd.Start(_ignite, writer, () => { if (initialQry != null) { writer.WriteInt((int) initialQry.OpId); initialQry.Write(writer, IsKeepBinary); } else writer.WriteInt(-1); // no initial query FinishMarshal(writer); // ReSharper disable once AccessToDisposedClosure return UU.CacheOutOpContinuousQuery(Target, (int)CacheOp.QryContinuous, stream.SynchronizeOutput()); }, qry); } return hnd; } #endregion #region Enumerable support /** <inheritdoc /> */ public IEnumerable<ICacheEntry<TK, TV>> GetLocalEntries(CachePeekMode[] peekModes) { return new CacheEnumerable<TK, TV>(this, EncodePeekModes(peekModes)); } /** <inheritdoc /> */ public IEnumerator<ICacheEntry<TK, TV>> GetEnumerator() { return new CacheEnumeratorProxy<TK, TV>(this, false, 0); } /** <inheritdoc /> */ IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Create real cache enumerator. /// </summary> /// <param name="loc">Local flag.</param> /// <param name="peekModes">Peek modes for local enumerator.</param> /// <returns>Cache enumerator.</returns> internal CacheEnumerator<TK, TV> CreateEnumerator(bool loc, int peekModes) { if (loc) return new CacheEnumerator<TK, TV>(UU.CacheLocalIterator(Target, peekModes), Marshaller, _flagKeepBinary); return new CacheEnumerator<TK, TV>(UU.CacheIterator(Target), Marshaller, _flagKeepBinary); } #endregion /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { return Marshaller.Unmarshal<T>(stream, _flagKeepBinary); } /// <summary> /// Encodes the peek modes into a single int value. /// </summary> private static int EncodePeekModes(CachePeekMode[] modes) { int modesEncoded = 0; if (modes != null) { foreach (var mode in modes) modesEncoded |= (int) mode; } return modesEncoded; } /// <summary> /// Unwraps an exception. /// </summary> /// <typeparam name="T">Result type.</typeparam> /// <param name="obj">Object.</param> /// <returns>Result.</returns> private static T GetResultOrThrow<T>(object obj) { var err = obj as Exception; if (err != null) throw err as CacheEntryProcessorException ?? new CacheEntryProcessorException(err); return obj == null ? default(T) : (T) obj; } /// <summary> /// Reads results of InvokeAll operation. /// </summary> /// <typeparam name="T">The type of the result.</typeparam> /// <param name="inStream">Stream.</param> /// <returns>Results of InvokeAll operation.</returns> private IDictionary<TK, ICacheEntryProcessorResult<T>> ReadInvokeAllResults<T>(IBinaryStream inStream) { var count = inStream.ReadInt(); if (count == -1) return null; var results = new Dictionary<TK, ICacheEntryProcessorResult<T>>(count); for (var i = 0; i < count; i++) { var key = Unmarshal<TK>(inStream); var hasError = inStream.ReadBool(); results[key] = hasError ? new CacheEntryProcessorResult<T>(ReadException(inStream)) : new CacheEntryProcessorResult<T>(Unmarshal<T>(inStream)); } return results; } /// <summary> /// Reads the exception, either in binary wrapper form, or as a pair of strings. /// </summary> /// <param name="inStream">The stream.</param> /// <returns>Exception.</returns> private CacheEntryProcessorException ReadException(IBinaryStream inStream) { var item = Unmarshal<object>(inStream); var clsName = item as string; if (clsName == null) return new CacheEntryProcessorException((Exception) item); var msg = Unmarshal<string>(inStream); return new CacheEntryProcessorException(ExceptionUtils.GetException(clsName, msg)); } /// <summary> /// Read dictionary returned by GET_ALL operation. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Dictionary.</returns> private static IDictionary<TK, TV> ReadGetAllDictionary(BinaryReader reader) { IBinaryStream stream = reader.Stream; if (stream.ReadBool()) { int size = stream.ReadInt(); IDictionary<TK, TV> res = new Dictionary<TK, TV>(size); for (int i = 0; i < size; i++) { TK key = reader.ReadObject<TK>(); TV val = reader.ReadObject<TV>(); res[key] = val; } return res; } return null; } /// <summary> /// Gets the cache result. /// </summary> private static CacheResult<TV> GetCacheResult(BinaryReader reader) { var res = reader == null ? new CacheResult<TV>() : new CacheResult<TV>(reader.ReadObject<TV>()); return res; } /// <summary> /// Throws the key not found exception. /// </summary> private static KeyNotFoundException GetKeyNotFoundException() { return new KeyNotFoundException("The given key was not present in the cache."); } /// <summary> /// Perform simple out-in operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val">Value.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<T1, TR>(int type, T1 val) { var res = DoOutInOp<T1, object>(type, val); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } /// <summary> /// Perform out-in operation. /// </summary> /// <param name="type">Operation type.</param> /// <param name="outAction">Out action.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<TR>(int type, Action<BinaryWriter> outAction) { var res = DoOutInOp<object>(type, outAction); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } /// <summary> /// Perform simple out-in operation accepting single argument. /// </summary> /// <param name="type">Operation type.</param> /// <param name="val1">Value.</param> /// <param name="val2">Value.</param> /// <returns>Result.</returns> private CacheResult<TR> DoOutInOpNullable<T1, T2, TR>(int type, T1 val1, T2 val2) { var res = DoOutInOp<T1, T2, object>(type, val1, val2); return res == null ? new CacheResult<TR>() : new CacheResult<TR>((TR)res); } } }
namespace ZetaResourceEditor.UI.ExportImport { partial class ImportWizardForm { /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImportWizardForm)); this.wizardControl = new DevExpress.XtraWizard.WizardControl(); this.importFileWizardPage = new DevExpress.XtraWizard.WelcomeWizardPage(); this.sourceFileTextEdit = new DevExpress.XtraEditors.MemoEdit(); this.buttonOpen = new DevExpress.XtraEditors.SimpleButton(); this.buttonBrowse = new DevExpress.XtraEditors.SimpleButton(); this.labelControl2 = new DevExpress.XtraEditors.LabelControl(); this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); this.successWizardPage = new DevExpress.XtraWizard.CompletionWizardPage(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.labelControl5 = new DevExpress.XtraEditors.LabelControl(); this.fileGroupsWizardPage = new DevExpress.XtraWizard.WizardPage(); this.invertFileGroupsButton = new DevExpress.XtraEditors.SimpleButton(); this.selectNoFileGroupsButton = new DevExpress.XtraEditors.SimpleButton(); this.selectAllFileGroupsButton = new DevExpress.XtraEditors.SimpleButton(); this.fileGroupsListBox = new DevExpress.XtraEditors.CheckedListBoxControl(); this.labelControl4 = new DevExpress.XtraEditors.LabelControl(); this.labelControl1 = new DevExpress.XtraEditors.LabelControl(); this.languagesWizardPage = new DevExpress.XtraWizard.WizardPage(); this.labelControl6 = new DevExpress.XtraEditors.LabelControl(); this.label3 = new DevExpress.XtraEditors.LabelControl(); this.selectAllLanguagesToExportButton = new DevExpress.XtraEditors.SimpleButton(); this.invertLanguagesToExportButton = new DevExpress.XtraEditors.SimpleButton(); this.selectNoLanguagesToExportButton = new DevExpress.XtraEditors.SimpleButton(); this.languagesToImportCheckListBox = new DevExpress.XtraEditors.CheckedListBoxControl(); this.progressWizardPage = new DevExpress.XtraWizard.WizardPage(); this.progressBarControl = new DevExpress.XtraEditors.MarqueeProgressBarControl(); this.progressLabel = new DevExpress.XtraEditors.LabelControl(); this.errorOccurredWizardPage = new DevExpress.XtraWizard.WizardPage(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.labelControl3 = new DevExpress.XtraEditors.LabelControl(); this.optionsButton = new DevExpress.XtraEditors.DropDownButton(); this.optionsPopupMenu = new DevExpress.XtraBars.PopupMenu(this.components); this.detailedErrorsButton = new DevExpress.XtraBars.BarButtonItem(); this.underylingExceptionButton = new DevExpress.XtraBars.BarButtonItem(); this.barManager = new DevExpress.XtraBars.BarManager(this.components); this.imageCollection1 = new DevExpress.Utils.ImageCollection(this.components); this.errorTextMemoEdit = new DevExpress.XtraEditors.MemoEdit(); this.progressBackgroundWorker = new System.ComponentModel.BackgroundWorker(); ((System.ComponentModel.ISupportInitialize)(this.wizardControl)).BeginInit(); this.wizardControl.SuspendLayout(); this.importFileWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.sourceFileTextEdit.Properties)).BeginInit(); this.successWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.fileGroupsWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.fileGroupsListBox)).BeginInit(); this.languagesWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.languagesToImportCheckListBox)).BeginInit(); this.progressWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.progressBarControl.Properties)).BeginInit(); this.errorOccurredWizardPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.optionsPopupMenu)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.imageCollection1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.errorTextMemoEdit.Properties)).BeginInit(); this.SuspendLayout(); // // wizardControl // this.wizardControl.Controls.Add(this.importFileWizardPage); this.wizardControl.Controls.Add(this.successWizardPage); this.wizardControl.Controls.Add(this.fileGroupsWizardPage); this.wizardControl.Controls.Add(this.languagesWizardPage); this.wizardControl.Controls.Add(this.progressWizardPage); this.wizardControl.Controls.Add(this.errorOccurredWizardPage); this.wizardControl.Name = "wizardControl"; this.wizardControl.Pages.AddRange(new DevExpress.XtraWizard.BaseWizardPage[] { this.importFileWizardPage, this.fileGroupsWizardPage, this.languagesWizardPage, this.progressWizardPage, this.errorOccurredWizardPage, this.successWizardPage}); resources.ApplyResources(this.wizardControl, "wizardControl"); this.wizardControl.TitleImage = ((System.Drawing.Image)(resources.GetObject("wizardControl.TitleImage"))); this.wizardControl.WizardStyle = DevExpress.XtraWizard.WizardStyle.WizardAero; this.wizardControl.PrevClick += new DevExpress.XtraWizard.WizardCommandButtonClickEventHandler(this.wizardControl_PrevClick); this.wizardControl.SelectedPageChanged += new DevExpress.XtraWizard.WizardPageChangedEventHandler(this.wizardControl_SelectedPageChanged); this.wizardControl.FinishClick += new System.ComponentModel.CancelEventHandler(this.wizardControl_FinishClick); this.wizardControl.NextClick += new DevExpress.XtraWizard.WizardCommandButtonClickEventHandler(this.wizardControl_NextClick); this.wizardControl.CancelClick += new System.ComponentModel.CancelEventHandler(this.wizardControl_CancelClick); // // importFileWizardPage // this.importFileWizardPage.Controls.Add(this.sourceFileTextEdit); this.importFileWizardPage.Controls.Add(this.buttonOpen); this.importFileWizardPage.Controls.Add(this.buttonBrowse); this.importFileWizardPage.Controls.Add(this.labelControl2); this.importFileWizardPage.Controls.Add(this.barDockControlLeft); this.importFileWizardPage.Controls.Add(this.barDockControlRight); this.importFileWizardPage.Controls.Add(this.barDockControlBottom); this.importFileWizardPage.Controls.Add(this.barDockControlTop); resources.ApplyResources(this.importFileWizardPage, "importFileWizardPage"); this.importFileWizardPage.Name = "importFileWizardPage"; // // sourceFileTextEdit // resources.ApplyResources(this.sourceFileTextEdit, "sourceFileTextEdit"); this.sourceFileTextEdit.Name = "sourceFileTextEdit"; this.sourceFileTextEdit.Properties.AcceptsReturn = false; this.sourceFileTextEdit.EditValueChanged += new System.EventHandler(this.sourceFileTextEdit_EditValueChanged); // // buttonOpen // this.buttonOpen.Image = ((System.Drawing.Image)(resources.GetObject("buttonOpen.Image"))); resources.ApplyResources(this.buttonOpen, "buttonOpen"); this.buttonOpen.Name = "buttonOpen"; this.buttonOpen.Click += new System.EventHandler(this.buttonOpen_Click); // // buttonBrowse // resources.ApplyResources(this.buttonBrowse, "buttonBrowse"); this.buttonBrowse.Image = ((System.Drawing.Image)(resources.GetObject("buttonBrowse.Image"))); this.buttonBrowse.Name = "buttonBrowse"; this.buttonBrowse.Click += new System.EventHandler(this.buttonBrowse_Click); // // labelControl2 // resources.ApplyResources(this.labelControl2, "labelControl2"); this.labelControl2.Name = "labelControl2"; // // successWizardPage // this.successWizardPage.AllowBack = false; this.successWizardPage.AllowCancel = false; this.successWizardPage.AllowNext = false; this.successWizardPage.Controls.Add(this.pictureBox2); this.successWizardPage.Controls.Add(this.labelControl5); this.successWizardPage.Name = "successWizardPage"; resources.ApplyResources(this.successWizardPage, "successWizardPage"); // // pictureBox2 // resources.ApplyResources(this.pictureBox2, "pictureBox2"); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.TabStop = false; // // labelControl5 // resources.ApplyResources(this.labelControl5, "labelControl5"); this.labelControl5.Appearance.Options.UseTextOptions = true; this.labelControl5.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Top; this.labelControl5.Appearance.TextOptions.WordWrap = DevExpress.Utils.WordWrap.Wrap; this.labelControl5.Name = "labelControl5"; // // fileGroupsWizardPage // this.fileGroupsWizardPage.Controls.Add(this.invertFileGroupsButton); this.fileGroupsWizardPage.Controls.Add(this.selectNoFileGroupsButton); this.fileGroupsWizardPage.Controls.Add(this.selectAllFileGroupsButton); this.fileGroupsWizardPage.Controls.Add(this.fileGroupsListBox); this.fileGroupsWizardPage.Controls.Add(this.labelControl4); this.fileGroupsWizardPage.Controls.Add(this.labelControl1); this.fileGroupsWizardPage.Name = "fileGroupsWizardPage"; resources.ApplyResources(this.fileGroupsWizardPage, "fileGroupsWizardPage"); // // invertFileGroupsButton // resources.ApplyResources(this.invertFileGroupsButton, "invertFileGroupsButton"); this.invertFileGroupsButton.Name = "invertFileGroupsButton"; this.invertFileGroupsButton.Click += new System.EventHandler(this.invertFileGroupsButton_Click); // // selectNoFileGroupsButton // resources.ApplyResources(this.selectNoFileGroupsButton, "selectNoFileGroupsButton"); this.selectNoFileGroupsButton.Name = "selectNoFileGroupsButton"; this.selectNoFileGroupsButton.Click += new System.EventHandler(this.selectNoFileGroupsButton_Click); // // selectAllFileGroupsButton // resources.ApplyResources(this.selectAllFileGroupsButton, "selectAllFileGroupsButton"); this.selectAllFileGroupsButton.Name = "selectAllFileGroupsButton"; this.selectAllFileGroupsButton.Click += new System.EventHandler(this.selectAllFileGroupsButton_Click); // // fileGroupsListBox // resources.ApplyResources(this.fileGroupsListBox, "fileGroupsListBox"); this.fileGroupsListBox.CheckOnClick = true; this.fileGroupsListBox.Name = "fileGroupsListBox"; this.fileGroupsListBox.SelectedIndexChanged += new System.EventHandler(this.fileGroupsListBox_SelectedIndexChanged); this.fileGroupsListBox.ItemCheck += new DevExpress.XtraEditors.Controls.ItemCheckEventHandler(this.fileGroupsListBox_ItemCheck); // // labelControl4 // resources.ApplyResources(this.labelControl4, "labelControl4"); this.labelControl4.Name = "labelControl4"; // // labelControl1 // resources.ApplyResources(this.labelControl1, "labelControl1"); this.labelControl1.Name = "labelControl1"; // // languagesWizardPage // this.languagesWizardPage.Controls.Add(this.labelControl6); this.languagesWizardPage.Controls.Add(this.label3); this.languagesWizardPage.Controls.Add(this.selectAllLanguagesToExportButton); this.languagesWizardPage.Controls.Add(this.invertLanguagesToExportButton); this.languagesWizardPage.Controls.Add(this.selectNoLanguagesToExportButton); this.languagesWizardPage.Controls.Add(this.languagesToImportCheckListBox); this.languagesWizardPage.Name = "languagesWizardPage"; resources.ApplyResources(this.languagesWizardPage, "languagesWizardPage"); // // labelControl6 // resources.ApplyResources(this.labelControl6, "labelControl6"); this.labelControl6.Name = "labelControl6"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // selectAllLanguagesToExportButton // resources.ApplyResources(this.selectAllLanguagesToExportButton, "selectAllLanguagesToExportButton"); this.selectAllLanguagesToExportButton.Name = "selectAllLanguagesToExportButton"; this.selectAllLanguagesToExportButton.Click += new System.EventHandler(this.selectAllLanguagesToExportButton_Click); // // invertLanguagesToExportButton // resources.ApplyResources(this.invertLanguagesToExportButton, "invertLanguagesToExportButton"); this.invertLanguagesToExportButton.Name = "invertLanguagesToExportButton"; this.invertLanguagesToExportButton.Click += new System.EventHandler(this.invertLanguagesToExportButton_Click); // // selectNoLanguagesToExportButton // resources.ApplyResources(this.selectNoLanguagesToExportButton, "selectNoLanguagesToExportButton"); this.selectNoLanguagesToExportButton.Name = "selectNoLanguagesToExportButton"; this.selectNoLanguagesToExportButton.Click += new System.EventHandler(this.selectNoLanguagesToExportButton_Click); // // languagesToImportCheckListBox // resources.ApplyResources(this.languagesToImportCheckListBox, "languagesToImportCheckListBox"); this.languagesToImportCheckListBox.CheckOnClick = true; this.languagesToImportCheckListBox.Name = "languagesToImportCheckListBox"; this.languagesToImportCheckListBox.SelectedIndexChanged += new System.EventHandler(this.languagesToImportCheckListBox_SelectedIndexChanged); this.languagesToImportCheckListBox.ItemCheck += new DevExpress.XtraEditors.Controls.ItemCheckEventHandler(this.languagesToImportCheckListBox_ItemCheck); // // progressWizardPage // this.progressWizardPage.AllowBack = false; this.progressWizardPage.AllowNext = false; this.progressWizardPage.Controls.Add(this.progressBarControl); this.progressWizardPage.Controls.Add(this.progressLabel); this.progressWizardPage.Name = "progressWizardPage"; resources.ApplyResources(this.progressWizardPage, "progressWizardPage"); // // progressBarControl // resources.ApplyResources(this.progressBarControl, "progressBarControl"); this.progressBarControl.Name = "progressBarControl"; // // progressLabel // resources.ApplyResources(this.progressLabel, "progressLabel"); this.progressLabel.Name = "progressLabel"; // // errorOccurredWizardPage // this.errorOccurredWizardPage.AllowNext = false; this.errorOccurredWizardPage.Controls.Add(this.pictureBox1); this.errorOccurredWizardPage.Controls.Add(this.labelControl3); this.errorOccurredWizardPage.Controls.Add(this.optionsButton); this.errorOccurredWizardPage.Controls.Add(this.errorTextMemoEdit); this.errorOccurredWizardPage.Name = "errorOccurredWizardPage"; resources.ApplyResources(this.errorOccurredWizardPage, "errorOccurredWizardPage"); // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // labelControl3 // resources.ApplyResources(this.labelControl3, "labelControl3"); this.labelControl3.Name = "labelControl3"; // // optionsButton // resources.ApplyResources(this.optionsButton, "optionsButton"); this.optionsButton.Appearance.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.optionsButton.Appearance.Options.UseFont = true; this.optionsButton.DropDownControl = this.optionsPopupMenu; this.optionsButton.Image = ((System.Drawing.Image)(resources.GetObject("optionsButton.Image"))); this.optionsButton.ImageLocation = DevExpress.XtraEditors.ImageLocation.MiddleRight; this.optionsButton.Name = "optionsButton"; this.optionsButton.ShowArrowButton = false; // // optionsPopupMenu // this.optionsPopupMenu.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { new DevExpress.XtraBars.LinkPersistInfo(this.detailedErrorsButton), new DevExpress.XtraBars.LinkPersistInfo(this.underylingExceptionButton)}); this.optionsPopupMenu.Manager = this.barManager; this.optionsPopupMenu.Name = "optionsPopupMenu"; this.optionsPopupMenu.BeforePopup += new System.ComponentModel.CancelEventHandler(this.optionsPopupMenu_BeforePopup); // // detailedErrorsButton // resources.ApplyResources(this.detailedErrorsButton, "detailedErrorsButton"); this.detailedErrorsButton.Id = 0; this.detailedErrorsButton.ImageIndex = 1; this.detailedErrorsButton.Name = "detailedErrorsButton"; this.detailedErrorsButton.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.detailedErrorsButton_ItemClick); // // underylingExceptionButton // resources.ApplyResources(this.underylingExceptionButton, "underylingExceptionButton"); this.underylingExceptionButton.Id = 1; this.underylingExceptionButton.ImageIndex = 0; this.underylingExceptionButton.Name = "underylingExceptionButton"; this.underylingExceptionButton.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.underylingExceptionButton_ItemClick); // // barManager // this.barManager.DockControls.Add(this.barDockControlTop); this.barManager.DockControls.Add(this.barDockControlBottom); this.barManager.DockControls.Add(this.barDockControlLeft); this.barManager.DockControls.Add(this.barDockControlRight); this.barManager.Form = this.importFileWizardPage; this.barManager.Images = this.imageCollection1; this.barManager.Items.AddRange(new DevExpress.XtraBars.BarItem[] { this.detailedErrorsButton, this.underylingExceptionButton}); this.barManager.MaxItemId = 3; // // imageCollection1 // this.imageCollection1.ImageStream = ((DevExpress.Utils.ImageCollectionStreamer)(resources.GetObject("imageCollection1.ImageStream"))); // // errorTextMemoEdit // resources.ApplyResources(this.errorTextMemoEdit, "errorTextMemoEdit"); this.errorTextMemoEdit.Name = "errorTextMemoEdit"; // // progressBackgroundWorker // this.progressBackgroundWorker.WorkerReportsProgress = true; this.progressBackgroundWorker.WorkerSupportsCancellation = true; this.progressBackgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.progressBackgroundWorker_DoWork); this.progressBackgroundWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.progressBackgroundWorker_RunWorkerCompleted); this.progressBackgroundWorker.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.progressBackgroundWorker_ProgressChanged); // // ImportWizardForm // this.Appearance.Font = new System.Drawing.Font("Tahoma", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.Appearance.Options.UseFont = true; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.wizardControl); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ImportWizardForm"; this.ShowInTaskbar = false; this.Load += new System.EventHandler(this.ImportWizard_Load); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ImportWizard_FormClosing); ((System.ComponentModel.ISupportInitialize)(this.wizardControl)).EndInit(); this.wizardControl.ResumeLayout(false); this.importFileWizardPage.ResumeLayout(false); this.importFileWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.sourceFileTextEdit.Properties)).EndInit(); this.successWizardPage.ResumeLayout(false); this.successWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.fileGroupsWizardPage.ResumeLayout(false); this.fileGroupsWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.fileGroupsListBox)).EndInit(); this.languagesWizardPage.ResumeLayout(false); this.languagesWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.languagesToImportCheckListBox)).EndInit(); this.progressWizardPage.ResumeLayout(false); this.progressWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.progressBarControl.Properties)).EndInit(); this.errorOccurredWizardPage.ResumeLayout(false); this.errorOccurredWizardPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.optionsPopupMenu)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.barManager)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.imageCollection1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.errorTextMemoEdit.Properties)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraWizard.WizardControl wizardControl; private DevExpress.XtraWizard.WelcomeWizardPage importFileWizardPage; private DevExpress.XtraWizard.CompletionWizardPage successWizardPage; private DevExpress.XtraEditors.SimpleButton buttonBrowse; private DevExpress.XtraEditors.LabelControl labelControl2; private DevExpress.XtraEditors.MemoEdit sourceFileTextEdit; private DevExpress.XtraBars.BarDockControl barDockControlTop; private DevExpress.XtraBars.BarDockControl barDockControlBottom; private DevExpress.XtraBars.BarDockControl barDockControlLeft; private DevExpress.XtraBars.BarDockControl barDockControlRight; private DevExpress.XtraBars.BarManager barManager; private DevExpress.Utils.ImageCollection imageCollection1; private DevExpress.XtraBars.BarButtonItem detailedErrorsButton; private DevExpress.XtraBars.BarButtonItem underylingExceptionButton; private DevExpress.XtraBars.PopupMenu optionsPopupMenu; private System.ComponentModel.BackgroundWorker progressBackgroundWorker; private DevExpress.XtraWizard.WizardPage fileGroupsWizardPage; private DevExpress.XtraEditors.SimpleButton invertFileGroupsButton; private DevExpress.XtraEditors.SimpleButton selectNoFileGroupsButton; private DevExpress.XtraEditors.SimpleButton selectAllFileGroupsButton; private DevExpress.XtraEditors.CheckedListBoxControl fileGroupsListBox; private DevExpress.XtraEditors.LabelControl labelControl1; private DevExpress.XtraWizard.WizardPage languagesWizardPage; private DevExpress.XtraEditors.LabelControl label3; private DevExpress.XtraEditors.SimpleButton selectAllLanguagesToExportButton; private DevExpress.XtraEditors.SimpleButton invertLanguagesToExportButton; private DevExpress.XtraEditors.SimpleButton selectNoLanguagesToExportButton; private DevExpress.XtraEditors.CheckedListBoxControl languagesToImportCheckListBox; private DevExpress.XtraWizard.WizardPage progressWizardPage; private DevExpress.XtraEditors.MarqueeProgressBarControl progressBarControl; private DevExpress.XtraEditors.LabelControl progressLabel; private DevExpress.XtraWizard.WizardPage errorOccurredWizardPage; private System.Windows.Forms.PictureBox pictureBox1; private DevExpress.XtraEditors.LabelControl labelControl3; private DevExpress.XtraEditors.DropDownButton optionsButton; private DevExpress.XtraEditors.MemoEdit errorTextMemoEdit; private System.Windows.Forms.PictureBox pictureBox2; private DevExpress.XtraEditors.LabelControl labelControl5; private DevExpress.XtraEditors.LabelControl labelControl4; private DevExpress.XtraEditors.LabelControl labelControl6; private DevExpress.XtraEditors.SimpleButton buttonOpen; } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using System.Linq.Expressions; #endif using System; using System.Collections.Generic; using System.Dynamic; using System.Runtime.CompilerServices; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; namespace IronPython.Runtime { [PythonType("buffer"), DontMapGetMemberNamesToDir] public sealed class PythonBuffer : ICodeFormattable, IDynamicMetaObjectProvider, IList<byte> { internal object _object; private int _offset; private int _size; private readonly CodeContext/*!*/ _context; public PythonBuffer(CodeContext/*!*/ context, object @object) : this(context, @object, 0) { } public PythonBuffer(CodeContext/*!*/ context, object @object, int offset) : this(context, @object, offset, -1) { } public PythonBuffer(CodeContext/*!*/ context, object @object, int offset, int size) { if (!InitBufferObject(@object, offset, size)) { throw PythonOps.TypeError("expected buffer object"); } _context = context; } private bool InitBufferObject(object o, int offset, int size) { if (offset < 0) { throw PythonOps.ValueError("offset must be zero or positive"); } else if (size < -1) { // -1 is the way to ask for the default size so we allow -1 as a size throw PythonOps.ValueError("size must be zero or positive"); } // we currently support only buffers, strings and arrays // of primitives, strings, bytes, and bytearray objects. int length; if (o is PythonBuffer) { PythonBuffer py = (PythonBuffer)o; o = py._object; // grab the internal object length = py._size; } else if (o is string) { string strobj = (string)o; length = strobj.Length; } else if (o is Bytes) { length = ((Bytes)o).Count; } else if (o is ByteArray) { length = ((ByteArray)o).Count; } else if (o is Array || o is IPythonArray) { Array arr = o as Array; if (arr != null) { Type t = arr.GetType().GetElementType(); if (!t.IsPrimitive && t != typeof(string)) { return false; } length = arr.Length; } else { IPythonArray pa = (IPythonArray)o; length = pa.Count; } } else if (o is IPythonBufferable) { length = ((IPythonBufferable)o).Size; _object = o; } else { return false; } // reset the size based on the given buffer's original size if (size >= (length - offset) || size == -1) { _size = length - offset; } else { _size = size; } _object = o; _offset = offset; return true; } public override string ToString() { object res = GetSelectedRange(); if (res is Bytes) { return PythonOps.MakeString((Bytes)res); } else if (res is ByteArray) { return PythonOps.MakeString((ByteArray)res); } else if (res is IPythonBufferable) { return PythonOps.MakeString((IList<byte>)GetSelectedRange()); } else if (res is byte[]) { return ((byte[])GetSelectedRange()).MakeString(); } return res.ToString(); } public int __cmp__([NotNull]PythonBuffer other) { if (Object.ReferenceEquals(this, other)) return 0; return PythonOps.Compare(ToString(), other.ToString()); } [PythonHidden] public override bool Equals(object obj) { PythonBuffer b = obj as PythonBuffer; if (b == null) { return false; } return __cmp__(b) == 0; } public override int GetHashCode() { return _object.GetHashCode() ^ _offset ^ (_size << 16 | (_size >> 16)); } private Slice GetSlice() { object end = null; if (_size >= 0) { end = _offset + _size; } return new Slice(_offset, end); } private static Exception ReadOnlyError() { return PythonOps.TypeError("buffer is read-only"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public void __delitem__(int index) { throw ReadOnlyError(); } public object this[object s] { [SpecialName] get { return PythonOps.GetIndex(_context, GetSelectedRange(), s); } [SpecialName] set { throw ReadOnlyError(); } } private object GetSelectedRange() { IPythonArray arr = _object as IPythonArray; if (arr != null) { return arr.tostring(); } ByteArray bytearr = _object as ByteArray; if (bytearr != null) { return new Bytes((IList<byte>)bytearr[GetSlice()]); } IPythonBufferable pyBuf = _object as IPythonBufferable; if (pyBuf != null) { return new Bytes(pyBuf.GetBytes(_offset, _size)); } return PythonOps.GetIndex(_context, _object, GetSlice()); } public static object operator +(PythonBuffer a, PythonBuffer b) { PythonContext context = PythonContext.GetContext(a._context); return context.Operation( PythonOperationKind.Add, PythonOps.GetIndex(a._context, a._object, a.GetSlice()), PythonOps.GetIndex(a._context, b._object, b.GetSlice()) ); } public static object operator +(PythonBuffer a, string b) { return a.ToString() + b; } public static object operator *(PythonBuffer b, int n) { PythonContext context = PythonContext.GetContext(b._context); return context.Operation( PythonOperationKind.Multiply, PythonOps.GetIndex(b._context, b._object, b.GetSlice()), n ); } public static object operator *(int n, PythonBuffer b) { PythonContext context = PythonContext.GetContext(b._context); return context.Operation( PythonOperationKind.Multiply, PythonOps.GetIndex(b._context, b._object, b.GetSlice()), n ); } public int __len__() { return Math.Max(_size, 0); } internal int Size { get { return _size; } } #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("<read-only buffer for 0x{0:X16}, size {1}, offset {2} at 0x{3:X16}>", PythonOps.Id(_object), _size, _offset, PythonOps.Id(this)); } #endregion /// <summary> /// A DynamicMetaObject which is just used to support custom conversions to COM. /// </summary> class BufferMeta : DynamicMetaObject, IComConvertible { public BufferMeta(Expression expr, BindingRestrictions restrictions, object value) : base(expr, restrictions, value) { } #region IComConvertible Members DynamicMetaObject IComConvertible.GetComMetaObject() { return new DynamicMetaObject( Expression.Call( typeof(PythonOps).GetMethod("ConvertBufferToByteArray"), Utils.Convert( Expression, typeof(PythonBuffer) ) ), BindingRestrictions.Empty ); } #endregion } #region IDynamicMetaObjectProvider Members DynamicMetaObject IDynamicMetaObjectProvider.GetMetaObject(Expression parameter) { return new BufferMeta(parameter, BindingRestrictions.Empty, this); } #endregion #region IList[System.Byte] implementation byte[] _objectByteCache = null; internal byte[] byteCache { get { return _objectByteCache ?? (_objectByteCache = PythonOps.ConvertBufferToByteArray(this)); } } [PythonHidden] int IList<byte>.IndexOf(byte item) { for (int i = 0; i < byteCache.Length; ++i) { if (byteCache[i] == item) return i; } return -1; } [PythonHidden] void IList<byte>.Insert(int index, byte item) { throw ReadOnlyError(); } [PythonHidden] void IList<byte>.RemoveAt(int index) { throw ReadOnlyError(); } byte IList<byte>.this[int index] { [PythonHidden] get { return byteCache[index]; } [PythonHidden] set { throw ReadOnlyError(); } } #endregion #region IEnumerable implementation [PythonHidden] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return byteCache.GetEnumerator(); } #endregion #region IEnumerable[System.Byte] implementation [PythonHidden] IEnumerator<byte> IEnumerable<byte>.GetEnumerator() { return ((IEnumerable<byte>)byteCache).GetEnumerator(); } #endregion #region ICollection[System.Byte] implementation [PythonHidden] void ICollection<byte>.Add(byte item) { throw ReadOnlyError(); } [PythonHidden] void ICollection<byte>.Clear() { throw ReadOnlyError(); } [PythonHidden] bool ICollection<byte>.Contains(byte item) { return ((IList<byte>)this).IndexOf(item) != -1; } [PythonHidden] void ICollection<byte>.CopyTo(byte[] array, int arrayIndex) { byteCache.CopyTo(array, arrayIndex); } [PythonHidden] bool ICollection<byte>.Remove(byte item) { throw ReadOnlyError(); } int ICollection<byte>.Count { [PythonHidden] get { return byteCache.Length; } } bool ICollection<byte>.IsReadOnly { [PythonHidden] get { return true; } } #endregion } /// <summary> /// A marker interface so we can recognize and access sequence members on our array objects. /// </summary> internal interface IPythonArray : IList<object> { string tostring(); } public interface IPythonBufferable { IntPtr UnsafeAddress { get; } int Size { get; } byte[] GetBytes(int offset, int length); } }
// *********************************************************************** // 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.Collections.ObjectModel; using System.Linq; using NUnit.Framework.Constraints; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { [TestFixture] public class DictionaryContainsKeyConstraintTests { [Test] public void SucceedsWhenKeyIsPresent() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainKey() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.ContainKey("Hola")); } [Test] public void SucceedsWhenKeyIsNotPresentUsingContainKey() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.Not.ContainKey("NotKey")); } [Test] public void FailsWhenKeyIsMissing() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; TestDelegate act = () => Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hallo")); Assert.That(act, Throws.Exception.TypeOf<AssertionException>()); } [Test] public void FailsWhenNotUsedAgainstADictionary() { List<KeyValuePair<string, string>> keyValuePairs = new List<KeyValuePair<string, string>>( new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }); TestDelegate act = () => Assert.That(keyValuePairs, new DictionaryContainsKeyConstraint("Hallo")); Assert.That(act, Throws.ArgumentException.With.Message.Contains("ContainsKey")); } #if !NETCOREAPP1_1 [Test] public void WorksWithNonGenericDictionary() { var dictionary = new Hashtable { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("Hello")); } #endif [Test, Obsolete] public void IgnoreCaseIsHonored() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").IgnoreCase); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingIsHonored() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").Using<string>((x, y) => StringUtil.Compare(x, y, true))); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void SucceedsWhenKeyIsPresentWhenDictionaryUsingCustomComparer() { var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenDictionaryUsingCustomComparer() { var dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, Does.ContainKey("hola")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingLookupCustomComparer() { var list = new List<string> { "ALICE", "BOB", "CATHERINE" }; ILookup<string, string> lookup = list.ToLookup(x => x, StringComparer.OrdinalIgnoreCase); Assert.That(lookup, Does.ContainKey("catherine")); } [Test] public void SucceedsWhenKeyIsNotPresentUsingContainsKeyUsingLookupDefaultComparer() { var list = new List<string> { "ALICE", "BOB", "CATHERINE" }; ILookup<string, string> lookup = list.ToLookup(x => x); Assert.That(lookup, !Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyWhenUsingKeyedCollectionCustomComparer() { var list = new TestKeyedCollection(StringComparer.OrdinalIgnoreCase) { "ALICE", "BOB", "CALUM" }; Assert.That(list, Does.ContainKey("calum")); } [Test] public void SucceedsWhenKeyIsNotPresentUsingContainsKeyUsingKeyedCollectionDefaultComparer() { var list = new TestKeyedCollection { "ALICE", "BOB", "CALUM" }; Assert.That(list, !Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableCustomComparer() { var table = new Hashtable(StringComparer.OrdinalIgnoreCase) { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(table, Does.ContainKey("alice")); } [Test] public void SucceedsWhenKeyIsPresentUsingContainsKeyUsingHashtableDefaultComparer() { var table = new Hashtable { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(table, !Does.ContainKey("calum")); } [Test] public void ShouldCallContainsKeysMethodWithTKeyParameterOnNewMethod() { var dictionary = new TestDictionaryGeneric<string, string> { { "ALICE", "BOB" }, { "CALUM", "DENNIS" } }; Assert.That(dictionary, Does.ContainKey("BOB")); } [Test] public void ShouldCallContainsKeysMethodOnDictionary() { var dictionary = new TestDictionary(20); Assert.That(dictionary, Does.ContainKey(20)); Assert.That(dictionary, !Does.ContainKey(10)); } [Test] public void ShouldCallContainsKeysMethodOnPlainDictionary() { var dictionary = new TestNonGenericDictionary(99); Assert.Catch<ArgumentException>(() => Assert.That(dictionary, Does.ContainKey(99))); } [Test] public void ShouldCallContainsKeysMethodOnObject() { var poco = new TestPlainContainsKey("David"); Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("David"))); } [Test] public void ShouldThrowWhenUsedOnObjectWithNonGenericContains() { var poco = new TestPlainObjectContainsNonGeneric("Peter"); Assert.Catch<ArgumentException>(() => Assert.That(poco, Does.ContainKey("Peter"))); } [Test] public void ShouldCallContainsWhenUsedOnObjectWithGenericContains() { var poco = new TestPlainObjectContainsGeneric<string>("Peter"); Assert.DoesNotThrow(() => Assert.That(poco, Does.ContainKey("Peter"))); } #if NET45 [Test] public void ShouldCallContainsKeysMethodOnReadOnlyInterface() { var dictionary = new TestReadOnlyDictionary("BOB"); Assert.That(dictionary, Does.ContainKey("BOB")); Assert.That(dictionary, !Does.ContainKey("ALICE")); } [Test] public void ShouldThrowWhenUsedWithISet() { var set = new TestSet(); Assert.Catch<ArgumentException>(() => Assert.That(set, Does.ContainKey("NotHappening"))); } #endif #if !NET20 [Test] public void ShouldCallContainsKeysMethodOnLookupInterface() { var dictionary = new TestLookup(20); Assert.That(dictionary, Does.ContainKey(20)); Assert.That(dictionary, !Does.ContainKey(43)); } #endif [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingDictionaryContainsKeyConstraintComparisonFunc() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("HELLO").Using<string, string>((x, y) => x.ToUpper().Equals(y.ToUpper()))); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingBaseCollectionItemsEqualConstraintNonGenericComparer() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hola").Using((IComparer)StringComparer.OrdinalIgnoreCase)); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingBaseCollectionItemsEqualConstraintGenericComparer() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hola").Using((IComparer<string>)StringComparer.OrdinalIgnoreCase)); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingBaseCollectionItemsEqualConstraintNonGenericEqualityComparer() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using((IEqualityComparer)StringComparer.OrdinalIgnoreCase)); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingBaseCollectionItemsEqualConstraintGenericEqualityComparer() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using((IEqualityComparer<string>)StringComparer.OrdinalIgnoreCase)); } [Test, Obsolete("DictionaryContainsKeyConstraint now uses the comparer which the dictionary is based on. To test using a comparer which the dictionary is not based on, use a collection constraint on the set of keys.")] public void UsingBaseCollectionItemsEqualConstraintComparerFunc() { var dictionary = new Dictionary<string, string> { { "Hello", "World" }, { "Hola", "Mundo" } }; Assert.That(dictionary, new DictionaryContainsKeyConstraint("hello").Using<string>((x, y) => x.ToLower().Equals(y.ToLower()))); } #region Test Assets public class TestPlainContainsKey { private readonly string _key; public TestPlainContainsKey(string key) { _key = key; } public bool ContainsKey(string key) { return _key.Equals(key); } } public class TestPlainObjectContainsNonGeneric { private readonly string _key; public TestPlainObjectContainsNonGeneric(string key) { _key = key; } public bool Contains(string key) { return _key.Equals(key); } } public class TestPlainObjectContainsGeneric<TKey> { private readonly TKey _key; public TestPlainObjectContainsGeneric(TKey key) { _key = key; } public bool Contains(TKey key) { return _key.Equals(key); } } public class TestKeyedCollection : KeyedCollection<string, string> { public TestKeyedCollection() { } public TestKeyedCollection(IEqualityComparer<string> comparer) : base(comparer) { } protected override string GetKeyForItem(string item) { return item; } } public class TestDictionaryGeneric<TKey, TItem> : Dictionary<TKey, TItem> { public new bool ContainsKey(TKey key) { return base.Values.Any(x => x.Equals(key)); } } public class TestDictionary : IDictionary<int, string> { private readonly int _key; public TestDictionary(int key) { _key = key; } public IEnumerator<KeyValuePair<int, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public void CopyTo(KeyValuePair<int, string>[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(KeyValuePair<int, string> item) { throw new NotImplementedException(); } public int Count { get; } public bool IsReadOnly { get; } public bool ContainsKey(int key) { return key == _key; } public void Add(int key, string value) { throw new NotImplementedException(); } public bool Remove(int key) { throw new NotImplementedException(); } public bool TryGetValue(int key, out string value) { throw new NotImplementedException(); } public string this[int key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ICollection<int> Keys { get; } public ICollection<string> Values { get; } } public class TestNonGenericDictionary : IDictionary { private readonly int _key; public TestNonGenericDictionary(int key) { _key = key; } public bool Contains(object key) { return _key == (int)key; } public void Add(object key, object value) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public IDictionaryEnumerator GetEnumerator() { throw new NotImplementedException(); } public void Remove(object key) { throw new NotImplementedException(); } public object this[object key] { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public ICollection Keys { get; } public ICollection Values { get; } public bool IsReadOnly { get; } public bool IsFixedSize { get; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get; } public object SyncRoot { get; } public bool IsSynchronized { get; } } #if !NET20 public class TestLookup : ILookup<int, string> { private readonly int _key; public TestLookup(int key) { _key = key; } public IEnumerator<IGrouping<int, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool Contains(int key) { return key == _key; } public int Count { get; } public IEnumerable<string> this[int key] { get { throw new NotImplementedException(); } } } #endif #if !NET20 && !NET35 && !NET40 public class TestReadOnlyDictionary : IReadOnlyDictionary<string, string> { private readonly string _key; public TestReadOnlyDictionary(string key) { _key = key; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get; } public bool ContainsKey(string key) { return _key == key; } public bool TryGetValue(string key, out string value) { throw new NotImplementedException(); } public string this[string key] { get { throw new NotImplementedException(); } } public IEnumerable<string> Keys { get; } public IEnumerable<string> Values { get; } } public class TestSet : ISet<int> { public IEnumerator<int> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void ICollection<int>.Add(int item) { throw new NotImplementedException(); } public void UnionWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void IntersectWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void ExceptWith(IEnumerable<int> other) { throw new NotImplementedException(); } public void SymmetricExceptWith(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsSubsetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsSupersetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsProperSupersetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool IsProperSubsetOf(IEnumerable<int> other) { throw new NotImplementedException(); } public bool Overlaps(IEnumerable<int> other) { throw new NotImplementedException(); } public bool SetEquals(IEnumerable<int> other) { throw new NotImplementedException(); } bool ISet<int>.Add(int item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(int item) { throw new NotImplementedException(); } public void CopyTo(int[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(int item) { throw new NotImplementedException(); } public int Count { get; } public bool IsReadOnly { get; } } #endif #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace ClosedXML.Excel { internal class XLRange : XLRangeBase, IXLRange { #region Constructor public XLRange(XLRangeParameters xlRangeParameters) : base(xlRangeParameters.RangeAddress, (xlRangeParameters.DefaultStyle as XLStyle).Value) { } #endregion Constructor public override XLRangeType RangeType { get { return XLRangeType.Range; } } #region IXLRange Members IXLRangeRow IXLRange.Row(Int32 row) { return Row(row); } IXLRangeColumn IXLRange.Column(Int32 columnNumber) { return Column(columnNumber); } IXLRangeColumn IXLRange.Column(String columnLetter) { return Column(columnLetter); } public virtual IXLRangeColumns Columns(Func<IXLRangeColumn, Boolean> predicate = null) { var retVal = new XLRangeColumns(); Int32 columnCount = ColumnCount(); for (Int32 c = 1; c <= columnCount; c++) { var column = Column(c); if (predicate == null || predicate(column)) retVal.Add(column); } return retVal; } public virtual IXLRangeColumns Columns(Int32 firstColumn, Int32 lastColumn) { var retVal = new XLRangeColumns(); for (int co = firstColumn; co <= lastColumn; co++) retVal.Add(Column(co)); return retVal; } public virtual IXLRangeColumns Columns(String firstColumn, String lastColumn) { return Columns(XLHelper.GetColumnNumberFromLetter(firstColumn), XLHelper.GetColumnNumberFromLetter(lastColumn)); } public virtual IXLRangeColumns Columns(String columns) { var retVal = new XLRangeColumns(); var columnPairs = columns.Split(','); foreach (string tPair in columnPairs.Select(pair => pair.Trim())) { String firstColumn; String lastColumn; if (tPair.Contains(':') || tPair.Contains('-')) { string[] columnRange = XLHelper.SplitRange(tPair); firstColumn = columnRange[0]; lastColumn = columnRange[1]; } else { firstColumn = tPair; lastColumn = tPair; } if (Int32.TryParse(firstColumn, out Int32 tmp)) { foreach (IXLRangeColumn col in Columns(Int32.Parse(firstColumn), Int32.Parse(lastColumn))) retVal.Add(col); } else { foreach (IXLRangeColumn col in Columns(firstColumn, lastColumn)) retVal.Add(col); } } return retVal; } IXLCell IXLRange.Cell(int row, int column) { return Cell(row, column); } IXLCell IXLRange.Cell(string cellAddressInRange) { return Cell(cellAddressInRange); } IXLCell IXLRange.Cell(int row, string column) { return Cell(row, column); } IXLCell IXLRange.Cell(IXLAddress cellAddressInRange) { return Cell(cellAddressInRange); } IXLRange IXLRange.Range(IXLRangeAddress rangeAddress) { return Range(rangeAddress); } IXLRange IXLRange.Range(string rangeAddress) { return Range(rangeAddress); } IXLRange IXLRange.Range(IXLCell firstCell, IXLCell lastCell) { return Range(firstCell, lastCell); } IXLRange IXLRange.Range(string firstCellAddress, string lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLRange.Range(IXLAddress firstCellAddress, IXLAddress lastCellAddress) { return Range(firstCellAddress, lastCellAddress); } IXLRange IXLRange.Range(int firstCellRow, int firstCellColumn, int lastCellRow, int lastCellColumn) { return Range(firstCellRow, firstCellColumn, lastCellRow, lastCellColumn); } public IXLRangeRows Rows(Func<IXLRangeRow, Boolean> predicate = null) { var retVal = new XLRangeRows(); Int32 rowCount = RowCount(); for (Int32 r = 1; r <= rowCount; r++) { var row = Row(r); if (predicate == null || predicate(row)) retVal.Add(Row(r)); } return retVal; } public IXLRangeRows Rows(Int32 firstRow, Int32 lastRow) { var retVal = new XLRangeRows(); for (int ro = firstRow; ro <= lastRow; ro++) retVal.Add(Row(ro)); return retVal; } public IXLRangeRows Rows(String rows) { var retVal = new XLRangeRows(); var rowPairs = rows.Split(','); foreach (string tPair in rowPairs.Select(pair => pair.Trim())) { String firstRow; String lastRow; if (tPair.Contains(':') || tPair.Contains('-')) { string[] rowRange = XLHelper.SplitRange(tPair); firstRow = rowRange[0]; lastRow = rowRange[1]; } else { firstRow = tPair; lastRow = tPair; } foreach (IXLRangeRow row in Rows(Int32.Parse(firstRow), Int32.Parse(lastRow))) retVal.Add(row); } return retVal; } public void Transpose(XLTransposeOptions transposeOption) { int rowCount = RowCount(); int columnCount = ColumnCount(); int squareSide = rowCount > columnCount ? rowCount : columnCount; var firstCell = FirstCell(); MoveOrClearForTranspose(transposeOption, rowCount, columnCount); TransposeMerged(squareSide); TransposeRange(squareSide); RangeAddress = new XLRangeAddress( RangeAddress.FirstAddress, new XLAddress(Worksheet, firstCell.Address.RowNumber + columnCount - 1, firstCell.Address.ColumnNumber + rowCount - 1, RangeAddress.LastAddress.FixedRow, RangeAddress.LastAddress.FixedColumn)); if (rowCount > columnCount) { var rng = Worksheet.Range( RangeAddress.LastAddress.RowNumber + 1, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber + (rowCount - columnCount), RangeAddress.LastAddress.ColumnNumber); rng.Delete(XLShiftDeletedCells.ShiftCellsUp); } else if (columnCount > rowCount) { var rng = Worksheet.Range( RangeAddress.FirstAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber + 1, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber + (columnCount - rowCount)); rng.Delete(XLShiftDeletedCells.ShiftCellsLeft); } foreach (IXLCell c in Range(1, 1, columnCount, rowCount).Cells()) { var border = (c.Style as XLStyle).Value.Border; c.Style.Border.TopBorder = border.LeftBorder; c.Style.Border.TopBorderColor = border.LeftBorderColor; c.Style.Border.LeftBorder = border.TopBorder; c.Style.Border.LeftBorderColor = border.TopBorderColor; c.Style.Border.RightBorder = border.BottomBorder; c.Style.Border.RightBorderColor = border.BottomBorderColor; c.Style.Border.BottomBorder = border.RightBorder; c.Style.Border.BottomBorderColor = border.RightBorderColor; } } public IXLTable AsTable() { return Worksheet.Table(this, false); } public IXLTable AsTable(String name) { return Worksheet.Table(this, name, false); } IXLTable IXLRange.CreateTable() { return CreateTable(); } public XLTable CreateTable() { return (XLTable)Worksheet.Table(this, true, true); } IXLTable IXLRange.CreateTable(String name) { return CreateTable(name); } public XLTable CreateTable(String name) { return (XLTable)Worksheet.Table(this, name, true, true); } public IXLTable CreateTable(String name, Boolean setAutofilter) { return Worksheet.Table(this, name, true, setAutofilter); } public new IXLRange CopyTo(IXLCell target) { base.CopyTo(target); Int32 lastRowNumber = target.Address.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; Int32 lastColumnNumber = target.Address.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range(target.Address.RowNumber, target.Address.ColumnNumber, lastRowNumber, lastColumnNumber); } public new IXLRange CopyTo(IXLRangeBase target) { base.CopyTo(target); Int32 lastRowNumber = target.RangeAddress.FirstAddress.RowNumber + RowCount() - 1; if (lastRowNumber > XLHelper.MaxRowNumber) lastRowNumber = XLHelper.MaxRowNumber; Int32 lastColumnNumber = target.RangeAddress.FirstAddress.ColumnNumber + ColumnCount() - 1; if (lastColumnNumber > XLHelper.MaxColumnNumber) lastColumnNumber = XLHelper.MaxColumnNumber; return target.Worksheet.Range(target.RangeAddress.FirstAddress.RowNumber, target.RangeAddress.FirstAddress.ColumnNumber, lastRowNumber, lastColumnNumber); } public IXLRange SetDataType(XLDataType dataType) { DataType = dataType; return this; } public new IXLRange Sort() { return base.Sort().AsRange(); } public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return base.Sort(columnsToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange(); } public new IXLRange Sort(Int32 columnToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return base.Sort(columnToSortBy, sortOrder, matchCase, ignoreBlanks).AsRange(); } public new IXLRange SortLeftToRight(XLSortOrder sortOrder = XLSortOrder.Ascending, Boolean matchCase = false, Boolean ignoreBlanks = true) { return base.SortLeftToRight(sortOrder, matchCase, ignoreBlanks).AsRange(); } #endregion IXLRange Members internal override void WorksheetRangeShiftedColumns(XLRange range, int columnsShifted) { RangeAddress = (XLRangeAddress)ShiftColumns(RangeAddress, range, columnsShifted); } internal override void WorksheetRangeShiftedRows(XLRange range, int rowsShifted) { RangeAddress = (XLRangeAddress)ShiftRows(RangeAddress, range, rowsShifted); } IXLRangeColumn IXLRange.FirstColumn(Func<IXLRangeColumn, Boolean> predicate) { return FirstColumn(predicate); } internal XLRangeColumn FirstColumn(Func<IXLRangeColumn, Boolean> predicate = null) { if (predicate == null) return Column(1); Int32 columnCount = ColumnCount(); for (Int32 c = 1; c <= columnCount; c++) { var column = Column(c); if (predicate(column)) return column; } return null; } IXLRangeColumn IXLRange.LastColumn(Func<IXLRangeColumn, Boolean> predicate) { return LastColumn(predicate); } internal XLRangeColumn LastColumn(Func<IXLRangeColumn, Boolean> predicate = null) { Int32 columnCount = ColumnCount(); if (predicate == null) return Column(columnCount); for (Int32 c = columnCount; c >= 1; c--) { var column = Column(c); if (predicate(column)) return column; } return null; } IXLRangeColumn IXLRange.FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate) { return FirstColumnUsed(XLCellsUsedOptions.AllContents, predicate); } internal XLRangeColumn FirstColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null) { return FirstColumnUsed(XLCellsUsedOptions.AllContents, predicate); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRangeColumn IXLRange.FirstColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate) { return FirstColumnUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeColumn IXLRange.FirstColumnUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate) { return FirstColumnUsed(options, predicate); } internal XLRangeColumn FirstColumnUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate = null) { if (predicate == null) { Int32 firstColumnUsed = Worksheet.Internals.CellsCollection.FirstColumnUsed( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, options); return firstColumnUsed == 0 ? null : Column(firstColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1); } Int32 columnCount = ColumnCount(); for (Int32 co = 1; co <= columnCount; co++) { var column = Column(co); if (!column.IsEmpty(options) && predicate(column)) return column; } return null; } IXLRangeColumn IXLRange.LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate) { return LastColumnUsed(XLCellsUsedOptions.AllContents, predicate); } internal XLRangeColumn LastColumnUsed(Func<IXLRangeColumn, Boolean> predicate = null) { return LastColumnUsed(XLCellsUsedOptions.AllContents, predicate); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRangeColumn IXLRange.LastColumnUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate) { return LastColumnUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeColumn IXLRange.LastColumnUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate) { return LastColumnUsed(options, predicate); } internal XLRangeColumn LastColumnUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate = null) { if (predicate == null) { Int32 lastColumnUsed = Worksheet.Internals.CellsCollection.LastColumnUsed( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, options); return lastColumnUsed == 0 ? null : Column(lastColumnUsed - RangeAddress.FirstAddress.ColumnNumber + 1); } Int32 columnCount = ColumnCount(); for (Int32 co = columnCount; co >= 1; co--) { var column = Column(co); if (!column.IsEmpty(options) && predicate(column)) return column; } return null; } IXLRangeRow IXLRange.FirstRow(Func<IXLRangeRow, Boolean> predicate) { return FirstRow(predicate); } public XLRangeRow FirstRow(Func<IXLRangeRow, Boolean> predicate = null) { if (predicate == null) return Row(1); Int32 rowCount = RowCount(); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = Row(ro); if (predicate(row)) return row; } return null; } IXLRangeRow IXLRange.LastRow(Func<IXLRangeRow, Boolean> predicate) { return LastRow(predicate); } public XLRangeRow LastRow(Func<IXLRangeRow, Boolean> predicate = null) { Int32 rowCount = RowCount(); if (predicate == null) return Row(rowCount); for (Int32 ro = rowCount; ro >= 1; ro--) { var row = Row(ro); if (predicate(row)) return row; } return null; } IXLRangeRow IXLRange.FirstRowUsed(Func<IXLRangeRow, Boolean> predicate) { return FirstRowUsed(XLCellsUsedOptions.AllContents, predicate); } internal XLRangeRow FirstRowUsed(Func<IXLRangeRow, Boolean> predicate = null) { return FirstRowUsed(XLCellsUsedOptions.AllContents, predicate); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRangeRow IXLRange.FirstRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate) { return FirstRowUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeRow IXLRange.FirstRowUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate) { return FirstRowUsed(options, predicate); } internal XLRangeRow FirstRowUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate = null) { if (predicate == null) { Int32 rowFromCells = Worksheet.Internals.CellsCollection.FirstRowUsed( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, options); //Int32 rowFromRows = Worksheet.Internals.RowsCollection.FirstRowUsed(includeFormats); return rowFromCells == 0 ? null : Row(rowFromCells - RangeAddress.FirstAddress.RowNumber + 1); } Int32 rowCount = RowCount(); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = Row(ro); if (!row.IsEmpty(options) && predicate(row)) return row; } return null; } IXLRangeRow IXLRange.LastRowUsed(Func<IXLRangeRow, Boolean> predicate) { return LastRowUsed(XLCellsUsedOptions.AllContents, predicate); } internal XLRangeRow LastRowUsed(Func<IXLRangeRow, Boolean> predicate = null) { return LastRowUsed(XLCellsUsedOptions.AllContents, predicate); } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRangeRow IXLRange.LastRowUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate) { return LastRowUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeRow IXLRange.LastRowUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate) { return LastRowUsed(options, predicate); } internal XLRangeRow LastRowUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate = null) { if (predicate == null) { Int32 lastRowUsed = Worksheet.Internals.CellsCollection.LastRowUsed( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber, options); return lastRowUsed == 0 ? null : Row(lastRowUsed - RangeAddress.FirstAddress.RowNumber + 1); } Int32 rowCount = RowCount(); for (Int32 ro = rowCount; ro >= 1; ro--) { var row = Row(ro); if (!row.IsEmpty(options) && predicate(row)) return row; } return null; } [Obsolete("Use the overload with XLCellsUsedOptions")] IXLRangeRows IXLRange.RowsUsed(Boolean includeFormats, Func<IXLRangeRow, Boolean> predicate) { return RowsUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeRows IXLRange.RowsUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate) { return RowsUsed(options, predicate); } internal XLRangeRows RowsUsed(XLCellsUsedOptions options, Func<IXLRangeRow, Boolean> predicate = null) { XLRangeRows rows = new XLRangeRows(); Int32 rowCount = RowCount(options); for (Int32 ro = 1; ro <= rowCount; ro++) { var row = Row(ro); if (!row.IsEmpty(options) && (predicate == null || predicate(row))) rows.Add(row); } return rows; } IXLRangeRows IXLRange.RowsUsed(Func<IXLRangeRow, Boolean> predicate) { return RowsUsed(predicate); } internal XLRangeRows RowsUsed(Func<IXLRangeRow, Boolean> predicate = null) { return RowsUsed(XLCellsUsedOptions.AllContents, predicate); } IXLRangeColumns IXLRange.ColumnsUsed(Boolean includeFormats, Func<IXLRangeColumn, Boolean> predicate) { return ColumnsUsed(includeFormats ? XLCellsUsedOptions.All : XLCellsUsedOptions.AllContents, predicate); } IXLRangeColumns IXLRange.ColumnsUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate) { return ColumnsUsed(options, predicate); } internal virtual XLRangeColumns ColumnsUsed(XLCellsUsedOptions options, Func<IXLRangeColumn, Boolean> predicate = null) { XLRangeColumns columns = new XLRangeColumns(); Int32 columnCount = ColumnCount(options); for (Int32 co = 1; co <= columnCount; co++) { var column = Column(co); if (!column.IsEmpty(options) && (predicate == null || predicate(column))) columns.Add(column); } return columns; } IXLRangeColumns IXLRange.ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate) { return ColumnsUsed(predicate); } internal virtual XLRangeColumns ColumnsUsed(Func<IXLRangeColumn, Boolean> predicate = null) { return ColumnsUsed(XLCellsUsedOptions.AllContents, predicate); } public XLRangeRow Row(Int32 row) { if (row <= 0 || row > XLHelper.MaxRowNumber + RangeAddress.FirstAddress.RowNumber - 1) throw new ArgumentOutOfRangeException(nameof(row), String.Format("Row number must be between 1 and {0}", XLHelper.MaxRowNumber + RangeAddress.FirstAddress.RowNumber - 1)); var firstCellAddress = new XLAddress(Worksheet, RangeAddress.FirstAddress.RowNumber + row - 1, RangeAddress.FirstAddress.ColumnNumber, false, false); var lastCellAddress = new XLAddress(Worksheet, RangeAddress.FirstAddress.RowNumber + row - 1, RangeAddress.LastAddress.ColumnNumber, false, false); return Worksheet.RangeRow(new XLRangeAddress(firstCellAddress, lastCellAddress)); } public virtual XLRangeColumn Column(Int32 columnNumber) { if (columnNumber <= 0 || columnNumber > XLHelper.MaxColumnNumber + RangeAddress.FirstAddress.ColumnNumber - 1) throw new ArgumentOutOfRangeException(nameof(columnNumber), String.Format("Column number must be between 1 and {0}", XLHelper.MaxColumnNumber + RangeAddress.FirstAddress.ColumnNumber - 1)); var firstCellAddress = new XLAddress(Worksheet, RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1, false, false); var lastCellAddress = new XLAddress(Worksheet, RangeAddress.LastAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber + columnNumber - 1, false, false); return Worksheet.RangeColumn(new XLRangeAddress(firstCellAddress, lastCellAddress)); } public virtual XLRangeColumn Column(String columnLetter) { return Column(XLHelper.GetColumnNumberFromLetter(columnLetter)); } internal IEnumerable<XLRange> Split(IXLRangeAddress anotherRange, bool includeIntersection) { if (!RangeAddress.Intersects(anotherRange)) { yield return this; yield break; } var thisRow1 = RangeAddress.FirstAddress.RowNumber; var thisRow2 = RangeAddress.LastAddress.RowNumber; var thisColumn1 = RangeAddress.FirstAddress.ColumnNumber; var thisColumn2 = RangeAddress.LastAddress.ColumnNumber; var otherRow1 = Math.Min(Math.Max(thisRow1, anotherRange.FirstAddress.RowNumber), thisRow2 + 1); var otherRow2 = Math.Max(Math.Min(thisRow2, anotherRange.LastAddress.RowNumber), thisRow1 - 1); var otherColumn1 = Math.Min(Math.Max(thisColumn1, anotherRange.FirstAddress.ColumnNumber), thisColumn2 + 1); var otherColumn2 = Math.Max(Math.Min(thisColumn2, anotherRange.LastAddress.ColumnNumber), thisColumn1 - 1); var candidates = new[] { // to the top of the intersection new XLRangeAddress( new XLAddress(thisRow1,thisColumn1, false, false), new XLAddress(otherRow1 - 1, thisColumn2, false, false)), // to the left of the intersection new XLRangeAddress( new XLAddress(otherRow1,thisColumn1, false, false), new XLAddress(otherRow2, otherColumn1 - 1, false, false)), includeIntersection ? new XLRangeAddress( new XLAddress(otherRow1, otherColumn1, false, false), new XLAddress(otherRow2, otherColumn2, false, false)) : XLRangeAddress.Invalid, // to the right of the intersection new XLRangeAddress( new XLAddress(otherRow1,otherColumn2 + 1, false, false), new XLAddress(otherRow2, thisColumn2, false, false)), // to the bottom of the intersection new XLRangeAddress( new XLAddress(otherRow2 + 1,thisColumn1, false, false), new XLAddress(thisRow2, thisColumn2, false, false)), }; foreach (var rangeAddress in candidates.Where(c => c.IsValid && c.IsNormalized)) { yield return Worksheet.Range(rangeAddress); } } private void TransposeRange(int squareSide) { var cellsToInsert = new Dictionary<XLSheetPoint, XLCell>(); var cellsToDelete = new List<XLSheetPoint>(); var rngToTranspose = Worksheet.Range( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.FirstAddress.RowNumber + squareSide - 1, RangeAddress.FirstAddress.ColumnNumber + squareSide - 1); Int32 roCount = rngToTranspose.RowCount(); Int32 coCount = rngToTranspose.ColumnCount(); for (Int32 ro = 1; ro <= roCount; ro++) { for (Int32 co = 1; co <= coCount; co++) { var oldCell = rngToTranspose.Cell(ro, co); var newKey = rngToTranspose.Cell(co, ro).Address; // new XLAddress(Worksheet, c.Address.ColumnNumber, c.Address.RowNumber); var newCell = new XLCell(Worksheet, newKey, oldCell.StyleValue); newCell.CopyFrom(oldCell, XLCellCopyOptions.All); cellsToInsert.Add(new XLSheetPoint(newKey.RowNumber, newKey.ColumnNumber), newCell); cellsToDelete.Add(new XLSheetPoint(oldCell.Address.RowNumber, oldCell.Address.ColumnNumber)); } } cellsToDelete.ForEach(c => Worksheet.Internals.CellsCollection.Remove(c)); cellsToInsert.ForEach(c => Worksheet.Internals.CellsCollection.Add(c.Key, c.Value)); } private void TransposeMerged(Int32 squareSide) { var rngToTranspose = Worksheet.Range( RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.FirstAddress.RowNumber + squareSide - 1, RangeAddress.FirstAddress.ColumnNumber + squareSide - 1); foreach (var merge in Worksheet.Internals.MergedRanges.Where(Contains).Cast<XLRange>()) { merge.RangeAddress = new XLRangeAddress( merge.RangeAddress.FirstAddress, rngToTranspose.Cell(merge.ColumnCount(), merge.RowCount()).Address); } } private void MoveOrClearForTranspose(XLTransposeOptions transposeOption, int rowCount, int columnCount) { if (transposeOption == XLTransposeOptions.MoveCells) { if (rowCount > columnCount) InsertColumnsAfter(false, rowCount - columnCount, false); else if (columnCount > rowCount) InsertRowsBelow(false, columnCount - rowCount, false); } else { if (rowCount > columnCount) { int toMove = rowCount - columnCount; var rngToClear = Worksheet.Range( RangeAddress.FirstAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber + 1, RangeAddress.LastAddress.RowNumber, RangeAddress.LastAddress.ColumnNumber + toMove); rngToClear.Clear(); } else if (columnCount > rowCount) { int toMove = columnCount - rowCount; var rngToClear = Worksheet.Range( RangeAddress.LastAddress.RowNumber + 1, RangeAddress.FirstAddress.ColumnNumber, RangeAddress.LastAddress.RowNumber + toMove, RangeAddress.LastAddress.ColumnNumber); rngToClear.Clear(); } } } public override bool Equals(object obj) { var other = obj as XLRange; if (other == null) return false; return RangeAddress.Equals(other.RangeAddress) && Worksheet.Equals(other.Worksheet); } public override int GetHashCode() { return RangeAddress.GetHashCode() ^ Worksheet.GetHashCode(); } public new IXLRange Clear(XLClearOptions clearOptions = XLClearOptions.All) { base.Clear(clearOptions); return this; } public IXLRangeColumn FindColumn(Func<IXLRangeColumn, bool> predicate) { Int32 columnCount = ColumnCount(); for (Int32 c = 1; c <= columnCount; c++) { var column = Column(c); if (predicate == null || predicate(column)) return column; } return null; } public IXLRangeRow FindRow(Func<IXLRangeRow, bool> predicate) { Int32 rowCount = RowCount(); for (Int32 r = 1; r <= rowCount; r++) { var row = Row(r); if (predicate(row)) return row; } return null; } public override string ToString() { if (IsEntireSheet()) { return Worksheet.Name; } else if (IsEntireRow()) { return String.Concat( Worksheet.Name.EscapeSheetName(), '!', RangeAddress.FirstAddress.RowNumber, ':', RangeAddress.LastAddress.RowNumber); } else if (IsEntireColumn()) { return String.Concat( Worksheet.Name.EscapeSheetName(), '!', RangeAddress.FirstAddress.ColumnLetter, ':', RangeAddress.LastAddress.ColumnLetter); } else return base.ToString(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Windows.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Projection; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces { public class TestWorkspace : Workspace { public const string WorkspaceName = "Test"; public ExportProvider ExportProvider { get; } public bool CanApplyChangeDocument { get; set; } internal override bool CanChangeActiveContextDocument { get { return true; } } public IList<TestHostProject> Projects { get; } public IList<TestHostDocument> Documents { get; } public IList<TestHostDocument> AdditionalDocuments { get; } public IList<TestHostDocument> ProjectionDocuments { get; } private readonly BackgroundCompiler _backgroundCompiler; private readonly BackgroundParser _backgroundParser; public TestWorkspace() : this(TestExportProvider.ExportProviderWithCSharpAndVisualBasic, WorkspaceName) { } public TestWorkspace(ExportProvider exportProvider, string workspaceKind = null, bool disablePartialSolutions = true) : base(MefV1HostServices.Create(exportProvider.AsExportProvider()), workspaceKind ?? WorkspaceName) { ResetThreadAffinity(); this.TestHookPartialSolutionsDisabled = disablePartialSolutions; this.ExportProvider = exportProvider; this.Projects = new List<TestHostProject>(); this.Documents = new List<TestHostDocument>(); this.AdditionalDocuments = new List<TestHostDocument>(); this.ProjectionDocuments = new List<TestHostDocument>(); this.CanApplyChangeDocument = true; _backgroundCompiler = new BackgroundCompiler(this); _backgroundParser = new BackgroundParser(this); _backgroundParser.Start(); } /// <summary> /// Reset the thread affinity, in particular the designated foreground thread, to the active /// thread. /// </summary> internal static void ResetThreadAffinity(ForegroundThreadData foregroundThreadData = null) { foregroundThreadData = foregroundThreadData ?? ForegroundThreadAffinitizedObject.CurrentForegroundThreadData; // HACK: When the platform team took over several of our components they created a copy // of ForegroundThreadAffinitizedObject. This needs to be reset in the same way as our copy // does. Reflection is the only choice at the moment. foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies()) { var type = assembly.GetType("Microsoft.VisualStudio.Language.Intellisense.Implementation.ForegroundThreadAffinitizedObject", throwOnError: false); if (type != null) { type.GetField("foregroundThread", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.Thread); type.GetField("ForegroundTaskScheduler", BindingFlags.Static | BindingFlags.NonPublic).SetValue(null, foregroundThreadData.TaskScheduler); break; } } } protected internal override bool PartialSemanticsEnabled { get { return _backgroundCompiler != null; } } public TestHostDocument DocumentWithCursor { get { return Documents.Single(d => d.CursorPosition.HasValue && !d.IsLinkFile); } } protected override void OnDocumentTextChanged(Document document) { if (_backgroundParser != null) { _backgroundParser.Parse(document); } } protected override void OnDocumentClosing(DocumentId documentId) { if (_backgroundParser != null) { _backgroundParser.CancelParse(documentId); } } public new void RegisterText(SourceTextContainer text) { base.RegisterText(text); } protected override void Dispose(bool finalize) { var metadataAsSourceService = ExportProvider.GetExportedValues<IMetadataAsSourceFileService>().FirstOrDefault(); if (metadataAsSourceService != null) { metadataAsSourceService.CleanupGeneratedFiles(); } this.ClearSolutionData(); foreach (var document in Documents) { document.CloseTextView(); } foreach (var document in AdditionalDocuments) { document.CloseTextView(); } foreach (var document in ProjectionDocuments) { document.CloseTextView(); } var exceptions = ExportProvider.GetExportedValue<TestExtensionErrorHandler>().GetExceptions(); if (exceptions.Count == 1) { throw exceptions.Single(); } else if (exceptions.Count > 1) { throw new AggregateException(exceptions); } if (SynchronizationContext.Current != null) { Dispatcher.CurrentDispatcher.DoEvents(); } if (_backgroundParser != null) { _backgroundParser.CancelAllParses(); } base.Dispose(finalize); } internal void AddTestSolution(TestHostSolution solution) { this.OnSolutionAdded(SolutionInfo.Create(solution.Id, solution.Version, solution.FilePath, projects: solution.Projects.Select(p => p.ToProjectInfo()))); } public void AddTestProject(TestHostProject project) { if (!this.Projects.Contains(project)) { this.Projects.Add(project); foreach (var doc in project.Documents) { this.Documents.Add(doc); } foreach (var doc in project.AdditionalDocuments) { this.AdditionalDocuments.Add(doc); } } this.OnProjectAdded(project.ToProjectInfo()); } public new void OnProjectRemoved(ProjectId projectId) { base.OnProjectRemoved(projectId); } public new void OnProjectReferenceAdded(ProjectId projectId, ProjectReference projectReference) { base.OnProjectReferenceAdded(projectId, projectReference); } public new void OnProjectReferenceRemoved(ProjectId projectId, ProjectReference projectReference) { base.OnProjectReferenceRemoved(projectId, projectReference); } public new Task OnDocumentOpenedAsync(DocumentId documentId, SourceTextContainer textContainer, bool isCurrentContext = true) { return base.OnDocumentOpenedAsync(documentId, textContainer, isCurrentContext); } public void OnDocumentClosed(DocumentId documentId) { var testDocument = this.GetTestDocument(documentId); this.OnDocumentClosed(documentId, testDocument.Loader); } public new void OnParseOptionsChanged(ProjectId projectId, ParseOptions parseOptions) { base.OnParseOptionsChanged(projectId, parseOptions); } public new void OnDocumentRemoved(DocumentId documentId) { base.OnDocumentRemoved(documentId); } public new void OnDocumentSourceCodeKindChanged(DocumentId documentId, SourceCodeKind sourceCodeKind) { base.OnDocumentSourceCodeKindChanged(documentId, sourceCodeKind); } public DocumentId GetDocumentId(TestHostDocument hostDocument) { if (!Documents.Contains(hostDocument) && !AdditionalDocuments.Contains(hostDocument)) { return null; } return hostDocument.Id; } public TestHostDocument GetTestDocument(DocumentId documentId) { return this.Documents.FirstOrDefault(d => d.Id == documentId); } public TestHostDocument GetTestAdditionalDocument(DocumentId documentId) { return this.AdditionalDocuments.FirstOrDefault(d => d.Id == documentId); } public TestHostProject GetTestProject(DocumentId documentId) { return GetTestProject(documentId.ProjectId); } public TestHostProject GetTestProject(ProjectId projectId) { return this.Projects.FirstOrDefault(p => p.Id == projectId); } public TServiceInterface GetService<TServiceInterface>() { return ExportProvider.GetExportedValue<TServiceInterface>(); } public override bool CanApplyChange(ApplyChangesKind feature) { switch (feature) { case ApplyChangesKind.AddDocument: case ApplyChangesKind.RemoveDocument: case ApplyChangesKind.AddAdditionalDocument: case ApplyChangesKind.RemoveAdditionalDocument: return true; case ApplyChangesKind.ChangeDocument: case ApplyChangesKind.ChangeAdditionalDocument: return this.CanApplyChangeDocument; default: return false; } } protected override void ApplyDocumentTextChanged(DocumentId document, SourceText newText) { var testDocument = this.GetTestDocument(document); testDocument.Update(newText); } protected override void ApplyDocumentAdded(DocumentInfo info, SourceText text) { var hostProject = this.GetTestProject(info.Id.ProjectId); var hostDocument = new TestHostDocument(text.ToString(), info.Name, info.SourceCodeKind, info.Id); hostProject.AddDocument(hostDocument); this.OnDocumentAdded(hostDocument.ToDocumentInfo()); } protected override void ApplyDocumentRemoved(DocumentId documentId) { var hostProject = this.GetTestProject(documentId.ProjectId); var hostDocument = this.GetTestDocument(documentId); hostProject.RemoveDocument(hostDocument); this.OnDocumentRemoved(documentId); } protected override void ApplyAdditionalDocumentTextChanged(DocumentId document, SourceText newText) { var testDocument = this.GetTestAdditionalDocument(document); testDocument.Update(newText); } protected override void ApplyAdditionalDocumentAdded(DocumentInfo info, SourceText text) { var hostProject = this.GetTestProject(info.Id.ProjectId); var hostDocument = new TestHostDocument(text.ToString(), info.Name, id: info.Id); hostProject.AddAdditionalDocument(hostDocument); this.OnAdditionalDocumentAdded(hostDocument.ToDocumentInfo()); } protected override void ApplyAdditionalDocumentRemoved(DocumentId documentId) { var hostProject = this.GetTestProject(documentId.ProjectId); var hostDocument = this.GetTestAdditionalDocument(documentId); hostProject.RemoveAdditionalDocument(hostDocument); this.OnAdditionalDocumentRemoved(documentId); } internal override void SetDocumentContext(DocumentId documentId) { OnDocumentContextUpdated(documentId); } /// <summary> /// Creates a TestHostDocument backed by a projection buffer. The surface buffer is /// described by a markup string with {|name:|} style pointers to annotated spans that can /// be found in one of a set of provided documents. Unnamed spans in the documents (which /// must have both endpoints inside an annotated spans) and in the surface buffer markup are /// mapped and included in the resulting document. /// /// If the markup string has the caret indicator "$$", then the caret will be placed at the /// corresponding position. If it does not, then the first span mapped into the projection /// buffer that contains the caret from its document is used. /// /// The result is a new TestHostDocument backed by a projection buffer including tracking /// spans from any number of documents and inert text from the markup itself. /// /// As an example, consider surface buffer markup /// ABC [|DEF|] [|GHI[|JKL|]|]{|S1:|} [|MNO{|S2:|}PQR S$$TU|] {|S4:|}{|S5:|}{|S3:|} /// /// This contains 4 unnamed spans and references to 5 spans that should be found and /// included. Consider an included base document created from the following markup: /// /// public class C /// { /// public void M1() /// { /// {|S1:int [|abc[|d$$ef|]|] = foo;|} /// int y = foo; /// {|S2:int [|def|] = foo;|} /// int z = {|S3:123|} + {|S4:456|} + {|S5:789|}; /// } /// } /// /// The resulting projection buffer (with unnamed span markup preserved) would look like: /// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123 /// /// The union of unnamed spans from the surface buffer markup and each of the projected /// spans is sorted as it would have been sorted by MarkupTestFile had it parsed the entire /// projection buffer as one file, which it would do in a stack-based manner. In our example, /// the order of the unnamed spans would be as follows: /// /// ABC [|DEF|] [|GHI[|JKL|]|]int [|abc[|d$$ef|]|] = foo; [|MNOint [|def|] = foo;PQR S$$TU|] 456789123 /// -----1 -----2 -------4 -----6 /// ------------3 --------------5 --------------------------------7 /// </summary> /// <param name="markup">Describes the surface buffer, and contains a mix of inert text, /// named spans and unnamed spans. Any named spans must contain only the name portion /// (e.g. {|Span1:|} which must match the name of a span in one of the baseDocuments. /// Annotated spans cannot be nested but they can be adjacent, in which case order will be /// preserved. The markup may also contain the caret indicator.</param> /// <param name="baseDocuments">The set of documents from which the projection buffer /// document will be composed.</param> /// <returns></returns> public TestHostDocument CreateProjectionBufferDocument(string markup, IList<TestHostDocument> baseDocuments, string languageName, string path = "projectionbufferdocumentpath", ProjectionBufferOptions options = ProjectionBufferOptions.None, IProjectionEditResolver editResolver = null) { IList<object> projectionBufferSpans; Dictionary<string, IList<TextSpan>> mappedSpans; int? mappedCaretLocation; GetSpansAndCaretFromSurfaceBufferMarkup(markup, baseDocuments, out projectionBufferSpans, out mappedSpans, out mappedCaretLocation); var projectionBufferFactory = this.GetService<IProjectionBufferFactoryService>(); var projectionBuffer = projectionBufferFactory.CreateProjectionBuffer(editResolver, projectionBufferSpans, options); // Add in mapped spans from each of the base documents foreach (var document in baseDocuments) { mappedSpans[string.Empty] = mappedSpans.ContainsKey(string.Empty) ? mappedSpans[string.Empty] : new List<TextSpan>(); foreach (var span in document.SelectedSpans) { var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot); var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single(); mappedSpans[string.Empty].Add(mappedSpan.ToTextSpan()); } // Order unnamed spans as they would be ordered by the normal span finding // algorithm in MarkupTestFile mappedSpans[string.Empty] = mappedSpans[string.Empty].OrderBy(s => s.End).ThenBy(s => -s.Start).ToList(); foreach (var kvp in document.AnnotatedSpans) { mappedSpans[kvp.Key] = mappedSpans.ContainsKey(kvp.Key) ? mappedSpans[kvp.Key] : new List<TextSpan>(); foreach (var span in kvp.Value) { var snapshotSpan = span.ToSnapshotSpan(document.TextBuffer.CurrentSnapshot); var mappedSpan = projectionBuffer.CurrentSnapshot.MapFromSourceSnapshot(snapshotSpan).Single(); mappedSpans[kvp.Key].Add(mappedSpan.ToTextSpan()); } } } var languageServices = this.Services.GetLanguageServices(languageName); var projectionDocument = new TestHostDocument( TestExportProvider.ExportProviderWithCSharpAndVisualBasic, languageServices, projectionBuffer, path, mappedCaretLocation, mappedSpans); this.ProjectionDocuments.Add(projectionDocument); return projectionDocument; } private void GetSpansAndCaretFromSurfaceBufferMarkup(string markup, IList<TestHostDocument> baseDocuments, out IList<object> projectionBufferSpans, out Dictionary<string, IList<TextSpan>> mappedMarkupSpans, out int? mappedCaretLocation) { IDictionary<string, IList<TextSpan>> markupSpans; projectionBufferSpans = new List<object>(); var projectionBufferSpanStartingPositions = new List<int>(); mappedCaretLocation = null; string inertText; int? markupCaretLocation; MarkupTestFile.GetPositionAndSpans(markup, out inertText, out markupCaretLocation, out markupSpans); var namedSpans = markupSpans.Where(kvp => kvp.Key != string.Empty); var sortedAndNamedSpans = namedSpans.OrderBy(kvp => kvp.Value.Single().Start) .ThenBy(kvp => markup.IndexOf("{|" + kvp.Key + ":|}", StringComparison.Ordinal)); var currentPositionInInertText = 0; var currentPositionInProjectionBuffer = 0; // If the markup points to k spans, these k spans divide the inert text into k + 1 // possibly empty substrings. When handling each span, also handle the inert text that // immediately precedes it. At the end, handle the trailing inert text foreach (var spanNameToListMap in sortedAndNamedSpans) { var spanName = spanNameToListMap.Key; var spanLocation = spanNameToListMap.Value.Single().Start; // Get any inert text between this and the previous span if (currentPositionInInertText < spanLocation) { var textToAdd = inertText.Substring(currentPositionInInertText, spanLocation - currentPositionInInertText); projectionBufferSpans.Add(textToAdd); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); // If the caret is in the markup and in this substring, calculate the final // caret location if (mappedCaretLocation == null && markupCaretLocation != null && currentPositionInInertText + textToAdd.Length >= markupCaretLocation) { var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText; } currentPositionInInertText += textToAdd.Length; currentPositionInProjectionBuffer += textToAdd.Length; } // Find and insert the span from the corresponding document var documentWithSpan = baseDocuments.FirstOrDefault(d => d.AnnotatedSpans.ContainsKey(spanName)); if (documentWithSpan == null) { continue; } markupSpans.Remove(spanName); var matchingSpan = documentWithSpan.AnnotatedSpans[spanName].Single(); var span = new Span(matchingSpan.Start, matchingSpan.Length); var trackingSpan = documentWithSpan.TextBuffer.CurrentSnapshot.CreateTrackingSpan(span, SpanTrackingMode.EdgeExclusive); projectionBufferSpans.Add(trackingSpan); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); // If the caret is not in markup but is in this span, then calculate the final // caret location. Note - if we find the caret marker in this document, then // we DO want to map it up, even if it's at the end of the span for this document. // This is not ambiguous for us, since we have explicit delimiters between the buffer // so it's clear which document the caret is in. if (mappedCaretLocation == null && markupCaretLocation == null && documentWithSpan.CursorPosition.HasValue && (matchingSpan.Contains(documentWithSpan.CursorPosition.Value) || matchingSpan.End == documentWithSpan.CursorPosition.Value)) { var caretOffsetInSpan = documentWithSpan.CursorPosition.Value - matchingSpan.Start; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInSpan; } currentPositionInProjectionBuffer += matchingSpan.Length; } // Handle any inert text after the final projected span if (currentPositionInInertText < inertText.Length - 1) { projectionBufferSpans.Add(inertText.Substring(currentPositionInInertText)); projectionBufferSpanStartingPositions.Add(currentPositionInProjectionBuffer); if (mappedCaretLocation == null && markupCaretLocation != null && markupCaretLocation >= currentPositionInInertText) { var caretOffsetInCurrentText = markupCaretLocation.Value - currentPositionInInertText; mappedCaretLocation = currentPositionInProjectionBuffer + caretOffsetInCurrentText; } } MapMarkupSpans(markupSpans, out mappedMarkupSpans, projectionBufferSpans, projectionBufferSpanStartingPositions); } private void MapMarkupSpans(IDictionary<string, IList<TextSpan>> markupSpans, out Dictionary<string, IList<TextSpan>> mappedMarkupSpans, IList<object> projectionBufferSpans, IList<int> projectionBufferSpanStartingPositions) { mappedMarkupSpans = new Dictionary<string, IList<TextSpan>>(); foreach (string key in markupSpans.Keys) { mappedMarkupSpans[key] = new List<TextSpan>(); foreach (var markupSpan in markupSpans[key]) { var positionInMarkup = 0; var spanIndex = 0; var markupSpanStart = markupSpan.Start; var markupSpanEndExclusive = markupSpan.Start + markupSpan.Length; int? spanStartLocation = null; int? spanEndLocationExclusive = null; foreach (var projectionSpan in projectionBufferSpans) { var text = projectionSpan as string; if (text != null) { if (spanStartLocation == null && positionInMarkup <= markupSpanStart && markupSpanStart <= positionInMarkup + text.Length) { var offsetInText = markupSpanStart - positionInMarkup; spanStartLocation = projectionBufferSpanStartingPositions[spanIndex] + offsetInText; } if (spanEndLocationExclusive == null && positionInMarkup <= markupSpanEndExclusive && markupSpanEndExclusive <= positionInMarkup + text.Length) { var offsetInText = markupSpanEndExclusive - positionInMarkup; spanEndLocationExclusive = projectionBufferSpanStartingPositions[spanIndex] + offsetInText; break; } positionInMarkup += text.Length; } spanIndex++; } mappedMarkupSpans[key].Add(new TextSpan(spanStartLocation.Value, spanEndLocationExclusive.Value - spanStartLocation.Value)); } } } public override void OpenDocument(DocumentId documentId, bool activate = true) { OnDocumentOpened(documentId, this.CurrentSolution.GetDocument(documentId).GetTextAsync().Result.Container); } public override void CloseDocument(DocumentId documentId) { var currentDoc = this.CurrentSolution.GetDocument(documentId); OnDocumentClosed(documentId, TextLoader.From(TextAndVersion.Create(currentDoc.GetTextAsync().Result, currentDoc.GetTextVersionAsync().Result))); } public void ChangeDocument(DocumentId documentId, SourceText text) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(oldSolution.WithDocumentText(documentId, text)); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.DocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId); } public void ChangeAdditionalDocument(DocumentId documentId, SourceText text) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(oldSolution.WithAdditionalDocumentText(documentId, text)); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.AdditionalDocumentChanged, oldSolution, newSolution, documentId.ProjectId, documentId); } public void ChangeProject(ProjectId projectId, Solution solution) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(solution); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.ProjectChanged, oldSolution, newSolution, projectId); } public new void ClearSolution() { base.ClearSolution(); } public void ChangeSolution(Solution solution) { var oldSolution = this.CurrentSolution; var newSolution = this.SetCurrentSolution(solution); this.RaiseWorkspaceChangedEventAsync(WorkspaceChangeKind.SolutionChanged, oldSolution, newSolution); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; using Orleans.Internal; namespace Orleans.Runtime.GrainDirectory { [Serializable] internal class ActivationInfo { public SiloAddress SiloAddress { get; private set; } public DateTime TimeCreated { get; private set; } public ActivationInfo(SiloAddress siloAddress) { SiloAddress = siloAddress; TimeCreated = DateTime.UtcNow; } public ActivationInfo(ActivationInfo iActivationInfo) { SiloAddress = iActivationInfo.SiloAddress; TimeCreated = iActivationInfo.TimeCreated; } public override string ToString() { return String.Format("{0}, {1}", SiloAddress, TimeCreated); } } [Serializable] internal class GrainInfo { public const int NO_ETAG = -1; public GrainAddress Activation { get; private set; } public DateTime TimeCreated { get; private set; } public int VersionTag { get; private set; } public bool OkToRemove(UnregistrationCause cause, TimeSpan lazyDeregistrationDelay) { switch (cause) { case UnregistrationCause.Force: return true; case UnregistrationCause.NonexistentActivation: { var delayparameter = lazyDeregistrationDelay; if (delayparameter <= TimeSpan.Zero) return false; // no lazy deregistration else return (TimeCreated <= DateTime.UtcNow - delayparameter); } default: throw new OrleansException("unhandled case"); } } public GrainAddress TryAddSingleActivation(GrainAddress address) { if (Activation is { } existing) { return existing; } else { Activation = address; TimeCreated = DateTime.UtcNow; VersionTag = ThreadSafeRandom.Next(); return address; } } public bool RemoveActivation(ActivationId act, UnregistrationCause cause, TimeSpan lazyDeregistrationDelay, out bool wasRemoved) { wasRemoved = false; if (Activation is { } existing && existing.ActivationId.Equals(act) && OkToRemove(cause, lazyDeregistrationDelay)) { wasRemoved = true; Activation = null; VersionTag = ThreadSafeRandom.Next(); } return wasRemoved; } public GrainAddress Merge(GrainInfo other) { var otherActivation = other.Activation; if (otherActivation is not null && Activation is null) { Activation = other.Activation; TimeCreated = other.TimeCreated; VersionTag = ThreadSafeRandom.Next(); } else if (Activation is not null && otherActivation is not null) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. if (Activation.ActivationId.Key.CompareTo(otherActivation.ActivationId.Key) < 0) { var activationToDrop = Activation; Activation = otherActivation; TimeCreated = other.TimeCreated; VersionTag = ThreadSafeRandom.Next(); return activationToDrop; } // Keep this activation and destroy the other. return otherActivation; } return null; } } internal class GrainDirectoryPartition { // Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full // parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do // a lot more lookups and so can sort periodically? /// <summary> /// contains a map from grain to its list of activations along with the version (etag) counter for the list /// </summary> private Dictionary<GrainId, GrainInfo> partitionData; private readonly object lockable; private readonly ILogger log; private readonly ILoggerFactory loggerFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly IOptions<GrainDirectoryOptions> grainDirectoryOptions; internal int Count { get { return partitionData.Count; } } public GrainDirectoryPartition(ISiloStatusOracle siloStatusOracle, IOptions<GrainDirectoryOptions> grainDirectoryOptions, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory) { partitionData = new Dictionary<GrainId, GrainInfo>(); lockable = new object(); log = loggerFactory.CreateLogger<GrainDirectoryPartition>(); this.siloStatusOracle = siloStatusOracle; this.grainDirectoryOptions = grainDirectoryOptions; this.grainFactory = grainFactory; this.loggerFactory = loggerFactory; } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } internal void Clear() { lock (lockable) { partitionData.Clear(); } } /// <summary> /// Returns all entries stored in the partition as an enumerable collection /// </summary> /// <returns></returns> public List<KeyValuePair<GrainId, GrainInfo>> GetItems() { lock (lockable) { return partitionData.ToList(); } } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <returns>The registered ActivationAddress and version associated with this directory mapping</returns> internal virtual AddressAndTag AddSingleActivation(GrainAddress address) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding single activation for grain {0}{1}{2}", address.SiloAddress, address.GrainId, address.ActivationId); AddressAndTag result = new AddressAndTag(); if (!IsValidSilo(address.SiloAddress)) { var siloStatus = this.siloStatusOracle.GetApproximateSiloStatus(address.SiloAddress); throw new OrleansException($"Trying to register {address.GrainId} on invalid silo: {address.SiloAddress}. Known status: {siloStatus}"); } GrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(address.GrainId, out grainInfo)) { partitionData[address.GrainId] = grainInfo = new GrainInfo(); } result.Address = grainInfo.TryAddSingleActivation(address); result.VersionTag = grainInfo.VersionTag; } return result; } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force) { var wasRemoved = false; lock (lockable) { if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, this.grainDirectoryOptions.Value.LazyDeregistrationDelay, out wasRemoved)) { // if the last activation for the grain was removed, we remove the entire grain info partitionData.Remove(grain); } } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved); } /// <summary> /// Removes the grain (and, effectively, all its activations) from the directory /// </summary> /// <param name="grain"></param> internal void RemoveGrain(GrainId grain) { lock (lockable) { partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing grain {0}", grain.ToString()); } internal AddressAndTag LookUpActivation(GrainId grain) { var result = new AddressAndTag(); lock (lockable) { if (!partitionData.TryGetValue(grain, out var grainInfo) || grainInfo.Activation is null) { return result; } result.Address = grainInfo.Activation; result.VersionTag = grainInfo.VersionTag; } if (!IsValidSilo(result.Address.SiloAddress)) { result.Address = null; } return result; } /// <summary> /// Returns the version number of the list of activations for the grain. /// If the grain is not found, -1 is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal int GetGrainETag(GrainId grain) { GrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainInfo.NO_ETAG; } return grainInfo.VersionTag; } } /// <summary> /// Merges one partition into another, assuming partitions are disjoint. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="other"></param> /// <returns>Activations which must be deactivated.</returns> internal Dictionary<SiloAddress, List<GrainAddress>> Merge(GrainDirectoryPartition other) { Dictionary<SiloAddress, List<GrainAddress>> activationsToRemove = null; lock (lockable) { foreach (var pair in other.partitionData) { if (partitionData.ContainsKey(pair.Key)) { if (log.IsEnabled(LogLevel.Debug)) log.Debug("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions"); var activationToDrop = partitionData[pair.Key].Merge(pair.Value); if (activationToDrop == null) continue; activationsToRemove ??= new Dictionary<SiloAddress, List<GrainAddress>>(); if (activationsToRemove.TryGetValue(activationToDrop.SiloAddress, out var activations)) { activations.Add(activationToDrop); } else { activationsToRemove[activationToDrop.SiloAddress] = new() { activationToDrop }; } } else { partitionData.Add(pair.Key, pair.Value); } } } return activationsToRemove; } /// <summary> /// Runs through all entries in the partition and moves/copies (depending on the given flag) the /// entries satisfying the given predicate into a new partition. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param> /// <param name="modifyOrigin">flag controlling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param> /// <returns>new grain directory partition containing entries satisfying the given predicate</returns> internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin) { var newDirectory = new GrainDirectoryPartition(this.siloStatusOracle, this.grainDirectoryOptions, this.grainFactory, this.loggerFactory); if (modifyOrigin) { // SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here List<KeyValuePair<GrainId, GrainInfo>> pairs; lock (lockable) { pairs = partitionData.Where(pair => predicate(pair.Key)).ToList(); } foreach (var pair in pairs) { newDirectory.partitionData.Add(pair.Key, pair.Value); } lock (lockable) { foreach (var pair in pairs) { partitionData.Remove(pair.Key); } } } else { lock (lockable) { foreach (var pair in partitionData.Where(pair => predicate(pair.Key))) { newDirectory.partitionData.Add(pair.Key, pair.Value); } } } return newDirectory; } internal List<GrainAddress> ToListOfActivations() { var result = new List<GrainAddress>(); lock (lockable) { foreach (var pair in partitionData) { if (pair.Value.Activation is { } address && IsValidSilo(address.SiloAddress)) { result.Add(address); } } } return result; } /// <summary> /// Sets the internal partition dictionary to the one given as input parameter. /// This method is supposed to be used by handoff manager to update the old partition with a new partition. /// </summary> /// <param name="newPartitionData">new internal partition dictionary</param> internal void Set(Dictionary<GrainId, GrainInfo> newPartitionData) { partitionData = newPartitionData; } /// <summary> /// Updates partition with a new delta of changes. /// This method is supposed to be used by handoff manager to update the partition with a set of delta changes. /// </summary> /// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition. /// If the value for a given key in the delta is valid, then existing entry in the partition is replaced. /// Otherwise, i.e., if the value is null, the corresponding entry is removed. /// </param> internal void Update(Dictionary<GrainId, GrainInfo> newPartitionDelta) { lock (lockable) { foreach (var kv in newPartitionDelta) { if (kv.Value != null) { partitionData[kv.Key] = kv.Value; } else { partitionData.Remove(kv.Key); } } } } public override string ToString() { var sb = new StringBuilder(); lock (lockable) { foreach (var grainEntry in partitionData) { if (grainEntry.Value.Activation is { } activation) { sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]"). Append(" => ").Append(activation.GrainId.ToString()). Append(" @ ").AppendLine(activation.ToString()); } } } return sb.ToString(); } } }
// Copyright (c) 2021 Alachisoft // // 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; using Alachisoft.NCache.Runtime.Serialization.IO; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Common.Net; namespace Alachisoft.NCache.Caching.Statistics { /// <summary> /// Info class that holds statistics related to cluster. /// </summary> [Serializable] public class ClusterCacheStatistics : CacheStatistics, ICloneable,ICompactSerializable { /// <summary> The name of the group participating in the cluster. </summary> private string _groupName; /// <summary> The name of the group participating in the cluster. </summary> private string _channelType; /// <summary> The number of nodes in the cluster that are providers or consumers, i.e., group members. </summary> private int _memberCount; /// <summary> The number of nodes in the cluster that are storage enabled. </summary> private int _serverCount; /// <summary> The number of nodes in the cluster that are unknown, i.e., different cache scheme. </summary> private int _otherCount; /// <summary> The statistics of the local node. </summary> private NodeInfo _localNode; /// <summary> The statistics of individual nodes. </summary> private ArrayList _nodeInfos; ///<summary>Data affinity of the entire cluster.</summary> private ArrayList _clusterDataAffinity = new ArrayList(); ///<summary>A map that gives the list of all data groups mapped at the node.</summary> private Hashtable _datagroupsAtPartition = new Hashtable(); ///<summary>A map that gives the list of all nodes that have mapping for a group.</summary> private Hashtable _partitionsHavingDatagroup = new Hashtable(); ///<summary>A map that gives the list of all nodes belonging to the same subgroup i.e. partition.</summary> private Hashtable _subgroupNodes = new Hashtable(); /// <summary> /// Constructor. /// </summary> public ClusterCacheStatistics() {} /// <summary> /// Copy constructor. /// </summary> /// <param name="stat"></param> protected ClusterCacheStatistics(ClusterCacheStatistics stat):base(stat) { lock(stat) { this._groupName = stat._groupName; this._channelType = stat._channelType; this._memberCount = stat._memberCount; this._serverCount = stat._serverCount; this._otherCount = stat._otherCount; this._localNode = stat._localNode == null ? null:stat._localNode.Clone() as NodeInfo; if(stat._nodeInfos != null) { this._nodeInfos = new ArrayList(stat._nodeInfos.Count); for(int i=0; i<stat._nodeInfos.Count; i++) { this._nodeInfos.Add(((NodeInfo)stat._nodeInfos[i]).Clone() as NodeInfo); } } if (stat.ClusterDataAffinity != null) this.ClusterDataAffinity = (ArrayList)stat.ClusterDataAffinity.Clone(); if (stat.PartitionsHavingDatagroup != null) this.PartitionsHavingDatagroup = (Hashtable)stat.PartitionsHavingDatagroup.Clone(); if (stat.DatagroupsAtPartition != null) this.DatagroupsAtPartition = (Hashtable)stat.DatagroupsAtPartition.Clone(); if (stat.SubgroupNodes != null) this.SubgroupNodes = (Hashtable)stat.SubgroupNodes.Clone(); } } public override long MaxSize { get { if (LocalNode != null) return LocalNode.Statistics.MaxSize; else return 0; } set { if(this.LocalNode != null) this.LocalNode.Statistics.MaxSize = value; } } /// <summary> /// The name of the group participating in the cluster. /// </summary> public string GroupName { get { return _groupName; } set { _groupName = value; } } /// <summary> /// The clustering scheme. /// </summary> public string ChannelType { get { return _channelType; } set { _channelType = value; } } /// <summary> /// The total number of nodes in the cluster. /// </summary> public int ClusterSize { get { return MemberCount + OtherCount; } } /// <summary> /// The number of nodes in the cluster that are providers or consumers, i.e., group members. /// </summary> public int MemberCount { get { return _memberCount; } set { _memberCount = value; } } /// <summary> /// The number of nodes in the cluster that are storage enabled. /// </summary> public int ServerCount { get { return _serverCount; } set { _serverCount = value; } } /// <summary> /// The number of nodes in the cluster that are unknown, i.e., different cache scheme. /// </summary> public int OtherCount { get { return _otherCount; } set { _otherCount = value; } } /// <summary> /// The statistics of the local node. /// </summary> public NodeInfo LocalNode { get { return _localNode; } set { _localNode = value; } } /// <summary> /// The statistics of the local node. /// </summary> public ArrayList Nodes { get { return _nodeInfos; } set { _nodeInfos = value; } } /// <summary> /// Gets/Sets teh data affinity of the cluster. /// </summary> public ArrayList ClusterDataAffinity { get { return _clusterDataAffinity; } set { _clusterDataAffinity = value; } } public Hashtable DatagroupsAtPartition { get { return _datagroupsAtPartition; } set { _datagroupsAtPartition = value; } } public Hashtable PartitionsHavingDatagroup { get { return _partitionsHavingDatagroup; } set { _partitionsHavingDatagroup = value; } } public Hashtable SubgroupNodes { get { return _subgroupNodes; } set { _subgroupNodes = value; } } #region / --- ICloneable --- / /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public override object Clone() { return new ClusterCacheStatistics(this); } #endregion /// <summary> /// Adds a new node to the node list /// </summary> /// <param name="info"></param> protected internal NodeInfo GetNode(Address address) { lock(this) { if(_nodeInfos != null) for(int i=0 ;i<_nodeInfos.Count; i++) { if(((NodeInfo)_nodeInfos[i]).Address.CompareTo(address) == 0) return _nodeInfos[i] as NodeInfo; } } return null; } internal NodeInfo[] GetNodesClone() { NodeInfo[] nodes = null; lock (this) { if (_nodeInfos != null) { nodes = new NodeInfo[_nodeInfos.Count]; _nodeInfos.CopyTo(nodes); } } return nodes; } /// <summary> /// Sets the values of the server/member/other counts /// </summary> /// <param name="server"></param> /// <param name="member"></param> /// <param name="other"></param> protected internal void SetServerCounts(int servCnt, int memCnt, int otherCnt) { lock(this) { _serverCount = servCnt; _memberCount = memCnt; _otherCount = otherCnt; } } /// <summary> /// returns the string representation of the statistics. /// </summary> /// <returns></returns> public override string ToString() { lock(this) { System.Text.StringBuilder ret = new System.Text.StringBuilder(); ret.Append("Cluster[" + base.ToString() + ", Nm:" + GroupName + ", "); ret.Append("S:" + ServerCount.ToString() + ", "); ret.Append("M:" + MemberCount.ToString() + ", "); ret.Append("O:" + OtherCount.ToString() + ", "); if(_localNode != null) ret.Append("Local" + _localNode.ToString()); foreach(NodeInfo i in _nodeInfos) { ret.Append(", " + i.ToString()); } ret.Append("]"); return ret.ToString(); } } #region / --- ICompactSerializable --- / public override void Deserialize(CompactReader reader) { base.Deserialize(reader); _groupName = reader.ReadObject() as string; _channelType = reader.ReadObject() as string; _memberCount = reader.ReadInt32(); _serverCount = reader.ReadInt32(); _otherCount = reader.ReadInt32(); _localNode = NodeInfo.ReadNodeInfo(reader); _nodeInfos = (ArrayList)reader.ReadObject(); } public override void Serialize(CompactWriter writer) { base.Serialize(writer); writer.WriteObject(_groupName); writer.WriteObject(_channelType); writer.Write(_memberCount); writer.Write(_serverCount); writer.Write(_otherCount); NodeInfo.WriteNodeInfo(writer, _localNode); writer.WriteObject(_nodeInfos); } #endregion } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Reflection; using System.Windows.Forms; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.PythonTools.Profiling { /// <summary> /// Top level node for our UI Hierarchy which includes all of the various performance sessions. /// /// We need one top-level node which we'll add the other nodes to. We treat the other nodes /// as nested hierarchies. /// </summary> class SessionsNode : BaseHierarchyNode, IVsHierarchyDeleteHandler { private readonly List<SessionNode> _sessions = new List<SessionNode>(); internal readonly EventSinkCollection _sessionsCollection = new EventSinkCollection(); private readonly IServiceProvider _serviceProvider; private readonly IVsUIHierarchyWindow _window; internal uint _activeSession = VSConstants.VSITEMID_NIL; internal static ImageList _imageList = InitImageList(); const string _rootName = "Python Performance Sessions"; internal SessionsNode(IServiceProvider serviceProvider, IVsUIHierarchyWindow window) { _serviceProvider = serviceProvider; _window = window; } internal SessionNode AddTarget(ProfilingTarget target, string filename, bool save) { Debug.Assert(filename.EndsWith(".pyperf")); // ensure a unique name string newBaseName = Path.GetFileNameWithoutExtension(filename); string tempBaseName = newBaseName; int append = 0; bool dupFound; do { dupFound = false; for (int i = 0; i < _sessions.Count; i++) { if (Path.GetFileNameWithoutExtension(_sessions[i].Filename) == newBaseName) { dupFound = true; } } if (dupFound) { append++; newBaseName = tempBaseName + append; } } while (dupFound); string newFilename = newBaseName + ".pyperf"; // add directory name back if present... string dirName = Path.GetDirectoryName(filename); if (!string.IsNullOrEmpty(dirName)) { newFilename = Path.Combine(dirName, newFilename); } filename = newFilename; // save to the unique item if desired (we save whenever we have an active solution as we have a place to put it)... if (save) { using (var fs = new FileStream(filename, FileMode.Create)) { ProfilingTarget.Serializer.Serialize(fs, target); } } var node = OpenTarget(target, filename); if (!save) { node.MarkDirty(); node._neverSaved = true; } return node; } internal SessionNode OpenTarget(ProfilingTarget target, string filename) { for (int i = 0; i < _sessions.Count; i++) { if (_sessions[i].Filename == filename) { throw new InvalidOperationException(String.Format("Performance '{0}' session is already open", filename)); } } uint prevSibl; if (_sessions.Count > 0) { prevSibl = _sessions[_sessions.Count - 1].ItemId; } else { prevSibl = VSConstants.VSITEMID_NIL; } var node = new SessionNode(_serviceProvider, this, target, filename); _sessions.Add(node); OnItemAdded(VSConstants.VSITEMID_ROOT, prevSibl, node.ItemId); if (_activeSession == VSConstants.VSITEMID_NIL) { SetActiveSession(node); } return node; } internal void SetActiveSession(SessionNode node) { uint oldItem = _activeSession; if (oldItem != VSConstants.VSITEMID_NIL) { _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_UnBoldItem); } _activeSession = node.ItemId; _window.ExpandItem(this, _activeSession, EXPANDFLAGS.EXPF_BoldItem); } #region IVsUIHierarchy Members public override int GetNestedHierarchy(uint itemid, ref Guid iidHierarchyNested, out IntPtr ppHierarchyNested, out uint pitemidNested) { var item = _sessionsCollection[itemid]; if (item != null) { if (iidHierarchyNested == typeof(IVsHierarchy).GUID || iidHierarchyNested == typeof(IVsUIHierarchy).GUID) { ppHierarchyNested = System.Runtime.InteropServices.Marshal.GetComInterfaceForObject(item, typeof(IVsUIHierarchy)); pitemidNested = VSConstants.VSITEMID_ROOT; return VSConstants.S_OK; } } return base.GetNestedHierarchy(itemid, ref iidHierarchyNested, out ppHierarchyNested, out pitemidNested); } public override int GetProperty(uint itemid, int propid, out object pvar) { // GetProperty is called many many times for this particular property pvar = null; var prop = (__VSHPROPID)propid; switch (prop) { case __VSHPROPID.VSHPROPID_CmdUIGuid: pvar = new Guid(GuidList.guidPythonProfilingPkgString); break; case __VSHPROPID.VSHPROPID_Parent: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = VSConstants.VSITEMID_ROOT; } break; case __VSHPROPID.VSHPROPID_FirstChild: if (itemid == VSConstants.VSITEMID_ROOT && _sessions.Count > 0) pvar = _sessions[0].ItemId; else pvar = VSConstants.VSITEMID_NIL; break; case __VSHPROPID.VSHPROPID_NextSibling: pvar = VSConstants.VSITEMID_NIL; for(int i = 0; i<_sessions.Count; i++) { if (_sessions[i].ItemId == itemid && i < _sessions.Count - 1) { pvar = _sessions[i + 1].ItemId; } } break; case __VSHPROPID.VSHPROPID_Expandable: pvar = true; break; case __VSHPROPID.VSHPROPID_ExpandByDefault: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = true; } break; case __VSHPROPID.VSHPROPID_IconImgList: case __VSHPROPID.VSHPROPID_OpenFolderIconHandle: pvar = (int)_imageList.Handle; break; case __VSHPROPID.VSHPROPID_IconIndex: case __VSHPROPID.VSHPROPID_OpenFolderIconIndex: if (itemid == VSConstants.VSITEMID_ROOT) { pvar = 0; } else { pvar = (int)TreeViewIconIndex.PerformanceSession; } break; case __VSHPROPID.VSHPROPID_SaveName: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Filename; } break; case __VSHPROPID.VSHPROPID_Caption: if (itemid != VSConstants.VSITEMID_ROOT) { pvar = GetItem(itemid).Caption; } break; case __VSHPROPID.VSHPROPID_ParentHierarchy: if (_sessionsCollection[itemid] != null) { pvar = this as IVsHierarchy; } break; } if (pvar != null) return VSConstants.S_OK; return VSConstants.DISP_E_MEMBERNOTFOUND; } #endregion #region IVsHierarchyDeleteHandler Members public int DeleteItem(uint dwDelItemOp, uint itemid) { var item = GetItem(itemid); if (item != null) { switch ((__VSDELETEITEMOPERATION)dwDelItemOp) { case __VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage: File.Delete(item.Filename); goto case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject; case __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject: item.Removed(); _sessions.Remove(item); _sessionsCollection.RemoveAt(itemid); OnItemDeleted(itemid); // our itemids have all changed, invalidate them OnInvalidateItems(VSConstants.VSITEMID_ROOT); break; } if (itemid == _activeSession) { if (_sessions.Count > 0) { SetActiveSession(_sessions[0]); } else { _activeSession = VSConstants.VSITEMID_NIL; } } return VSConstants.S_OK; } return VSConstants.E_FAIL; } public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) { pfCanDelete = 1; return VSConstants.S_OK; } #endregion private static ImageList InitImageList() { var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Microsoft.PythonTools.ProfilingTreeView.bmp"); return Utilities.GetImageList( stream ); } private SessionNode GetItem(uint itemid) { return (SessionNode)_sessionsCollection[itemid]; } internal void StartProfiling() { if (_activeSession != VSConstants.VSITEMID_NIL) { GetItem(_activeSession).StartProfiling(); } } public List<SessionNode> Sessions { get { return _sessions; } } } }
// 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.Runtime.InteropServices { using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Threading; using System.Runtime.Versioning; using System.Diagnostics.Contracts; // These are the types of handles used by the EE. // IMPORTANT: These must match the definitions in ObjectHandle.h in the EE. // IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType // constant must be updated. [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public enum GCHandleType { Weak = 0, WeakTrackResurrection = 1, Normal = 2, Pinned = 3 } // This class allows you to create an opaque, GC handle to any // COM+ object. A GC handle is used when an object reference must be // reachable from unmanaged memory. There are 3 kinds of roots: // Normal - keeps the object from being collected. // Weak - allows object to be collected and handle contents will be zeroed. // Weak references are zeroed before the finalizer runs, so if the // object is resurrected in the finalizer the weak reference is // still zeroed. // WeakTrackResurrection - Same as weak, but stays until after object is // really gone. // Pinned - same as normal, but allows the address of the actual object // to be taken. // [StructLayout(LayoutKind.Sequential)] [System.Runtime.InteropServices.ComVisible(true)] public struct GCHandle { // IMPORTANT: This must be kept in sync with the GCHandleType enum. private const GCHandleType MaxHandleType = GCHandleType.Pinned; #if MDA_SUPPORTED [System.Security.SecuritySafeCritical] // auto-generated static GCHandle() { s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled(); if (s_probeIsActive) s_cookieTable = new GCHandleCookieTable(); } #endif // Allocate a handle storing the object and the type. [System.Security.SecurityCritical] // auto-generated internal GCHandle(Object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) throw new ArgumentOutOfRangeException(nameof(type), Environment.GetResourceString("ArgumentOutOfRange_Enum")); Contract.EndContractBlock(); m_handle = InternalAlloc(value, type); // Record if the handle is pinned. if (type == GCHandleType.Pinned) SetIsPinned(); } // Used in the conversion functions below. [System.Security.SecurityCritical] // auto-generated internal GCHandle(IntPtr handle) { InternalCheckDomain(handle); m_handle = handle; } // Creates a new GC handle for an object. // // value - The object that the GC handle is created for. // type - The type of GC handle to create. // // returns a new GC handle that protects the object. [System.Security.SecurityCritical] // auto-generated_required public static GCHandle Alloc(Object value) { return new GCHandle(value, GCHandleType.Normal); } [System.Security.SecurityCritical] // auto-generated_required public static GCHandle Alloc(Object value, GCHandleType type) { return new GCHandle(value, type); } // Frees a GC handle. [System.Security.SecurityCritical] // auto-generated_required public void Free() { // Copy the handle instance member to a local variable. This is required to prevent // race conditions releasing the handle. IntPtr handle = m_handle; // Free the handle if it hasn't already been freed. if (handle != IntPtr.Zero && Interlocked.CompareExchange(ref m_handle, IntPtr.Zero, handle) == handle) { #if MDA_SUPPORTED // If this handle was passed out to unmanaged code, we need to remove it // from the cookie table. // NOTE: the entry in the cookie table must be released before the // internal handle is freed to prevent a race with reusing GC handles. if (s_probeIsActive) s_cookieTable.RemoveHandleIfPresent(handle); #endif #if BIT64 InternalFree((IntPtr)(((long)handle) & ~1L)); #else // BIT64 (32) InternalFree((IntPtr)(((int)handle) & ~1)); #endif } else { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); } } // Target property - allows getting / updating of the handle's referent. public Object Target { [System.Security.SecurityCritical] // auto-generated_required get { // Check if the handle was never initialized or was freed. if (m_handle == IntPtr.Zero) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); return InternalGet(GetHandleValue()); } [System.Security.SecurityCritical] // auto-generated_required set { // Check if the handle was never initialized or was freed. if (m_handle == IntPtr.Zero) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); InternalSet(GetHandleValue(), value, IsPinned()); } } // Retrieve the address of an object in a Pinned handle. This throws // an exception if the handle is any type other than Pinned. [System.Security.SecurityCritical] // auto-generated_required public IntPtr AddrOfPinnedObject() { // Check if the handle was not a pinned handle. if (!IsPinned()) { // Check if the handle was never initialized for was freed. if (m_handle == IntPtr.Zero) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); // You can only get the address of pinned handles. throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotPinned")); } // Get the address. return InternalAddrOfPinnedObject(GetHandleValue()); } // Determine whether this handle has been allocated or not. public bool IsAllocated { get { return m_handle != IntPtr.Zero; } } // Used to create a GCHandle from an int. This is intended to // be used with the reverse conversion. [System.Security.SecurityCritical] // auto-generated_required public static explicit operator GCHandle(IntPtr value) { return FromIntPtr(value); } [System.Security.SecurityCritical] // auto-generated_required public static GCHandle FromIntPtr(IntPtr value) { if (value == IntPtr.Zero) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_HandleIsNotInitialized")); Contract.EndContractBlock(); IntPtr handle = value; #if MDA_SUPPORTED if (s_probeIsActive) { // Make sure this cookie matches up with a GCHandle we've passed out a cookie for. handle = s_cookieTable.GetHandle(value); if (IntPtr.Zero == handle) { // Fire an MDA if we were unable to retrieve the GCHandle. Mda.FireInvalidGCHandleCookieProbe(value); return new GCHandle(IntPtr.Zero); } } #endif return new GCHandle(handle); } // Used to get the internal integer representation of the handle out. public static explicit operator IntPtr(GCHandle value) { return ToIntPtr(value); } public static IntPtr ToIntPtr(GCHandle value) { #if MDA_SUPPORTED if (s_probeIsActive) { // Remember that we passed this GCHandle out by storing the cookie we returned so we // can later validate. return s_cookieTable.FindOrAddHandle(value.m_handle); } #endif return value.m_handle; } public override int GetHashCode() { return m_handle.GetHashCode(); } public override bool Equals(Object o) { GCHandle hnd; // Check that o is a GCHandle first if(o == null || !(o is GCHandle)) return false; else hnd = (GCHandle) o; return m_handle == hnd.m_handle; } public static bool operator ==(GCHandle a, GCHandle b) { return a.m_handle == b.m_handle; } public static bool operator !=(GCHandle a, GCHandle b) { return a.m_handle != b.m_handle; } internal IntPtr GetHandleValue() { #if BIT64 return new IntPtr(((long)m_handle) & ~1L); #else // !BIT64 (32) return new IntPtr(((int)m_handle) & ~1); #endif } internal bool IsPinned() { #if BIT64 return (((long)m_handle) & 1) != 0; #else // !BIT64 (32) return (((int)m_handle) & 1) != 0; #endif } internal void SetIsPinned() { #if BIT64 m_handle = new IntPtr(((long)m_handle) | 1L); #else // !BIT64 (32) m_handle = new IntPtr(((int)m_handle) | 1); #endif } // Internal native calls that this implementation uses. [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAlloc(Object value, GCHandleType type); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalFree(IntPtr handle); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalGet(IntPtr handle); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalCheckDomain(IntPtr handle); [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern GCHandleType InternalGetHandleType(IntPtr handle); // The actual integer handle value that the EE uses internally. private IntPtr m_handle; #if MDA_SUPPORTED // The GCHandle cookie table. static private volatile GCHandleCookieTable s_cookieTable = null; static private volatile bool s_probeIsActive = false; #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; using Xunit; namespace System.Tests { public static class GCTests { private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms [Fact] public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0 if (s_is32Bits) { Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms } } [Fact] public static void Collect_Int() { for (int i = 0; i < GC.MaxGeneration + 10; i++) { GC.Collect(i); } } [Fact] public static void Collect_Int_NegativeGeneration_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0 } [Theory] [InlineData(GCCollectionMode.Default)] [InlineData(GCCollectionMode.Forced)] public static void Collect_Int_GCCollectionMode(GCCollectionMode mode) { for (int gen = 0; gen <= 2; gen++) { var b = new byte[1024 * 1024 * 10]; int oldCollectionCount = GC.CollectionCount(gen); b = null; GC.Collect(gen, GCCollectionMode.Default); Assert.True(GC.CollectionCount(gen) > oldCollectionCount); } } [Fact] public static void Collect_Int_GCCollectionMode_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default)); // Generation < 0 Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1)); // Invalid collection mode Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1)); // Invalid collection mode } [Fact] public static void Collect_Int_GCCollectionMode_Bool_Invalid() { Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false)); // Generation < 0 Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Default - 1, false)); // Invalid collection mode Assert.Throws<ArgumentOutOfRangeException>("mode", () => GC.Collect(2, GCCollectionMode.Optimized + 1, false)); // Invalid collection mode } [Fact] public static void Collect_CallsFinalizer() { FinalizerTest.Run(); } private class FinalizerTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); // Make sure Finalize() is called GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive() { KeepAliveTest.Run(); } private class KeepAliveTest { public static void Run() { var keepAlive = new KeepAliveObject(); var doNotKeepAlive = new DoNotKeepAliveObject(); doNotKeepAlive = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(DoNotKeepAliveObject.Finalized); Assert.False(KeepAliveObject.Finalized); GC.KeepAlive(keepAlive); } private class KeepAliveObject { public static bool Finalized { get; private set; } ~KeepAliveObject() { Finalized = true; } } private class DoNotKeepAliveObject { public static bool Finalized { get; private set; } ~DoNotKeepAliveObject() { Finalized = true; } } } [Fact] public static void KeepAlive_Null() { KeepAliveNullTest.Run(); } private class KeepAliveNullTest { public static void Run() { var obj = new TestObject(); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.KeepAlive(obj); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive_Recursive() { KeepAliveRecursiveTest.Run(); } private class KeepAliveRecursiveTest { public static void Run() { int recursionCount = 0; RunWorker(new TestObject(), ref recursionCount); } private static void RunWorker(object obj, ref int recursionCount) { if (recursionCount++ == 10) return; GC.Collect(); GC.WaitForPendingFinalizers(); RunWorker(obj, ref recursionCount); Assert.False(TestObject.Finalized); GC.KeepAlive(obj); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer() { SuppressFinalizerTest.Run(); } private class SuppressFinalizerTest { public static void Run() { var obj = new TestObject(); GC.SuppressFinalize(obj); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer_NullObject_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null } [Fact] public static void ReRegisterForFinalize() { ReRegisterForFinalizeTest.Run(); } [Fact] public static void ReRegisterFoFinalize() { Assert.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null } private class ReRegisterForFinalizeTest { public static void Run() { TestObject.Finalized = false; CreateObject(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private static void CreateObject() { using (var obj = new TestObject()) { GC.SuppressFinalize(obj); } } private class TestObject : IDisposable { public static bool Finalized { get; set; } ~TestObject() { Finalized = true; } public void Dispose() { GC.ReRegisterForFinalize(this); } } } [Fact] public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0 } [Fact] public static void RemoveMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0 if (s_is32Bits) { Assert.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms } } [Fact] public static void GetTotalMemoryTest_ForceCollection() { // We don't test GetTotalMemory(false) at all because a collection // could still occur even if not due to the GetTotalMemory call, // and as such there's no way to validate the behavior. We also // don't verify a tighter bound for the result of GetTotalMemory // because collections could cause significant fluctuations. GC.Collect(); int gen0 = GC.CollectionCount(0); int gen1 = GC.CollectionCount(1); int gen2 = GC.CollectionCount(2); Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue); Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue); } [Fact] public static void GetGeneration() { // We don't test a tighter bound on GetGeneration as objects // can actually get demoted or stay in the same generation // across collections. GC.Collect(); var obj = new object(); for (int i = 0; i <= GC.MaxGeneration + 1; i++) { Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration); GC.Collect(); } } [Theory] [InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)] [InlineData(GCLargeObjectHeapCompactionMode.Default)] public static void LargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value) { GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode; try { GCSettings.LargeObjectHeapCompactionMode = value; Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode); } finally { GCSettings.LargeObjectHeapCompactionMode = orig; Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode); } } [Theory] [InlineData(GCLatencyMode.Batch)] [InlineData(GCLatencyMode.Interactive)] public static void LatencyRoundtrips(GCLatencyMode value) { GCLatencyMode orig = GCSettings.LatencyMode; try { GCSettings.LatencyMode = value; Assert.Equal(value, GCSettings.LatencyMode); } finally { GCSettings.LatencyMode = orig; Assert.Equal(orig, GCSettings.LatencyMode); } } [Theory] [PlatformSpecific(PlatformID.Windows)] //Concurent GC is not enabled on Unix. Recombine to TestLatencyRoundTrips once addressed. [InlineData(GCLatencyMode.LowLatency)] [InlineData(GCLatencyMode.SustainedLowLatency)] public static void LatencyRoundtrips_LowLatency(GCLatencyMode value) => LatencyRoundtrips(value); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security.Claims; using System.Text; using System.Threading; using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE; using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON; using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags; using LUID = Interop.LUID; using LSA_STRING = Interop.SspiCli.LSA_STRING; using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS; using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE; using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE; namespace System.Security.Principal { public class WindowsIdentity : ClaimsIdentity, IDisposable { private string _name = null; private SecurityIdentifier _owner = null; private SecurityIdentifier _user = null; private IdentityReferenceCollection _groups = null; private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string _authType = null; private int _isAuthenticated = -1; private volatile TokenImpersonationLevel _impersonationLevel; private volatile bool _impersonationLevelInitialized; public new const string DefaultIssuer = @"AD AUTHORITY"; private string _issuerName = DefaultIssuer; private object _claimsIntiailizedLock = new object(); private volatile bool _claimsInitialized; private List<Claim> _deviceClaims; private List<Claim> _userClaims; // // Constructors. // private WindowsIdentity() : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { } /// <summary> /// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN). /// </summary> /// <remarks> /// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current /// thread privilege to include Tcb. /// </remarks> public WindowsIdentity(string sUserPrincipalName) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { // Desktop compat: See comments below for why we don't validate sUserPrincipalName. using (SafeLsaHandle lsaHandle = ConnectToLsa()) { int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A); // 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api // so we'll use the same name the CLR used even though we're not actually the "CLR." byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 }; TOKEN_SOURCE sourceContext; if (!Interop.SecurityBase.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) throw new SecurityException(new Win32Exception().Message); sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Array.Copy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); // Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) throw new ArgumentNullException("s"); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) { // Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort, // effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.) Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue); } unsafe { // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length); using (SafeLocalAllocHandle authenticationInfo = Interop.mincore_obsolete.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength)))) { if (authenticationInfo.IsInvalid || authenticationInfo == null) throw new OutOfMemoryException(); KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle()); pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon; pKerbS4uLogin->Flags = KerbS4uLogonFlags.None; pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length); IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1); pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset; Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length); pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0; pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero; ushort sourceNameLength = checked((ushort)(sourceName.Length)); using (SafeLocalAllocHandle sourceNameBuffer = Interop.mincore_obsolete.LocalAlloc(0, new UIntPtr(sourceNameLength))) { if (sourceNameBuffer.IsInvalid || sourceNameBuffer == null) throw new OutOfMemoryException(); Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length); LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength); SafeLsaReturnBufferHandle profileBuffer; int profileBufferLength; LUID logonId; SafeAccessTokenHandle accessTokenHandle; QUOTA_LIMITS quota; int subStatus; int ntStatus = Interop.SspiCli.LsaLogonUser( lsaHandle, ref lsaOriginName, SECURITY_LOGON_TYPE.Network, packageId, authenticationInfo.DangerousGetHandle(), authenticationInfoLength, IntPtr.Zero, ref sourceContext, out profileBuffer, out profileBufferLength, out logonId, out accessTokenHandle, out quota, out subStatus); if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0) ntStatus = subStatus; if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); if (profileBuffer != null) profileBuffer.Dispose(); _safeTokenHandle = accessTokenHandle; } } } } } private static SafeLsaHandle ConnectToLsa() { SafeLsaHandle lsaHandle; int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); return lsaHandle; } private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName) { unsafe { int packageId; byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName); fixed (byte* pAsciiPackageName = asciiPackageName) { LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length))); int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); } return packageId; } } public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { } public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { } private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { CreateFromToken(userToken); _authType = authType; _isAuthenticated = isAuthenticated; } private void CreateFromToken(IntPtr userToken) { if (userToken == IntPtr.Zero) throw new ArgumentException(SR.Argument_TokenZero); Contract.EndContractBlock(); // Find out if the specified token is a valid. uint dwLength = (uint)Marshal.SizeOf<uint>(); bool result = Interop.mincore.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType, SafeLocalAllocHandle.InvalidHandle, 0, out dwLength); if (Marshal.GetLastWin32Error() == Interop.mincore.Errors.ERROR_INVALID_HANDLE) throw new ArgumentException(SR.Argument_InvalidImpersonationToken); if (!Interop.mincore.DuplicateHandle(Interop.mincore.GetCurrentProcess(), userToken, Interop.mincore.GetCurrentProcess(), ref _safeTokenHandle, 0, true, Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) throw new SecurityException(new Win32Exception().Message); } // // Factory methods. // public static WindowsIdentity GetCurrent() { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false); } public static WindowsIdentity GetCurrent(bool ifImpersonating) { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating); } public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { return GetCurrentInternal(desiredAccess, false); } // GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate // the request is anonymous. It does not represent a real process or thread token so // it cannot impersonate or do anything useful. Note this identity does not represent the // usual concept of an anonymous token, and the name is simply misleading but we cannot change it now. public static WindowsIdentity GetAnonymous() { return new WindowsIdentity(); } // // Properties. // // this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same. public override sealed string AuthenticationType { get { // If this is an anonymous identity, return an empty string if (_safeTokenHandle.IsInvalid) return String.Empty; if (_authType == null) { Interop.LUID authId = GetLogonAuthId(_safeTokenHandle); if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID) return String.Empty; // no authentication, just return an empty string SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle; try { int status = Interop.mincore.LsaGetLogonSessionData(ref authId, ref pLogonSessionData); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>()); Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0); return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer); } finally { if (!pLogonSessionData.IsInvalid) pLogonSessionData.Dispose(); } } return _authType; } } public TokenImpersonationLevel ImpersonationLevel { get { // In case of a race condition here here, both threads will set m_impersonationLevel to the same value, // which is ok. if (!_impersonationLevelInitialized) { TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; // If this is an anonymous identity if (_safeTokenHandle.IsInvalid) { impersonationLevel = TokenImpersonationLevel.Anonymous; } else { TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType); if (tokenType == TokenType.TokenPrimary) { impersonationLevel = TokenImpersonationLevel.None; // primary token; } else { /// This is an impersonation token, get the impersonation level int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel); impersonationLevel = (TokenImpersonationLevel)level + 1; } } _impersonationLevel = impersonationLevel; _impersonationLevelInitialized = true; } return _impersonationLevel; } } public override bool IsAuthenticated { get { if (_isAuthenticated == -1) { // This approach will not work correctly for domain guests (will return false // instead of true). This is a corner-case that is not very interesting. _isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0; } return _isAuthenticated == 1; } } private bool CheckNtTokenForSid(SecurityIdentifier sid) { Contract.EndContractBlock(); // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; TokenImpersonationLevel til = ImpersonationLevel; bool isMember = false; try { if (til == TokenImpersonationLevel.None) { if (!Interop.mincore.DuplicateTokenEx(_safeTokenHandle, (uint)TokenAccessLevels.Query, IntPtr.Zero, (uint)TokenImpersonationLevel.Identification, (uint)TokenType.TokenImpersonation, ref token)) throw new SecurityException(new Win32Exception().Message); } // CheckTokenMembership will check if the SID is both present and enabled in the access token. if (!Interop.mincore.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token), sid.BinaryForm, ref isMember)) throw new SecurityException(new Win32Exception().Message); } finally { if (token != SafeAccessTokenHandle.InvalidHandle) { token.Dispose(); } } return isMember; } // // IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always // possible to extract this same information from the User SID property and the new // (and more general) methods defined in the SID class (IsWellKnown, etc...). // public virtual bool IsGuest { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest })); } } public virtual bool IsSystem { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }); return (this.User == sid); } } public virtual bool IsAnonymous { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return true; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }); return (this.User == sid); } } public override string Name { get { return GetName(); } } internal String GetName() { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return String.Empty; if (_name == null) { // revert thread impersonation for the duration of the call to get the name. RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate { NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount; _name = ntAccount.ToString(); }); } return _name; } public SecurityIdentifier Owner { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_owner == null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner)) { _owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true); } } return _owner; } } public SecurityIdentifier User { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_user == null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser)) { _user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true); } } return _user; } } public IdentityReferenceCollection Groups { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_groups == null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups)) { uint groupCount = pGroups.Read<uint>(0); Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0); Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(), groupDetails, 0, groupDetails.Length); foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails) { // Ignore disabled, logon ID, and deny-only groups. uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { groups.Add(new SecurityIdentifier(group.Sid, true)); } } } Interlocked.CompareExchange(ref _groups, groups, null); } return _groups; } } public SafeAccessTokenHandle AccessToken { get { return _safeTokenHandle; } } // // Public methods. // public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { if (action == null) throw new ArgumentNullException("action"); RunImpersonatedInternal(safeAccessTokenHandle, action); } public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { if (func == null) throw new ArgumentNullException("func"); T result = default(T); RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; } protected virtual void Dispose(bool disposing) { if (disposing) { if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed) _safeTokenHandle.Dispose(); } _name = null; _owner = null; _user = null; } public void Dispose() { Dispose(true); } // // internal. // private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged); private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action) { bool isImpersonating; int hr; SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr); if (previousToken == null || previousToken.IsInvalid) throw new SecurityException(new Win32Exception(hr).Message); s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null; ExecutionContext currentContext = ExecutionContext.Capture(); // Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone // on the way out. ExecutionContext.Run( currentContext, delegate { if (!Interop.mincore.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); s_currentImpersonatedToken.Value = null; if (!token.IsInvalid && !Interop.mincore.ImpersonateLoggedOnUser(token)) throw new SecurityException(SR.Argument_ImpersonateUser); s_currentImpersonatedToken.Value = token; action(); }, null); } private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args) { if (!args.ThreadContextChanged) return; // we handle explicit Value property changes elsewhere. if (!Interop.mincore.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); if (args.CurrentValue != null && !args.CurrentValue.IsInvalid) { if (!Interop.mincore.ImpersonateLoggedOnUser(args.CurrentValue)) Environment.FailFast(new Win32Exception().Message); } } internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly) { int hr = 0; bool isImpersonating; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { // either we wanted only ThreadToken - return null if (threadOnly && !isImpersonating) return null; // or there was an error throw new SecurityException(new Win32Exception(hr).Message); } WindowsIdentity wi = new WindowsIdentity(); wi._safeTokenHandle.Dispose(); wi._safeTokenHandle = safeTokenHandle; return wi; } // // private. // private static int GetHRForWin32Error(int dwLastError) { if ((dwLastError & 0x80000000) == 0x80000000) return dwLastError; else return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } private static Exception GetExceptionFromNtStatus(int status) { if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED) return new UnauthorizedAccessException(); if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY) return new OutOfMemoryException(); int win32ErrorCode = Interop.mincore.RtlNtStatusToDosError(status); return new SecurityException(new Win32Exception(win32ErrorCode).Message); } private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr) { isImpersonating = true; SafeAccessTokenHandle safeTokenHandle; hr = 0; bool success = Interop.mincore.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle); if (!success) hr = Marshal.GetHRForLastWin32Error(); if (!success && hr == GetHRForWin32Error(Interop.mincore.Errors.ERROR_NO_TOKEN)) { // No impersonation isImpersonating = false; if (!threadOnly) safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr); } return safeTokenHandle; } private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr) { hr = 0; SafeAccessTokenHandle safeTokenHandle; if (!Interop.mincore.OpenProcessToken(Interop.mincore.GetCurrentProcess(), desiredAccess, out safeTokenHandle)) hr = GetHRForWin32Error(Marshal.GetLastWin32Error()); return safeTokenHandle; } /// <summary> /// Get a property from the current token /// </summary> private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct { Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass)) { Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return information.Read<T>(0); } } // // QueryImpersonation used to test if the current thread is impersonated. // This method doesn't return the thread token (WindowsIdentity). // Note GetCurrentInternal can be used to perform the same test, but // QueryImpersonation is optimized for performance // internal static ImpersonationQueryResult QueryImpersonation() { SafeAccessTokenHandle safeTokenHandle = null; bool success = Interop.mincore.OpenThreadToken(TokenAccessLevels.Query, WinSecurityContext.Thread, out safeTokenHandle); if (safeTokenHandle != null) { Debug.Assert(success, "[WindowsIdentity..QueryImpersonation] - success"); safeTokenHandle.Dispose(); return ImpersonationQueryResult.Impersonated; } int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.mincore.Errors.ERROR_ACCESS_DENIED) { // thread is impersonated because the thread was there (and we failed to open it). return ImpersonationQueryResult.Impersonated; } if (lastError == Interop.mincore.Errors.ERROR_NO_TOKEN) { // definitely not impersonating return ImpersonationQueryResult.NotImpersonated; } // Unexpected failure. return ImpersonationQueryResult.Failed; } private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0); return statistics.AuthenticationId; } } private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint)Marshal.SizeOf<uint>(); bool result = Interop.mincore.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Interop.mincore.Errors.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Interop.mincore.Errors.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Interop.mincore_obsolete.LocalAlloc(0, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) throw new OutOfMemoryException(); safeLocalAllocHandle.Initialize(dwLength); result = Interop.mincore.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) throw new SecurityException(new Win32Exception().Message); break; case Interop.mincore.Errors.ERROR_INVALID_HANDLE: throw new ArgumentException(SR.Argument_InvalidImpersonationToken); default: throw new SecurityException(new Win32Exception(dwErrorCode).Message); } return safeLocalAllocHandle; } protected WindowsIdentity(WindowsIdentity identity) : base(identity, null, identity._authType, null, null) { if (identity == null) throw new ArgumentNullException("identity"); Contract.EndContractBlock(); bool mustDecrement = false; try { if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) { identity._safeTokenHandle.DangerousAddRef(ref mustDecrement); if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) CreateFromToken(identity._safeTokenHandle.DangerousGetHandle()); _authType = identity._authType; _isAuthenticated = identity._isAuthenticated; } } finally { if (mustDecrement) identity._safeTokenHandle.DangerousRelease(); } } internal IntPtr GetTokenInternal() { return _safeTokenHandle.DangerousGetHandle(); } internal WindowsIdentity(ClaimsIdentity claimsIdentity, IntPtr userToken) : base(claimsIdentity) { if (userToken != IntPtr.Zero && userToken.ToInt64() > 0) { CreateFromToken(userToken); } } /// <summary> /// Returns a new instance of the base, used when serializing the WindowsIdentity. /// </summary> internal ClaimsIdentity CloneAsBase() { return base.Clone(); } /// <summary> /// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object. /// </summary> public override ClaimsIdentity Clone() { return new WindowsIdentity(this); } /// <summary> /// Gets the 'User Claims' from the NTToken that represents this identity /// </summary> public virtual IEnumerable<Claim> UserClaims { get { InitializeClaims(); return _userClaims.ToArray(); } } /// <summary> /// Gets the 'Device Claims' from the NTToken that represents the device the identity is using /// </summary> public virtual IEnumerable<Claim> DeviceClaims { get { InitializeClaims(); return _deviceClaims.ToArray(); } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>. /// Includes UserClaims and DeviceClaims. /// </summary> public override IEnumerable<Claim> Claims { get { if (!_claimsInitialized) { InitializeClaims(); } foreach (Claim claim in base.Claims) yield return claim; foreach (Claim claim in _userClaims) yield return claim; foreach (Claim claim in _deviceClaims) yield return claim; } } /// <summary> /// Intenal method to initialize the claim collection. /// Lazy init is used so claims are not initialzed until needed /// </summary> private void InitializeClaims() { if (!_claimsInitialized) { lock (_claimsIntiailizedLock) { if (!_claimsInitialized) { _userClaims = new List<Claim>(); _deviceClaims = new List<Claim>(); if (!String.IsNullOrEmpty(Name)) { // // Add the name claim only if the WindowsIdentity.Name is populated // WindowsIdentity.Name will be null when it is the fake anonymous user // with a token value of IntPtr.Zero // _userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this)); } // primary sid AddPrimarySidClaim(_userClaims); // group sids AddGroupSidClaims(_userClaims); _claimsInitialized = true; } } } } /// <summary> /// Creates a collection of SID claims that represent the users groups. /// </summary> private void AddGroupSidClaims(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve the primary group sid safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup); Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle()); SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true); // only add one primary group sid bool foundPrimaryGroupSid = false; // Retrieve all group sids, primary group sid is one of them safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups")); Claim claim; for (int i = 0; i < count; ++i) { Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes); uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>()); } } finally { safeAllocHandle.Dispose(); safeAllocHandlePrimaryGroup.Dispose(); } } /// <summary> /// Creates a Windows SID Claim and adds to collection of claims. /// </summary> private void AddPrimarySidClaim(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser); Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle()); uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true); Claim claim; if (user.Attributes == 0) { claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } } finally { safeAllocHandle.Dispose(); } } } internal enum WinSecurityContext { Thread = 1, // OpenAsSelf = false Process = 2, // OpenAsSelf = true Both = 3 // OpenAsSelf = true, then OpenAsSelf = false } internal enum ImpersonationQueryResult { Impersonated = 0, // current thread is impersonated NotImpersonated = 1, // current thread is not impersonated Failed = 2 // failed to query } internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } internal enum TokenInformationClass : int { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/rpc/staff_msg_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Operations.RPC { public static partial class StaffMsgSvc { static readonly string __ServiceName = "holms.types.operations.rpc.StaffMsgSvc"; static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest> __Marshaller_StaffMsgSvcFetchForCurrentUserRequest = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse> __Marshaller_StaffMsgSvcManyResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator> __Marshaller_MailboxEntryIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse> __Marshaller_StaffMsgSvcGetUnreadCountResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Operations.Messaging.MailboxEntry> __Marshaller_MailboxEntry = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Operations.Messaging.MailboxEntry.Parser.ParseFrom); static readonly grpc::Method<global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest, global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse> __Method_FetchMessageBoxForCurrentUser = new grpc::Method<global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest, global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse>( grpc::MethodType.Unary, __ServiceName, "FetchMessageBoxForCurrentUser", __Marshaller_StaffMsgSvcFetchForCurrentUserRequest, __Marshaller_StaffMsgSvcManyResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator, global::Google.Protobuf.WellKnownTypes.Empty> __Method_DeleteMessage = new grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "DeleteMessage", __Marshaller_MailboxEntryIndicator, __Marshaller_Empty); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse> __Method_GetUnreadCount = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse>( grpc::MethodType.Unary, __ServiceName, "GetUnreadCount", __Marshaller_Empty, __Marshaller_StaffMsgSvcGetUnreadCountResponse); static readonly grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty> __Method_SendMessage = new grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "SendMessage", __Marshaller_MailboxEntry, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty> __Method_UpdateViewedTime = new grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "UpdateViewedTime", __Marshaller_MailboxEntry, __Marshaller_Empty); static readonly grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty> __Method_UpsertDraft = new grpc::Method<global::HOLMS.Types.Operations.Messaging.MailboxEntry, global::Google.Protobuf.WellKnownTypes.Empty>( grpc::MethodType.Unary, __ServiceName, "UpsertDraft", __Marshaller_MailboxEntry, __Marshaller_Empty); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.StaffMsgSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of StaffMsgSvc</summary> public abstract partial class StaffMsgSvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse> FetchMessageBoxForCurrentUser(global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse> GetUnreadCount(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> SendMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> UpdateViewedTime(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::Google.Protobuf.WellKnownTypes.Empty> UpsertDraft(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for StaffMsgSvc</summary> public partial class StaffMsgSvcClient : grpc::ClientBase<StaffMsgSvcClient> { /// <summary>Creates a new client for StaffMsgSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public StaffMsgSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for StaffMsgSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public StaffMsgSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected StaffMsgSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected StaffMsgSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse FetchMessageBoxForCurrentUser(global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return FetchMessageBoxForCurrentUser(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse FetchMessageBoxForCurrentUser(global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_FetchMessageBoxForCurrentUser, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse> FetchMessageBoxForCurrentUserAsync(global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return FetchMessageBoxForCurrentUserAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.StaffMsgSvcManyResponse> FetchMessageBoxForCurrentUserAsync(global::HOLMS.Types.Operations.RPC.StaffMsgSvcFetchForCurrentUserRequest request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_FetchMessageBoxForCurrentUser, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMessage(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty DeleteMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteMessage, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMessageAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteMessageAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> DeleteMessageAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntryIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteMessage, null, options, request); } public virtual global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse GetUnreadCount(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetUnreadCount(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse GetUnreadCount(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetUnreadCount, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse> GetUnreadCountAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetUnreadCountAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Operations.RPC.StaffMsgSvcGetUnreadCountResponse> GetUnreadCountAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetUnreadCount, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SendMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SendMessage(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty SendMessage(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_SendMessage, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SendMessageAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return SendMessageAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> SendMessageAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_SendMessage, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty UpdateViewedTime(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateViewedTime(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty UpdateViewedTime(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateViewedTime, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpdateViewedTimeAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateViewedTimeAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpdateViewedTimeAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateViewedTime, null, options, request); } public virtual global::Google.Protobuf.WellKnownTypes.Empty UpsertDraft(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpsertDraft(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::Google.Protobuf.WellKnownTypes.Empty UpsertDraft(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpsertDraft, null, options, request); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpsertDraftAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpsertDraftAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::Google.Protobuf.WellKnownTypes.Empty> UpsertDraftAsync(global::HOLMS.Types.Operations.Messaging.MailboxEntry request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpsertDraft, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override StaffMsgSvcClient NewInstance(ClientBaseConfiguration configuration) { return new StaffMsgSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(StaffMsgSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_FetchMessageBoxForCurrentUser, serviceImpl.FetchMessageBoxForCurrentUser) .AddMethod(__Method_DeleteMessage, serviceImpl.DeleteMessage) .AddMethod(__Method_GetUnreadCount, serviceImpl.GetUnreadCount) .AddMethod(__Method_SendMessage, serviceImpl.SendMessage) .AddMethod(__Method_UpdateViewedTime, serviceImpl.UpdateViewedTime) .AddMethod(__Method_UpsertDraft, serviceImpl.UpsertDraft).Build(); } } } #endregion
using UnityEngine; using UnityEngine.UI; using System.Collections.Generic; public class CameraControls : MonoBehaviour { RaycastHit2D hit; public GameObject hitObject; public GameObject selected; public GameObject lastSelected; public GameObject selectorParticle; public GameObject CameraNWEdge; public GameObject CameraSEEdge; public GameObject player1Base; public GameObject player2Base; // dynamic UI elements public Text moveText; public Text actionText; public Text healthText; public Text attackText; public Text playerText; public Text oilText; public Text goldText; public Text oreText; public Text lossText; public Text GoalText; public Button endTurn; public Button lossButton; public Button buildButton; public GameObject actionPanel; public GameObject lossPanel; public GameObject BuyPlanetPanel; public GameObject TradingPanel; // red unit prefabs public GameObject FortificationRedPrefab; public GameObject SettlerBotRedPrefab; public GameObject HeavyBotRedPrefab; public GameObject MeleeBotRedPrefab; public GameObject WorkerBotRedPrefab; public GameObject RangedBotRedPrefab; public GameObject BaseRedPrefab; // blue unit prefabs public GameObject FortificationBluePrefab; public GameObject SettlerBotBluePrefab; public GameObject HeavyBotBluePrefab; public GameObject MeleeBotBluePrefab; public GameObject WorkerBotBluePrefab; public GameObject RangedBotBluePrefab; public GameObject BaseBluePrefab; // get level init object (for player lists, unit lists) public GameObject levelInit; // turn bool int turn; // trading values public int oreConversion; public int oilConversion; public int winGoldCount; public int turnCount; // camera move bool bool moveBool; int cameraMin; int cameraMax; float scrollValue; // vector for movement target (always lerps here) public Vector3 moveCoordinates; // mouse location values public float mouseX; public float mouseY; public float mouseZ; // bool to stop camera movement public bool paused; // keep track of current player public int currentPlayer; // When a player buys a unit it is stored here until it is placed. public UnitType UnitToPlace { get; set; } // Use this for initialization void Start () { UnitToPlace = UnitType.None; currentPlayer = 1; moveBool = false; lastSelected = null; paused = false; turn = 1; turnCount = 1; cameraMax = 10; cameraMin = 1; scrollValue = 0F; // display first turn indicator GetComponent<NotificationController> ().ShowNotification ("Turn " + turnCount.ToString ()); } // trade function for resources to gold. 1 for ore, 2 for oil public void TradeforGold (int function) { // get current player PlayerController callingPlayer = GetPlayerController (); // get function, see if trade is possible if (function == 1) { //trade ore if (callingPlayer.oreCount >= oreConversion) { callingPlayer.oreCount -= oreConversion; callingPlayer.goldCount += 1; UIResourceUpdate (); } } else { //trade oil if (callingPlayer.oilCount >= oilConversion) { callingPlayer.oilCount -= oilConversion; callingPlayer.goldCount += 1; UIResourceUpdate (); } } } // sets camera focus on end turn for the given player, the camera flies to this object on their turn start void SetBase (int playerID, GameObject baseObject) { if (playerID == 1) { player1Base = baseObject; } else if (playerID == 2) { player2Base = baseObject; } } // function to grab selector particle (called in init after it is created void SetParams () { // setup camera params selectorParticle = GameObject.FindGameObjectWithTag ("Selector Particle"); CameraNWEdge = GameObject.FindGameObjectWithTag ("Map NW Corner"); CameraSEEdge = GameObject.FindGameObjectWithTag ("Map SE Corner"); } // set camera to other player between turns public void TakeTurn () { // deselect units selected = lastSelected = null; selectorParticle.BroadcastMessage ("FlashTo", CameraSEEdge); UIDeselectPawn (); if (turn == 1) { // do turn bookkeeping levelInit.GetComponent<LevelInit> ().player2.TakeTurn (); turn = 0; GetComponent<NotificationController> ().ShowNotification ("Turn " + turnCount.ToString ()); turnCount++; // move camera to player 2's base MoveTo (player2Base); currentPlayer = 2; playerText.text = "Player 2"; UIResourceUpdate (); } else { // do turn bookkeeping levelInit.GetComponent<LevelInit> ().player1.TakeTurn (); turn = 1; GetComponent<NotificationController> ().ShowNotification ("Turn " + turnCount.ToString ()); // move camera to player 1's base MoveTo (player1Base); currentPlayer = 1; playerText.text = "Player 1"; UIResourceUpdate (); } } // function to end game (given player number loses) public void PlayerLoss (int playerNumber) { // enable loss panel lossPanel.SetActive (true); selectorParticle.BroadcastMessage ("StopParticle"); // check who lost, set text accordingly if (playerNumber == 1) { lossText.text = "Player 2 Wins!"; } else { lossText.text = "Player 1 Wins!"; } } // function to freely move camera to a target public void MoveTo (GameObject target) { moveCoordinates = new Vector3 (target.transform.position.x, target.transform.position.y, -10); moveBool = true; } // function to set up UI when a pawn is clicked; void UIUpdatePawnInfo (GameObject target, int owned) { // set color and correct numbers for moves/actions on UI // check if we have selected something if (target != null) { // check if the unit even has a pawn controller PawnController targetUnit = target.GetComponent<PawnController> (); if (owned == 1) { // if it is movable, display moves and actions if (targetUnit.movable == true) { moveText.color = Color.black; moveText.text = "Moves Remaining:\t" + targetUnit.currentMoves.ToString (); } if (targetUnit.canAct == true) { buildButton.interactable = true; } // in all cases, display actions, health, and attack (even if 0) actionText.color = Color.black; actionText.text = "Actions Remaining:\t" + targetUnit.currentActions.ToString (); healthText.color = Color.black; healthText.text = "Unit Health:\t\t" + targetUnit.health.ToString (); attackText.color = Color.black; attackText.text = "Attack Power:\t" + targetUnit.attackDamage.ToString (); // activate actionPanel color actionPanel.GetComponent<Image> ().color = Color.red; // Check unit type, build button for unit } else { healthText.color = Color.black; healthText.text = "Unit Health:\t\t" + targetUnit.health.ToString (); moveText.color = Color.grey; moveText.text = "Moves Remaining:"; actionText.color = Color.grey; actionText.text = "Actions Remaining:"; attackText.color = Color.grey; attackText.text = "Attack Power:"; actionPanel.GetComponent<Image> ().color = Color.black; } } } // function to remove UI elements when a pawn is clicked void UIDeselectPawn () { // assume no pawn is selected now moveText.color = Color.grey; moveText.text = "Moves Remaining:"; actionText.color = Color.grey; actionText.text = "Actions Remaining:"; healthText.color = Color.grey; healthText.text = "Unit Health:"; attackText.color = Color.grey; attackText.text = "Attack Power:"; // activate actionPanel color actionPanel.GetComponent<Image> ().color = Color.grey; if (lastSelected != null) { if (lastSelected.GetComponent<PawnController> ().canAct != true) { buildButton.interactable = false; } } } // function to update resource UI public void UIResourceUpdate () { // update all UI text as above on resource panel PlayerController player = GetPlayerController (); if (player.goldCount >= winGoldCount) { BuyPlanetPanel.SetActive (true); GoalText.text = "0 Gold to Win"; } else { GoalText.text = (winGoldCount - player.goldCount).ToString () + " Gold to Win"; } oilText.text = "Oil:\t" + player.oilCount.ToString (); goldText.text = "Gold:\t" + player.goldCount.ToString (); oreText.text = "Ore:\t" + player.oreCount.ToString (); } // mine a tile (claim territory) public void MineTile () { // make sure we have *something* selected if (lastSelected != null) { PawnController worker = lastSelected.GetComponent<PawnController> (); GroundScript mineTile = worker.currentTile.GetComponent<GroundScript> (); // check if this is a mineable tile if (mineTile.isResource == true) { // check if worker has actions left if (worker.currentActions > 0) { // subtract action, change sprite worker.currentActions -= 1; mineTile.ClaimTerritory (currentPlayer); mineTile.isClaimed = currentPlayer; // add territory to total for player GetPlayerController ().AddTerritory (mineTile); } } } } // function to choose the unit to spawn based off of unittype public void SpawnSelection (UnitType unit) { UnitToPlace = unit; GameObject chosenPrefab = null; bool resetBase = false; PlayerController player = GetPlayerController (); // check which player (determines color prefab set) if (currentPlayer == 1) { switch (UnitToPlace) { case UnitType.Base: chosenPrefab = BaseRedPrefab; resetBase = true; break; case UnitType.Fortification: chosenPrefab = FortificationRedPrefab; break; case UnitType.SettlerBot: chosenPrefab = SettlerBotRedPrefab; break; case UnitType.WorkerBot: chosenPrefab = WorkerBotRedPrefab; break; case UnitType.MeleeBot: chosenPrefab = MeleeBotRedPrefab; break; case UnitType.HeavyBot: chosenPrefab = HeavyBotRedPrefab; break; } } // player 2 (blue) else { switch (UnitToPlace) { case UnitType.Base: chosenPrefab = BaseBluePrefab; resetBase = true; break; case UnitType.Fortification: chosenPrefab = FortificationBluePrefab; break; case UnitType.SettlerBot: chosenPrefab = SettlerBotBluePrefab; break; case UnitType.WorkerBot: chosenPrefab = WorkerBotBluePrefab; break; case UnitType.MeleeBot: chosenPrefab = MeleeBotBluePrefab; break; case UnitType.HeavyBot: chosenPrefab = HeavyBotBluePrefab; break; default: throw new UnityException ("Built a unit with an unsupported UnitType"); //break; } } if ((player.BuyUnit (chosenPrefab)) == 0) { if ((chosenPrefab = (GameObject)(SpawnPawn (chosenPrefab, lastSelected.GetComponent<PawnController> ().currentTile, currentPlayer, UnitToPlace))) == null) { // show UI panel saying no valid spawn location around building unit } else { if (resetBase) { if (currentPlayer == 1) { player1Base = chosenPrefab; } else { player2Base = chosenPrefab; } } } } else { // show UI panel saying the player can't afford it GetComponent<NotificationController> ().ShowNotification ("You can not afford to buy this."); } // The unit has been placed. UnitToPlace = UnitType.None; UIResourceUpdate (); } // spawn an arbitrary pawn at spawnTileLocation. Spawns beside tile location (or not at all) public GameObject SpawnPawn (GameObject spawnPrefab, GameObject spawnTileLocation, int owningPlayer, UnitType unitType) { // check if this tile exists if (spawnTileLocation != null) { GroundScript spawnTile = spawnTileLocation.GetComponent<GroundScript> (); // check if this tile location is occupied (maybe a building) if (spawnTile.occupied != true) { return Spawn (spawnPrefab, spawnTileLocation, owningPlayer, unitType); } // if the left block of the spawn tile isn't null, spawn there else if (spawnTile.left_block != null) { // if it is not occupied, spawn if (spawnTile.left_block.GetComponent<GroundScript> ().occupied != true) { return Spawn (spawnPrefab, spawnTile.left_block, owningPlayer, unitType); } } // if the upper block of the spawn tile isn't null, spawn there else if (spawnTile.up_block != null) { // if it is not occupied, spawn if (spawnTile.up_block.GetComponent<GroundScript> ().occupied != true) { return Spawn (spawnPrefab, spawnTile.up_block, owningPlayer, unitType); } } // if the right block of the spawn tile isn't null, spawn there else if (spawnTile.right_block != null) { // if it is not occupied, spawn if (spawnTile.right_block.GetComponent<GroundScript> ().occupied != true) { return Spawn (spawnPrefab, spawnTile.right_block, owningPlayer, unitType); } } // if the lower block of the spawn tile isn't null, spawn there else if (spawnTile.down_block != null) { // if it is not occupied, spawn if (spawnTile.down_block.GetComponent<GroundScript> ().occupied != true) { return Spawn (spawnPrefab, spawnTile.right_block, owningPlayer, unitType); } } } // no valid spot to spawn GetComponent<NotificationController> ().ShowNotification ("No Open square around unit to build into!"); return null; } // private spawn method to handle bookkeeping GameObject Spawn (GameObject spawnPrefab, GameObject spawnTileLocation, int owningPlayer, UnitType unitType) { // instantiate the pawn, set it's tile, set it's owner, set the tile's occupancy spawnPrefab = (GameObject)Instantiate (spawnPrefab, spawnTileLocation.transform.position, spawnTileLocation.transform.rotation); spawnPrefab.BroadcastMessage ("SetTile", spawnTileLocation); spawnPrefab.BroadcastMessage ("SetOwner", owningPlayer); spawnPrefab.BroadcastMessage ("SetCamera", transform.gameObject); spawnPrefab.GetComponent<PawnController> ().currentTile.GetComponent<GroundScript> ().SetOccupant (spawnPrefab); // add settler to the owning player's unit list, set unit's unitID if (owningPlayer == 1) { spawnPrefab.GetComponent<PawnController> ().unitID = levelInit.GetComponent<LevelInit> ().player1.AddUnit (spawnPrefab); } else { spawnPrefab.GetComponent<PawnController> ().unitID = levelInit.GetComponent<LevelInit> ().player2.AddUnit (spawnPrefab); } spawnPrefab.GetComponent<PawnController> ().SetUnitType (unitType); return spawnPrefab; } // Update is called once per frame; here we handle selection, deselection, movement void Update () { mouseX = Input.mousePosition.x; mouseY = Input.mousePosition.y; mouseZ = Input.mousePosition.z; // if we left click in the camera, select the pawn (if selectable) if (Input.GetMouseButtonDown (0)) { // cast a ray to see what was clicked hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero); if (hit.collider != null) { if ((hit.transform.gameObject.tag == "Selectable") || (hit.transform.gameObject.tag == "Selectable and Movable")) { // make sure the current player owns this pawn if (hit.transform.gameObject.GetComponent<PawnController> ().owningPlayer == currentPlayer) { // update selection selected = hit.transform.gameObject; selectorParticle.GetComponent<ParticleBase> ().selectedPawn = selected; // move selection particle selectorParticle.BroadcastMessage ("FlashTo", selected); selectorParticle.BroadcastMessage ("StartParticle"); // update UI (flush it really quick in case we are going from one pawn to another UIDeselectPawn (); UIUpdatePawnInfo (selected, 1); } // if it is an enemy player, show health else { UIUpdatePawnInfo (hit.transform.gameObject, 0); } } // deselection code else { // Save the last pawn selected so when the player clicks the build button we know which panels to show. if (selected != null) { lastSelected = selected; } // deselect pawn, move selection particle off screen selected = null; selectorParticle.BroadcastMessage ("FlashTo", CameraSEEdge); // update UI UIDeselectPawn (); } } } // if we right click in the camera, move the selected pawn to that grid space (or try to) else if (Input.GetMouseButtonDown (1)) { // cast a ray to see what was clicked hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero); // check if we hit a valid panel if (hit.collider != null) { // check if there is actually something selected if (selected != null) { // check if we are moving to an invalid block if ((hit.transform.gameObject.tag != ("MovementBlocker"))) { // If there is no pawn to place if (UnitToPlace == UnitType.None) { // move the pawn using that pawn's code // determine direction with distance from selection float xDist = hit.transform.position.x - selected.transform.position.x; float yDist = hit.transform.position.y - selected.transform.position.y; if (Mathf.Abs (xDist) >= Mathf.Abs (yDist)) { if (xDist > 0) { if (selected.GetComponent<PawnController> ().MoveTo (4) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } } else { if (selected.GetComponent<PawnController> ().MoveTo (3) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } } } else { if (yDist > 0) { if (selected.GetComponent<PawnController> ().MoveTo (1) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } } else { if (selected.GetComponent<PawnController> ().MoveTo (2) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } } } } // update UI UIUpdatePawnInfo (selected, 1); } } } hitObject = hit.transform.gameObject; } // if we hit up key else if (Input.GetKeyDown ("up")) { // if we hit keys while something is selected... if (selected != null) { if (selected.GetComponent<PawnController> ().MoveTo (1) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } // update UI UIUpdatePawnInfo (selected, 1); } } // if we hit down key else if (Input.GetKeyDown ("down")) { // if we hit keys while something is selected... if (selected != null) { if (selected.GetComponent<PawnController> ().MoveTo (2) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } // update UI UIUpdatePawnInfo (selected, 1); } } // if we hit left key else if (Input.GetKeyDown ("left")) { // if we hit keys while something is selected... if (selected != null) { if (selected.GetComponent<PawnController> ().MoveTo (3) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } // update UI UIUpdatePawnInfo (selected, 1); } } // if we hit right key else if (Input.GetKeyDown ("right")) { // if we hit keys while something is selected... if (selected != null) { if (selected.GetComponent<PawnController> ().MoveTo (4) == 0) { moveCoordinates = new Vector3 (selected.GetComponent<PawnController> ().moveCoordinates.x, selected.GetComponent<PawnController> ().moveCoordinates.y, -10); moveBool = true; } // update UI UIUpdatePawnInfo (selected, 1); } } // camera movement if ((mouseX < 7) && (transform.position.x > CameraNWEdge.transform.position.x + 12) && (!paused)) { // move camera left transform.position = new Vector3 (transform.position.x - 0.1f, transform.position.y, transform.position.z); } else if ((mouseX > Screen.width - 7) && (transform.position.x < CameraSEEdge.transform.position.x - 13) && (!paused)) { // move camera right transform.position = new Vector3 (transform.position.x + 0.1f, transform.position.y, transform.position.z); } if ((mouseY < 5) && (transform.position.y > CameraSEEdge.transform.position.y + 6) && (!paused)) { // move camera down transform.position = new Vector3 (transform.position.x, transform.position.y - 0.1f, transform.position.z); } else if ((mouseY > Screen.height - 7) && (transform.position.y < CameraNWEdge.transform.position.y - 7) && (!paused)) { // move camera up transform.position = new Vector3 (transform.position.x, transform.position.y + 0.1f, transform.position.z); } // code to move camera to a location (at turn end) if (moveBool == true) { // check if we moved Vector3 oldPosition = transform.position; transform.position = Vector3.Lerp (transform.position, moveCoordinates, 10 * Time.deltaTime); if (oldPosition == transform.position) { moveBool = false; } } // depth scrolling if ((scrollValue = Input.GetAxis ("Mouse ScrollWheel")) != 0) { // forward if (scrollValue > 0) { Camera.main.orthographicSize--; } else { Camera.main.orthographicSize++; } Camera.main.orthographicSize = Mathf.Clamp (Camera.main.orthographicSize, cameraMin, cameraMax); } // handle space button if (Input.GetKeyDown ("space")) { TakeTurn (); } UIResourceUpdate (); } public PlayerController GetPlayerController () { PlayerController player; if (currentPlayer == 1) { player = levelInit.GetComponent<LevelInit> ().player1; } else { player = levelInit.GetComponent<LevelInit> ().player2; } return player; } }
// 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.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Api; using OpenLiveWriter.ApplicationFramework.Skinning; using OpenLiveWriter.BlogClient; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.Controls; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor; namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl { internal class CategoryDropDownControlM1 : ComboBox, IBlogPostEditor, IBlogCategorySettings, INewCategoryContext { #region IBlogPostEditor Members void IBlogPostEditor.Initialize(IBlogPostEditingContext editingContext, IBlogClientOptions clientOptions) { // categories from blog CategoryContext.SetBlogCategories(_targetBlog.Categories); // pickup new categories from the blog-post CategoryContext.SetNewCategories(editingContext.BlogPost.NewCategories); // combine all post categories before settting ArrayList selectedCategories = new ArrayList(); selectedCategories.AddRange(editingContext.BlogPost.NewCategories); selectedCategories.AddRange(editingContext.BlogPost.Categories); _lastSelectedCategories = new BlogPostCategory[0]; CategoryContext.SelectedCategories = selectedCategories.ToArray(typeof(BlogPostCategory)) as BlogPostCategory[]; toolTipCategories.SetToolTip(this, CategoryContext.FormattedCategoryList); _isDirty = false; } void IBlogPostEditor.SaveChanges(BlogPost post, BlogPostSaveOptions options) { post.Categories = CategoryContext.SelectedExistingCategories; post.NewCategories = CategoryContext.SelectedNewCategories; _isDirty = false; } private ToolTip2 toolTipCategories; bool IBlogPostEditor.ValidatePublish() { // see if we need to halt publishing to specify a category if (Visible) { if (PostEditorSettings.CategoryReminder && (CategoryContext.Categories.Length > 0) && (CategoryContext.SelectedCategories.Length == 0)) { if (DisplayMessage.Show(MessageId.CategoryReminder, FindForm()) == DialogResult.No) { Focus(); return false; } } } // proceed return true; } void IBlogPostEditor.OnPublishSucceeded(BlogPost blogPost, PostResult postResult) { _isDirty = false; } void INewCategoryContext.NewCategoryAdded(BlogPostCategory category) { _categoryContext.CommitNewCategory(category); _isDirty = false; } bool IBlogPostEditor.IsDirty { get { return _isDirty; } } private bool _isDirty = false; void IBlogPostEditor.OnBlogChanged(Blog newBlog) { // save dirty state bool isDirty = _isDirty; _targetBlog = newBlog; AdaptToBlogOptions(); // a new blog always wipes out "New" categories CategoryContext.SetNewCategories(new BlogPostCategory[0]); _lastSelectedCategories = new BlogPostCategory[0]; CategoryContext.SelectedCategories = new BlogPostCategory[0]; // restore dirty state _isDirty = isDirty; } private Blog _targetBlog; void IBlogPostEditor.OnBlogSettingsChanged(bool templateChanged) { AdaptToBlogOptions(); } private void AdaptToBlogOptions() { if (_targetBlog.ClientOptions.SupportsMultipleCategories) CategoryContext.SelectionMode = CategoryContext.SelectionModes.MultiSelect; else CategoryContext.SelectionMode = CategoryContext.SelectionModes.SingleSelect; CategoryContext.SupportsAddingCategories = _targetBlog.ClientOptions.SupportsNewCategories; CategoryContext.SupportsHierarchicalCategories = _targetBlog.ClientOptions.SupportsHierarchicalCategories; CategoryContext.MaxCategoryNameLength = _targetBlog.ClientOptions.MaxCategoryNameLength; // categories from blog CategoryContext.SetBlogCategories(_targetBlog.Categories); } public void OnClosing(CancelEventArgs e) { } public void OnPostClosing(CancelEventArgs e) { } #endregion public CategoryDropDownControlM1() : base() { if (DesignMode) _categoryContext = new CategoryContext(); // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // prevent editing and showing of drop down DropDownStyle = ComboBoxStyle.DropDownList; // fully cusotm painting IntegralHeight = false; DrawMode = DrawMode.OwnerDrawFixed; Items.Add(String.Empty); } public void Initialize(IWin32Window parentFrame, CategoryContext categoryContext) { _categoryContext = categoryContext ?? new CategoryContext(); _parentFrame = parentFrame; _categoryContext.BlogCategorySettings = this; _categoryContext.Changed += new CategoryContext.CategoryChangedEventHandler(_categoryContext_Changed); } // replace standard drop down behavior with category form protected override void WndProc(ref Message m) { if (IsDropDownMessage(m)) { if (_categoryDisplayForm == null) DisplayCategoryForm(); else Focus(); } else { base.WndProc(ref m); } } // replace standard painting behavior protected override void OnDrawItem(DrawItemEventArgs evt) { BidiGraphics g = new BidiGraphics(evt.Graphics, ClientRectangle); // determine the text color based on whether we have categories bool hasCategories = _categoryContext.SelectedCategories.Length > 0; Color textColor = hasCategories ? SystemColors.ControlText : SystemColors.GrayText; //Color.FromArgb(200, SystemColors.ControlText) ; // margins const int HORIZONTAL_MARGIN = 1; // draw the icon (if we have one) const int ICON_MARGIN = 4; int textMargin = 0; if (_icon != null) { g.DrawImage(true, _icon, new Rectangle(ScaleX(ICON_MARGIN), ScaleY(2), ScaleX(_icon.Width), ScaleY(_icon.Height))); textMargin += ScaleX(ICON_MARGIN + _icon.Width); } // draw the text int leftMargin = textMargin; int rightMargin = ScaleX(HORIZONTAL_MARGIN); Rectangle textRegion = new Rectangle(new Point(leftMargin, -1), new Size(Width - leftMargin - rightMargin, Height)); TextFormatFlags tempFormat = DisplayFormat; Rectangle tempRectangle = textRegion; g.DrawText( _categoryContext.Text, Font, tempRectangle, textColor, tempFormat); // draw focus rectangle (only if necessary) evt.DrawFocusRectangle(); } BlogPostCategory[] IBlogCategorySettings.RefreshCategories(bool ignoreErrors) { try { _targetBlog.RefreshCategories(); } catch (BlogClientOperationCancelledException) { // show no UI for operation cancelled Debug.WriteLine("BlogClient operation cancelled"); } catch (Exception ex) { if (!ignoreErrors) DisplayableExceptionDisplayForm.Show(_parentFrame, ex); } return _targetBlog.Categories; } void IBlogCategorySettings.UpdateCategories(BlogPostCategory[] categories) { using (BlogSettings blogSettings = BlogSettings.ForBlogId(_targetBlog.Id)) blogSettings.Categories = categories; } private CategoryContext CategoryContext { get { return _categoryContext; } } public void DisplayCategoryForm() { Focus(); /* _categoryDisplayForm = new CategoryDisplayFormM1(this, _categoryContext) ; _categoryDisplayForm.MinDropDownWidth = 0; IMiniFormOwner miniFormOwner = FindForm() as IMiniFormOwner; if (miniFormOwner != null) _categoryDisplayForm.FloatAboveOwner(miniFormOwner); _categoryDisplayForm.Closed += new EventHandler(_categoryDisplayForm_Closed); using ( new WaitCursor() ) _categoryDisplayForm.Show(); */ Point anchor = PointToScreen(new Point(RightToLeft == RightToLeft.Yes ? 0 : ClientSize.Width, ClientSize.Height)); _categoryDisplayForm = new CategoryDisplayFormW3M1(_categoryContext, anchor); _categoryDisplayForm.SelfDispose = true; IMiniFormOwner miniFormOwner = FindForm() as IMiniFormOwner; if (miniFormOwner != null) _categoryDisplayForm.FloatAboveOwner(miniFormOwner); _categoryDisplayForm.Closed += _categoryDisplayForm_Closed; using (new WaitCursor()) _categoryDisplayForm.Show(); } private CategoryDisplayFormW3M1 _categoryDisplayForm = null; private void _categoryContext_Changed(object sender, CategoryContext.CategoryChangedEventArgs e) { if (!CategoryListsAreEqual(_lastSelectedCategories, CategoryContext.SelectedCategories)) _isDirty = true; // always record last selected categories _lastSelectedCategories = CategoryContext.SelectedCategories; toolTipCategories.SetToolTip(this, CategoryContext.FormattedCategoryList); Invalidate(); Update(); } private BlogPostCategory[] _lastSelectedCategories = new BlogPostCategory[0]; private bool CategoryListsAreEqual(BlogPostCategory[] categories1, BlogPostCategory[] categories2) { if (categories1.Length == categories2.Length) { for (int i = 0; i < categories1.Length; i++) { if (!categories1[i].Equals(categories2[i])) return false; } // if we got this far they are equal return true; } else { return false; } } private void _categoryDisplayForm_Closed(object sender, EventArgs e) { _categoryDisplayForm = null; Invalidate(); } private TextFormatFlags DisplayFormat { get { return TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter | TextFormatFlags.NoPrefix; } } private bool IsDropDownMessage(Message m) { // Left Mouse Button while form is not displaying if (m.Msg == WM.LBUTTONDOWN || m.Msg == WM.LBUTTONDBLCLK) { return true; } // F4 else if (m.Msg == WM.KEYDOWN) { Keys keyCombo = (Keys)(int)m.WParam & Keys.KeyCode; if (keyCombo == Keys.F4) return true; else return false; } // Alt+Arrow else if (m.Msg == WM.SYSKEYDOWN) { int wparam = m.WParam.ToInt32(); int lparam = m.LParam.ToInt32(); if ((wparam == 0x28 && (lparam == 0x21500001 || lparam == 0x20500001)) || //Alt+Down, Alt+NumDown (wparam == 0x26 && (lparam == 0x21480001 || lparam == 0x20480001))) //Alt+Up, Alt+NumUp { return true; } else { return false; } } // Not a drop-down message else { return false; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (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.toolTipCategories = new ToolTip2(this.components); // // CategoryDropDownControlM1 // this.Size = new System.Drawing.Size(138, 48); } #endregion #region High DPI Scaling protected override void ScaleControl(SizeF factor, BoundsSpecified specified) { SaveScaleState(factor.Width, factor.Height); base.ScaleControl(factor, specified); } protected override void ScaleCore(float dx, float dy) { SaveScaleState(dx, dy); base.ScaleCore(dx, dy); } private void SaveScaleState(float dx, float dy) { scale = new PointF(scale.X * dx, scale.Y * dy); } private PointF scale = new PointF(1f, 1f); protected int ScaleX(int x) { return (int)(x * scale.X); } protected int ScaleY(int y) { return (int)(y * scale.Y); } #endregion private IWin32Window _parentFrame; private System.ComponentModel.IContainer components; private CategoryContext _categoryContext; private Bitmap _icon = null; public void OnClosed() { } public void OnPostClosed() { } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.PythonTools.TestAdapter; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.Python; namespace TestAdapterTests { [TestClass] public class TestExecutorTests { [ClassInitialize] public static void DoDeployment(TestContext context) { AssertListener.Initialize(); PythonTestData.Deploy(); } [TestMethod, Priority(1)] public void FromCommandLineArgsRaceCondition() { // https://pytools.codeplex.com/workitem/1429 var mre = new ManualResetEvent(false); var tasks = new Task<bool>[100]; try { for (int i = 0; i < tasks.Length; i += 1) { tasks[i] = Task.Run(() => { mre.WaitOne(); using (var arg = VisualStudioApp.FromProcessId(123)) { return arg is VisualStudioApp; } }); } mre.Set(); Assert.IsTrue(Task.WaitAll(tasks, TimeSpan.FromSeconds(30.0))); Assert.IsTrue(tasks.All(t => t.Result)); } finally { mre.Dispose(); Task.WaitAll(tasks, TimeSpan.FromSeconds(30.0)); } } [TestMethod, Priority(1)] [TestCategory("10s")] public void TestRun() { PythonPaths.Python27_x64.AssertInstalled(); PythonPaths.Python33_x64.AssertInstalled(); var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterATests.Concat(TestInfo.TestAdapterBTests).ToArray(); var testCases = expectedTests.Select(tr => tr.TestCase); executor.RunTests(testCases, runContext, recorder); PrintTestResults(recorder.Results); foreach (var expectedResult in expectedTests) { var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.TestCase.FullyQualifiedName); Assert.IsNotNull(actualResult); Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.TestCase.FullyQualifiedName + " had incorrect result"); } } [TestMethod, Priority(1)] [TestCategory("10s")] public void TestRunAll() { PythonPaths.Python27_x64.AssertInstalled(); PythonPaths.Python33_x64.AssertInstalled(); var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterATests.Concat(TestInfo.TestAdapterBTests).ToArray(); executor.RunTests(new[] { TestInfo.TestAdapterLibProjectFilePath, TestInfo.TestAdapterAProjectFilePath, TestInfo.TestAdapterBProjectFilePath }, runContext, recorder); PrintTestResults(recorder.Results); foreach (var expectedResult in expectedTests) { var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.TestCase.FullyQualifiedName); Assert.IsNotNull(actualResult, expectedResult.TestCase.FullyQualifiedName + " not found in results"); Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.TestCase.FullyQualifiedName + " had incorrect result"); } } [TestMethod, Priority(1)] public void TestCancel() { PythonPaths.Python27_x64.AssertInstalled(); PythonPaths.Python33_x64.AssertInstalled(); var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterATests.Union(TestInfo.TestAdapterBTests).ToArray(); var testCases = expectedTests.Select(tr => tr.TestCase); var thread = new System.Threading.Thread(o => { executor.RunTests(testCases, runContext, recorder); }); thread.Start(); // One of the tests being run is hard coded to take 10 secs Assert.IsTrue(thread.IsAlive); System.Threading.Thread.Sleep(100); executor.Cancel(); System.Threading.Thread.Sleep(100); // It should take less than 10 secs to cancel // Depending on which assemblies are loaded, it may take some time // to obtain the interpreters service. Assert.IsTrue(thread.Join(10000)); System.Threading.Thread.Sleep(100); Assert.IsFalse(thread.IsAlive); // Canceled test cases do not get recorded Assert.IsTrue(recorder.Results.Count < expectedTests.Length); } [TestMethod, Priority(1)] [TestCategory("10s")] public void TestMultiprocessing() { var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = TestInfo.TestAdapterMultiprocessingTests; var testCases = expectedTests.Select(tr => tr.TestCase); executor.RunTests(new[] { TestInfo.TestAdapterMultiprocessingProjectFilePath }, runContext, recorder); PrintTestResults(recorder.Results); foreach (var expectedResult in expectedTests) { var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.TestCase.FullyQualifiedName); Assert.IsNotNull(actualResult, expectedResult.TestCase.FullyQualifiedName + " not found in results"); Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.TestCase.FullyQualifiedName + " had incorrect result"); } } [TestMethod, Priority(1)] [TestCategory("10s")] public void TestEnvironment() { var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = new[] { TestInfo.EnvironmentTestSuccess }; var testCases = expectedTests.Select(tr => tr.TestCase); executor.RunTests(new[] { TestInfo.TestAdapterEnvironmentProject }, runContext, recorder); PrintTestResults(recorder.Results); foreach (var expectedResult in expectedTests) { var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.TestCase.FullyQualifiedName); Assert.IsNotNull(actualResult, expectedResult.TestCase.FullyQualifiedName + " not found in results"); Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.TestCase.FullyQualifiedName + " had incorrect result"); } } [TestMethod, Priority(1)] [TestCategory("10s")] public void TestExtensionReference() { PythonPaths.Python27.AssertInstalled(); var executor = new TestExecutor(); var recorder = new MockTestExecutionRecorder(); var runContext = new MockRunContext(); var expectedTests = new[] { TestInfo.ExtensionReferenceTestSuccess }; var testCases = expectedTests.Select(tr => tr.TestCase); executor.RunTests(new[] { TestInfo.TestAdapterExtensionReferenceProject }, runContext, recorder); PrintTestResults(recorder.Results); foreach (var expectedResult in expectedTests) { var actualResult = recorder.Results.SingleOrDefault(tr => tr.TestCase.FullyQualifiedName == expectedResult.TestCase.FullyQualifiedName); Assert.IsNotNull(actualResult, expectedResult.TestCase.FullyQualifiedName + " not found in results"); Assert.AreEqual(expectedResult.Outcome, actualResult.Outcome, expectedResult.TestCase.FullyQualifiedName + " had incorrect result"); } } private static void PrintTestResults(IEnumerable<TestResult> results) { foreach (var result in results) { Console.WriteLine("Test: " + result.TestCase.FullyQualifiedName); Console.WriteLine("Result: " + result.Outcome); foreach(var msg in result.Messages) { Console.WriteLine("Message " + msg.Category + ":"); Console.WriteLine(msg.Text); } Console.WriteLine(""); } } } }
namespace Kaiju.Domain.Models { using System; using System.Collections.Generic; using Kaiju.Domain.Enums; public class Sprint { private readonly int id; private readonly string name; private readonly DateTime start; private readonly DateTime? end; private readonly int allIssuesEstimateSum; private readonly int completedIssuesEstimateSum; private readonly int incompletedIssuesEstimateSum; private readonly int puntedIssuesEstimateSum; private List<Issue> completedIssues; private List<Issue> incompletedIssues; private readonly SprintState state; private Sprint( int id, string name, SprintState state, DateTime start, DateTime? end, int allIssuesEstimateSum, int completedIssuesEstimateSum, int incompletedIssuesEstimateSum, int puntedIssuesEstimateSum) { this.id = id; this.name = name; this.state = state; this.start = start; this.end = end; this.allIssuesEstimateSum = allIssuesEstimateSum; this.completedIssuesEstimateSum = completedIssuesEstimateSum; this.incompletedIssuesEstimateSum = incompletedIssuesEstimateSum; this.puntedIssuesEstimateSum = puntedIssuesEstimateSum; this.completedIssues = new List<Issue>(); this.incompletedIssues = new List<Issue>(); } public DateTime Start { get { return this.start; } } public DateTime? End { get { return this.end; } } public IEnumerable<Issue> CompletedIssues { get { return this.completedIssues ?? (this.completedIssues = new List<Issue>()); } } public IEnumerable<Issue> IncompletedIssues { get { return this.incompletedIssues ?? (this.incompletedIssues = new List<Issue>()); } } public int AllIssuesEstimateSum { get { return this.allIssuesEstimateSum; } } public int CompletedIssuesEstimateSum { get { return this.completedIssuesEstimateSum; } } public int IncompletedIssuesEstimateSum { get { return this.incompletedIssuesEstimateSum; } } public int PuntedIssuesEstimateSum { get { return this.puntedIssuesEstimateSum; } } public int Velocity { get { return this.CompletedIssuesEstimateSum; } } public SprintState State { get { return this.state; } } public int Id { get { return this.id; } } public string Name { get { return this.name; } } public static Sprint CreateClosedSprint( int id, string name, DateTime start, DateTime end, int allIssuesEstimate, int completedIssuesEstimate, int incompletedIssuesEstimate, int puntedIssuesEstimate) { return new Sprint( id, name, SprintState.Closed, start, end, allIssuesEstimate, completedIssuesEstimate, incompletedIssuesEstimate, puntedIssuesEstimate); } public static Sprint CreateActiveSprint( int id, string name, DateTime start, int allIssuesEstimate, int completedIssuesEstimate, int incompletedIssuesEstimate, int puntedIssuesEstimate) { return new Sprint( id, name, SprintState.Active, start, null, allIssuesEstimate, completedIssuesEstimate, incompletedIssuesEstimate, puntedIssuesEstimate); } public void AddCompletedIssue(Issue issue) { this.completedIssues.Add(issue); } public void AddCompletedIssues(IEnumerable<Issue> issues) { this.completedIssues.AddRange(issues); } public void AddIncompletedIssue(Issue issue) { this.incompletedIssues.Add(issue); } public void AddIncompletedIssues(IEnumerable<Issue> issues) { this.incompletedIssues.AddRange(issues); } } }
#region Apache License // // 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. // #endregion using System; using System.Collections; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; using System.Threading; using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Appender that allows clients to connect via Telnet to receive log messages /// </summary> /// <remarks> /// <para> /// The TelnetAppender accepts socket connections and streams logging messages /// back to the client. /// The output is provided in a telnet-friendly way so that a log can be monitored /// over a TCP/IP socket. /// This allows simple remote monitoring of application logging. /// </para> /// <para> /// The default <see cref="Port"/> is 23 (the telnet port). /// </para> /// </remarks> /// <author>Keith Long</author> /// <author>Nicko Cadell</author> public class TelnetAppender : AppenderSkeleton { private SocketHandler m_handler; private int m_listeningPort = 23; #region Constructor /// <summary> /// Default constructor /// </summary> /// <remarks> /// <para> /// Default constructor /// </para> /// </remarks> public TelnetAppender() { } #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the TelnetAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(TelnetAppender); #endregion Private Static Fields /// <summary> /// Gets or sets the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections. /// </summary> /// <value> /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" /> /// indicating the TCP port number on which this <see cref="TelnetAppender"/> will listen for connections. /// </value> /// <remarks> /// <para> /// The default value is 23 (the telnet port). /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> /// or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public int Port { get { return m_listeningPort; } set { if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified for Port is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); } else { m_listeningPort = value; } } } #region Override implementation of AppenderSkeleton /// <summary> /// Overrides the parent method to close the socket handler /// </summary> /// <remarks> /// <para> /// Closes all the outstanding connections. /// </para> /// </remarks> protected override void OnClose() { base.OnClose(); if (m_handler != null) { m_handler.Dispose(); m_handler = null; } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> protected override bool RequiresLayout { get { return true; } } /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// Create the socket handler and wait for connections /// </para> /// </remarks> public override void ActivateOptions() { base.ActivateOptions(); try { LogLog.Debug(declaringType, "Creating SocketHandler to listen on port ["+m_listeningPort+"]"); m_handler = new SocketHandler(m_listeningPort); } catch(Exception ex) { LogLog.Error(declaringType, "Failed to create SocketHandler", ex); throw; } } /// <summary> /// Writes the logging event to each connected client. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the logging event to each connected client. /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { if (m_handler != null && m_handler.HasConnections) { m_handler.Send(RenderLoggingEvent(loggingEvent)); } } #endregion #region SocketHandler helper class /// <summary> /// Helper class to manage connected clients /// </summary> /// <remarks> /// <para> /// The SocketHandler class is used to accept connections from /// clients. It is threaded so that clients can connect/disconnect /// asynchronously. /// </para> /// </remarks> protected class SocketHandler : IDisposable { private const int MAX_CONNECTIONS = 20; private Socket m_serverSocket; private ArrayList m_clients = new ArrayList(); /// <summary> /// Class that represents a client connected to this handler /// </summary> /// <remarks> /// <para> /// Class that represents a client connected to this handler /// </para> /// </remarks> protected class SocketClient : IDisposable { private Socket m_socket; private StreamWriter m_writer; /// <summary> /// Create this <see cref="SocketClient"/> for the specified <see cref="Socket"/> /// </summary> /// <param name="socket">the client's socket</param> /// <remarks> /// <para> /// Opens a stream writer on the socket. /// </para> /// </remarks> public SocketClient(Socket socket) { m_socket = socket; try { m_writer = new StreamWriter(new NetworkStream(socket)); } catch { Dispose(); throw; } } /// <summary> /// Write a string to the client /// </summary> /// <param name="message">string to send</param> /// <remarks> /// <para> /// Write a string to the client /// </para> /// </remarks> public void Send(String message) { m_writer.Write(message); m_writer.Flush(); } #region IDisposable Members /// <summary> /// Cleanup the clients connection /// </summary> /// <remarks> /// <para> /// Close the socket connection. /// </para> /// </remarks> public void Dispose() { try { if (m_writer != null) { m_writer.Close(); m_writer = null; } } catch { } if (m_socket != null) { try { m_socket.Shutdown(SocketShutdown.Both); } catch { } try { m_socket.Close(); } catch { } m_socket = null; } } #endregion } /// <summary> /// Opens a new server port on <paramref ref="port"/> /// </summary> /// <param name="port">the local port to listen on for connections</param> /// <remarks> /// <para> /// Creates a socket handler on the specified local server port. /// </para> /// </remarks> public SocketHandler(int port) { m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_serverSocket.Bind(new IPEndPoint(IPAddress.Any, port)); m_serverSocket.Listen(5); m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null); } /// <summary> /// Sends a string message to each of the connected clients /// </summary> /// <param name="message">the text to send</param> /// <remarks> /// <para> /// Sends a string message to each of the connected clients /// </para> /// </remarks> public void Send(String message) { ArrayList localClients = m_clients; foreach (SocketClient client in localClients) { try { client.Send(message); } catch (Exception) { // The client has closed the connection, remove it from our list client.Dispose(); RemoveClient(client); } } } /// <summary> /// Add a client to the internal clients list /// </summary> /// <param name="client">client to add</param> private void AddClient(SocketClient client) { lock(this) { ArrayList clientsCopy = (ArrayList)m_clients.Clone(); clientsCopy.Add(client); m_clients = clientsCopy; } } /// <summary> /// Remove a client from the internal clients list /// </summary> /// <param name="client">client to remove</param> private void RemoveClient(SocketClient client) { lock(this) { ArrayList clientsCopy = (ArrayList)m_clients.Clone(); clientsCopy.Remove(client); m_clients = clientsCopy; } } /// <summary> /// Test if this handler has active connections /// </summary> /// <value> /// <c>true</c> if this handler has active connections /// </value> /// <remarks> /// <para> /// This property will be <c>true</c> while this handler has /// active connections, that is at least one connection that /// the handler will attempt to send a message to. /// </para> /// </remarks> public bool HasConnections { get { ArrayList localClients = m_clients; return (localClients != null && localClients.Count > 0); } } /// <summary> /// Callback used to accept a connection on the server socket /// </summary> /// <param name="asyncResult">The result of the asynchronous operation</param> /// <remarks> /// <para> /// On connection adds to the list of connections /// if there are two many open connections you will be disconnected /// </para> /// </remarks> private void OnConnect(IAsyncResult asyncResult) { try { // Block until a client connects Socket socket = m_serverSocket.EndAccept(asyncResult); LogLog.Debug(declaringType, "Accepting connection from ["+socket.RemoteEndPoint.ToString()+"]"); SocketClient client = new SocketClient(socket); int currentActiveConnectionsCount = m_clients.Count; if (currentActiveConnectionsCount < MAX_CONNECTIONS) { try { client.Send("TelnetAppender v1.0 (" + (currentActiveConnectionsCount + 1) + " active connections)\r\n\r\n"); AddClient(client); } catch { client.Dispose(); } } else { client.Send("Sorry - Too many connections.\r\n"); client.Dispose(); } } catch { } finally { if (m_serverSocket != null) { m_serverSocket.BeginAccept(new AsyncCallback(OnConnect), null); } } } #region IDisposable Members /// <summary> /// Close all network connections /// </summary> /// <remarks> /// <para> /// Make sure we close all network connections /// </para> /// </remarks> public void Dispose() { ArrayList localClients = m_clients; foreach (SocketClient client in localClients) { client.Dispose(); } m_clients.Clear(); Socket localSocket = m_serverSocket; m_serverSocket = null; try { localSocket.Shutdown(SocketShutdown.Both); } catch { } try { localSocket.Close(); } catch { } } #endregion } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Provider; using System.Security.AccessControl; namespace Microsoft.PowerShell.Commands { /// <summary> /// The FileSystemProvider provides stateless namespace navigation /// of the file system. /// </summary> public sealed partial class FileSystemProvider : NavigationCmdletProvider, IContentCmdletProvider, IPropertyCmdletProvider, ISecurityDescriptorCmdletProvider { #region ISecurityDescriptorCmdletProvider members /// <summary> /// Gets the SecurityDescriptor at the specified path, including only the specified /// AccessControlSections. /// </summary> /// <param name="path"> /// The path of the item to retrieve. It may be a drive or provider-qualified path and may include. /// glob characters. /// </param> /// <param name="sections"> /// The sections of the security descriptor to include. /// </param> /// <returns> /// Nothing. An object that represents the security descriptor for the item /// specified by path is written to the context's pipeline. /// </returns> /// <exception cref="System.ArgumentException"> /// path is null or empty. /// path doesn't exist /// sections is not valid. /// </exception> public void GetSecurityDescriptor(string path, AccessControlSections sections) { ObjectSecurity sd = null; path = NormalizePath(path); if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentNullException("path"); } if ((sections & ~AccessControlSections.All) != 0) { throw PSTraceSource.NewArgumentException("sections"); } var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); try { PlatformInvokes.EnableTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState); if (Directory.Exists(path)) { sd = new DirectorySecurity(path, sections); } else { sd = new FileSecurity(path, sections); } } catch (System.Security.SecurityException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); } finally { PlatformInvokes.RestoreTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState); } WriteSecurityDescriptorObject(sd, path); } /// <summary> /// Sets the SecurityDescriptor at the specified path. /// </summary> /// <param name="path"> /// The path of the item to set the security descriptor on. /// It may be a drive or provider-qualified path and may include. /// glob characters. /// </param> /// <param name="securityDescriptor"> /// The new security descriptor for the item. /// </param> /// <exception cref="System.ArgumentException"> /// path is null or empty. /// </exception> /// <exception cref="System.ArgumentNullException"> /// securitydescriptor is null. /// </exception> public void SetSecurityDescriptor( string path, ObjectSecurity securityDescriptor) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } path = NormalizePath(path); if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } if (!File.Exists(path) && !Directory.Exists(path)) { ThrowTerminatingError(CreateErrorRecord(path, "SetSecurityDescriptor_FileNotFound")); } FileSystemSecurity sd = securityDescriptor as FileSystemSecurity; if (sd == null) { throw PSTraceSource.NewArgumentException("securityDescriptor"); } else { // This algorithm works around the following security descriptor complexities: // // - In order to copy an ACL between files, you need to use the // binary form, and transfer all sections. If you don't use the binary form, // then the FileSystem only applies changes that have happened to that specific // ACL object -- which will not be present if you are just stamping a specific // ACL on a lot of files. // - Copying a full ACL means copying its Audit section, which normal users // don't have access to. // // In order to make this cmdlet support regular users modifying their own files, // the solution is to: // // - First attempt to copy the entire security descriptor as we did in V1. // This ensures backward compatability for administrator scripts that currently // work. // - If the attempt fails due to a PrivilegeNotHeld exception, try again with // an estimate of the minimum required subset. This is an estimate, since the // ACL object doesn't tell you exactly what's changed. // - If their ACL doesn't include any audit rules, don't try to set the // audit section. If it does contain Audit rules, continue to try and // set the section, so they get an appropriate error message. // - If their ACL has the same Owner / Group as the destination file, // also don't try to set those sections. // If they added audit rules, or made changes to the Owner / Group, they will // still get an error message. // // We can't roll the two steps into one, as the second step can't handle the // situation where an admin wants to _clear_ the audit entries. It would be nice to // detect a difference in audit entries (like we do with Owner and Group,) but // retrieving the Audit entries requires SeSecurityPrivilege as well. try { // Try to set the entire security descriptor SetSecurityDescriptor(path, sd, AccessControlSections.All); } catch (PrivilegeNotHeldException) { // Get the security descriptor of the destination path ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl(); Type ntAccountType = typeof(System.Security.Principal.NTAccount); AccessControlSections sections = AccessControlSections.All; // If they didn't modify any audit information, don't try to set // the audit section. int auditRuleCount = sd.GetAuditRules(true, true, ntAccountType).Count; if ((auditRuleCount == 0) && (sd.AreAuditRulesProtected == existingDescriptor.AreAccessRulesProtected)) { sections &= ~AccessControlSections.Audit; } // If they didn't modify the owner, don't try to set that section. if (sd.GetOwner(ntAccountType) == existingDescriptor.GetOwner(ntAccountType)) { sections &= ~AccessControlSections.Owner; } // If they didn't modify the group, don't try to set that section. if (sd.GetGroup(ntAccountType) == existingDescriptor.GetGroup(ntAccountType)) { sections &= ~AccessControlSections.Group; } // Try to set the security descriptor again, this time with a reduced set // of sections. SetSecurityDescriptor(path, sd, sections); } } } private void SetSecurityDescriptor(string path, ObjectSecurity sd, AccessControlSections sections) { var currentPrivilegeState = new PlatformInvokes.TOKEN_PRIVILEGE(); byte[] securityDescriptorBinary = null; try { // Get the binary form of the descriptor. PlatformInvokes.EnableTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState); securityDescriptorBinary = sd.GetSecurityDescriptorBinaryForm(); } finally { PlatformInvokes.RestoreTokenPrivilege("SeBackupPrivilege", ref currentPrivilegeState); } try { PlatformInvokes.EnableTokenPrivilege("SeRestorePrivilege", ref currentPrivilegeState); // Transfer it to the new file / directory. // We keep these two code branches so that we can have more // granular information when we ouput the object type via // WriteSecurityDescriptorObject. if (Directory.Exists(path)) { DirectorySecurity newDescriptor = new DirectorySecurity(); newDescriptor.SetSecurityDescriptorBinaryForm(securityDescriptorBinary, sections); new DirectoryInfo(path).SetAccessControl(newDescriptor); WriteSecurityDescriptorObject(newDescriptor, path); } else { FileSecurity newDescriptor = new FileSecurity(); newDescriptor.SetSecurityDescriptorBinaryForm(securityDescriptorBinary, sections); new FileInfo(path).SetAccessControl(newDescriptor); WriteSecurityDescriptorObject(newDescriptor, path); } } finally { PlatformInvokes.RestoreTokenPrivilege("SeRestorePrivilege", ref currentPrivilegeState); } } /// <summary> /// Creates a new empty security descriptor of the same type as /// the item specified by the path. If "path" points to a file system directory, /// then the descriptor returned will be of type DirectorySecurity. /// </summary> /// <param name="path"> /// Path of the item to use to determine the type of resulting /// SecurityDescriptor. /// </param> /// <param name="sections"> /// The sections of the security descriptor to create. /// </param> /// <returns> /// A new ObjectSecurity object of the same type as /// the item specified by the path. /// </returns> public ObjectSecurity NewSecurityDescriptorFromPath( string path, AccessControlSections sections) { ItemType itemType = ItemType.Unknown; if (IsItemContainer(path)) { itemType = ItemType.Directory; } else { itemType = ItemType.File; } return NewSecurityDescriptor(itemType); } /// <summary> /// Creates a new empty security descriptor of the specified type. /// </summary> /// <param name="type"> /// The type of Security Descriptor to create. Valid types are /// "file", "directory," and "container." /// </param> /// <param name="sections"> /// The sections of the security descriptor to create. /// </param> /// <returns> /// A new ObjectSecurity object of the specified type. /// </returns> public ObjectSecurity NewSecurityDescriptorOfType( string type, AccessControlSections sections) { ItemType itemType = ItemType.Unknown; itemType = GetItemType(type); return NewSecurityDescriptor(itemType); } private static ObjectSecurity NewSecurityDescriptor( ItemType itemType) { ObjectSecurity sd = null; switch (itemType) { case ItemType.File: sd = new FileSecurity(); break; case ItemType.Directory: sd = new DirectorySecurity(); break; } return sd; } private static ErrorRecord CreateErrorRecord(string path, string errorId) { string message = null; message = StringUtil.Format(FileSystemProviderStrings.FileNotFound, path); ErrorRecord er = new ErrorRecord(new FileNotFoundException(message), errorId, ErrorCategory.ObjectNotFound, null); return er; } #endregion ISecurityDescriptorCmdletProvider members } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1 { internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private readonly int _correlationId; private readonly MemberRangeMap _memberRangeMap; private readonly AnalyzerExecutor _executor; private readonly StateManager _stateManager; private readonly SimpleTaskQueue _eventQueue; public DiagnosticIncrementalAnalyzer( DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, HostAnalyzerManager analyzerManager, AbstractHostDiagnosticUpdateSource hostDiagnosticUpdateSource) : base(owner, workspace, analyzerManager, hostDiagnosticUpdateSource) { _correlationId = correlationId; _memberRangeMap = new MemberRangeMap(); _executor = new AnalyzerExecutor(this); _eventQueue = new SimpleTaskQueue(TaskScheduler.Default); _stateManager = new StateManager(analyzerManager); _stateManager.ProjectAnalyzerReferenceChanged += OnProjectAnalyzerReferenceChanged; } private void OnProjectAnalyzerReferenceChanged(object sender, ProjectAnalyzerReferenceChangedEventArgs e) { if (e.Removed.Length == 0) { // nothing to refresh return; } // guarantee order of the events. var asyncToken = Owner.Listener.BeginAsyncOperation(nameof(OnProjectAnalyzerReferenceChanged)); _eventQueue.ScheduleTask(() => ClearProjectStatesAsync(e.Project, e.Removed, CancellationToken.None), CancellationToken.None).CompletesAsyncOperation(asyncToken); } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken)) { return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentClose, GetResetLogMessage, document, cancellationToken)) { // we don't need the info for closed file _memberRangeMap.Remove(document.Id); return ClearOnlyDocumentStates(document, raiseEvent: true, cancellationToken: cancellationToken); } } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken)) { // unlike document open or close where we don't know whether this document will be re-analyzed again due to // engine's option such as "Close File Diagnostics", this one will be called when we want to re-analyze the document // for whatever reason. so we let events to be raised when actual analysis happens but clear the cache so that // we don't return existing data without re-analysis. return ClearOnlyDocumentStates(document, raiseEvent: false, cancellationToken: cancellationToken); } } private Task ClearOnlyDocumentStates(Document document, bool raiseEvent, CancellationToken cancellationToken) { // we remove whatever information we used to have on document open/close and re-calculate diagnostics // we had to do this since some diagnostic analyzer changes its behavior based on whether the document is opened or not. // so we can't use cached information. ClearDocumentStates(document, _stateManager.GetStateSets(document.Project), raiseEvent, includeProjectState: false, cancellationToken: cancellationToken); return SpecializedTasks.EmptyTask; } private bool CheckOption(Workspace workspace, string language, bool documentOpened) { var optionService = workspace.Services.GetService<IOptionService>(); if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language)) { return true; } if (documentOpened) { return true; } return false; } internal IEnumerable<DiagnosticAnalyzer> GetAnalyzers(Project project) { return _stateManager.GetAnalyzers(project); } public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken); var openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Syntax, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Syntax, diagnosticIds)) { var data = await _executor.GetSyntaxAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Syntax, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } var state = stateSet.GetState(StateType.Syntax); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion, projectVersion); if (bodyOpt == null) { await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false); } else { // only open file can go this route await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken) { try { // syntax facts service must exist, otherwise, this method won't have called. var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var memberId = syntaxFacts.GetMethodLevelMemberId(root, member); var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, this, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, this, cancellationToken); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, document.Project)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document)) { var supportsSemanticInSpan = stateSet.Analyzer.SupportsSpanBasedSemanticDiagnosticAnalysis(); var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; var ranges = _memberRangeMap.GetSavedMemberRange(stateSet.Analyzer, document); var data = await _executor.GetDocumentBodyAnalysisDataAsync( stateSet, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false); _memberRangeMap.UpdateMemberRange(stateSet.Analyzer, document, versions.TextVersion, memberId, member.FullSpan, ranges); var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, this, cancellationToken); bool openedDocument = document.IsOpen(); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(document.Project)) { if (SkipRunningAnalyzer(document.Project.CompilationOptions, userDiagnosticDriver, openedDocument, skipClosedFileChecks, stateSet)) { await ClearExistingDiagnostics(document, stateSet, StateType.Document, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Document, diagnosticIds)) { var data = await _executor.GetDocumentAnalysisDataAsync(userDiagnosticDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Document, document.Id, stateSet, new SolutionArgument(document), data.Items); continue; } if (openedDocument) { _memberRangeMap.Touch(stateSet.Analyzer, document, versions.TextVersion); } var state = stateSet.GetState(StateType.Document); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDocumentDiagnosticsUpdatedIfNeeded(StateType.Document, document, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { await AnalyzeProjectAsync(project, cancellationToken).ConfigureAwait(false); } private async Task AnalyzeProjectAsync(Project project, CancellationToken cancellationToken) { try { // Compilation actions can report diagnostics on open files, so "documentOpened = true" if (!CheckOption(project.Solution.Workspace, project.Language, documentOpened: true)) { return; } var projectTextVersion = await project.GetLatestDocumentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var analyzerDriver = new DiagnosticAnalyzerDriver(project, this, cancellationToken); var versions = new VersionArgument(projectTextVersion, semanticVersion, projectVersion); foreach (var stateSet in _stateManager.GetOrUpdateStateSets(project)) { // Compilation actions can report diagnostics on open files, so we skipClosedFileChecks. if (SkipRunningAnalyzer(project.CompilationOptions, analyzerDriver, openedDocument: true, skipClosedFileChecks: true, stateSet: stateSet)) { await ClearExistingDiagnostics(project, stateSet, cancellationToken).ConfigureAwait(false); continue; } if (ShouldRunAnalyzerForStateType(stateSet.Analyzer, StateType.Project, diagnosticIds: null)) { var data = await _executor.GetProjectAnalysisDataAsync(analyzerDriver, stateSet, versions).ConfigureAwait(false); if (data.FromCache) { RaiseProjectDiagnosticsUpdated(project, stateSet, data.Items); continue; } var state = stateSet.GetState(StateType.Project); await PersistProjectData(project, state, data).ConfigureAwait(false); RaiseProjectDiagnosticsUpdatedIfNeeded(project, stateSet, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private bool SkipRunningAnalyzer( CompilationOptions compilationOptions, DiagnosticAnalyzerDriver userDiagnosticDriver, bool openedDocument, bool skipClosedFileChecks, StateSet stateSet) { if (Owner.IsAnalyzerSuppressed(stateSet.Analyzer, userDiagnosticDriver.Project)) { return true; } if (skipClosedFileChecks) { return false; } if (ShouldRunAnalyzerForClosedFile(compilationOptions, openedDocument, stateSet.Analyzer)) { return false; } return true; } private static async Task PersistProjectData(Project project, DiagnosticState state, AnalysisData data) { // TODO: Cancellation is not allowed here to prevent data inconsistency. But there is still a possibility of data inconsistency due to // things like exception. For now, I am letting it go and let v2 engine take care of it properly. If v2 doesnt come online soon enough // more refactoring is required on project state. // clear all existing data state.Remove(project.Id); foreach (var document in project.Documents) { state.Remove(document.Id); } // quick bail out if (data.Items.Length == 0) { return; } // save new data var group = data.Items.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { // save project scope diagnostics await state.PersistAsync(project, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); continue; } // save document scope diagnostics var document = project.GetDocument(kv.Key); if (document == null) { continue; } await state.PersistAsync(document, new AnalysisData(data.TextVersion, data.DataVersion, kv.ToImmutableArrayOrEmpty()), CancellationToken.None).ConfigureAwait(false); } } public override void RemoveDocument(DocumentId documentId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None)) { _memberRangeMap.Remove(documentId); foreach (var stateSet in _stateManager.GetStateSets(documentId.ProjectId)) { stateSet.Remove(documentId); var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId); for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { RaiseDiagnosticsUpdated((StateType)stateType, documentId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } } } } public override void RemoveProject(ProjectId projectId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None)) { foreach (var stateSet in _stateManager.GetStateSets(projectId)) { stateSet.Remove(projectId); var solutionArgs = new SolutionArgument(null, projectId, null); RaiseDiagnosticsUpdated(StateType.Project, projectId, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } } _stateManager.RemoveStateSet(projectId); } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: false, diagnostics: diagnostics, cancellationToken: cancellationToken); return await getter.TryGetAsync().ConfigureAwait(false); } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var getter = new LatestDiagnosticsForSpanGetter(this, document, root, range, blockForData: true, cancellationToken: cancellationToken); var result = await getter.TryGetAsync().ConfigureAwait(false); Contract.Requires(result); return getter.Diagnostics; } private bool ShouldRunAnalyzerForClosedFile(CompilationOptions options, bool openedDocument, DiagnosticAnalyzer analyzer) { // we have opened document, doesnt matter if (openedDocument || analyzer.IsCompilerAnalyzer()) { return true; } // PERF: Don't query descriptors for compiler analyzer, always execute it. if (analyzer.IsCompilerAnalyzer()) { return true; } return Owner.GetDiagnosticDescriptors(analyzer).Any(d => GetEffectiveSeverity(d, options) != ReportDiagnostic.Hidden); } private static ReportDiagnostic GetEffectiveSeverity(DiagnosticDescriptor descriptor, CompilationOptions options) { return options == null ? MapSeverityToReport(descriptor.DefaultSeverity) : descriptor.GetEffectiveSeverity(options); } private static ReportDiagnostic MapSeverityToReport(DiagnosticSeverity severity) { switch (severity) { case DiagnosticSeverity.Hidden: return ReportDiagnostic.Hidden; case DiagnosticSeverity.Info: return ReportDiagnostic.Info; case DiagnosticSeverity.Warning: return ReportDiagnostic.Warn; case DiagnosticSeverity.Error: return ReportDiagnostic.Error; default: throw ExceptionUtilities.Unreachable; } } private bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds) { return ShouldRunAnalyzerForStateType(analyzer, stateTypeId, diagnosticIds, Owner.GetDiagnosticDescriptors); } private static bool ShouldRunAnalyzerForStateType(DiagnosticAnalyzer analyzer, StateType stateTypeId, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptors = null) { // PERF: Don't query descriptors for compiler analyzer, always execute it for all state types. if (analyzer.IsCompilerAnalyzer()) { return true; } if (diagnosticIds != null && getDescriptors(analyzer).All(d => !diagnosticIds.Contains(d.Id))) { return false; } switch (stateTypeId) { case StateType.Syntax: return analyzer.SupportsSyntaxDiagnosticAnalysis(); case StateType.Document: return analyzer.SupportsSemanticDiagnosticAnalysis(); case StateType.Project: return analyzer.SupportsProjectDiagnosticAnalysis(); default: throw ExceptionUtilities.Unreachable; } } public override void LogAnalyzerCountSummary() { DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, DiagnosticLogAggregator); DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, DiagnosticLogAggregator); // reset the log aggregator ResetDiagnosticLogAggregator(); } private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return VersionStamp.CanReusePersistedVersion(versions.TextVersion, existingData.TextVersion) && project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private void RaiseDocumentDiagnosticsUpdatedIfNeeded( StateType type, Document document, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseDiagnosticsUpdated(type, document.Id, stateSet, new SolutionArgument(document), newItems); } private void RaiseProjectDiagnosticsUpdatedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (noItems) { return; } RaiseProjectDiagnosticsRemovedIfNeeded(project, stateSet, existingItems, newItems); RaiseProjectDiagnosticsUpdated(project, stateSet, newItems); } private void RaiseProjectDiagnosticsRemovedIfNeeded( Project project, StateSet stateSet, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { if (existingItems.Length == 0) { return; } var removedItems = existingItems.GroupBy(d => d.DocumentId).Select(g => g.Key).Except(newItems.GroupBy(d => d.DocumentId).Select(g => g.Key)); foreach (var documentId in removedItems) { if (documentId == null) { RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), ImmutableArray<DiagnosticData>.Empty); continue; } var document = project.GetDocument(documentId); var argument = documentId == null ? new SolutionArgument(null, documentId.ProjectId, documentId) : new SolutionArgument(document); RaiseDiagnosticsUpdated(StateType.Project, documentId, stateSet, argument, ImmutableArray<DiagnosticData>.Empty); } } private void RaiseProjectDiagnosticsUpdated(Project project, StateSet stateSet, ImmutableArray<DiagnosticData> diagnostics) { var group = diagnostics.GroupBy(d => d.DocumentId); foreach (var kv in group) { if (kv.Key == null) { RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, new SolutionArgument(project), kv.ToImmutableArrayOrEmpty()); continue; } RaiseDiagnosticsUpdated(StateType.Project, kv.Key, stateSet, new SolutionArgument(project.GetDocument(kv.Key)), kv.ToImmutableArrayOrEmpty()); } } private static ImmutableArray<DiagnosticData> GetDiagnosticData(ILookup<DocumentId, DiagnosticData> lookup, DocumentId documentId) { return lookup.Contains(documentId) ? lookup[documentId].ToImmutableArrayOrEmpty() : ImmutableArray<DiagnosticData>.Empty; } private void RaiseDiagnosticsUpdated( StateType type, object key, StateSet stateSet, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics) { if (Owner == null) { return; } // get right arg id for the given analyzer var id = stateSet.ErrorSourceName != null ? new HostAnalyzerKey(stateSet.Analyzer, type, key, stateSet.ErrorSourceName) : (object)new ArgumentKey(stateSet.Analyzer, type, key); Owner.RaiseDiagnosticsUpdated(this, new DiagnosticsUpdatedArgs(id, Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics)); } private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics( AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics, SyntaxTree tree, SyntaxNode member, int memberId) { // get old span var oldSpan = range[memberId]; // get old diagnostics var diagnostics = existingData.Items; // check quick exit cases if (diagnostics.Length == 0 && memberDiagnostics.Length == 0) { return diagnostics; } // simple case if (diagnostics.Length == 0 && memberDiagnostics.Length > 0) { return memberDiagnostics; } // regular case var result = new List<DiagnosticData>(); // update member location Contract.Requires(member.FullSpan.Start == oldSpan.Start); var delta = member.FullSpan.End - oldSpan.End; var replaced = false; foreach (var diagnostic in diagnostics) { if (diagnostic.TextSpan.Start < oldSpan.Start) { result.Add(diagnostic); continue; } if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } if (oldSpan.End <= diagnostic.TextSpan.Start) { result.Add(UpdatePosition(diagnostic, tree, delta)); continue; } } // if it haven't replaced, replace it now if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } return result.ToImmutableArray(); } private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta) { var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length); var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length); var mappedLineInfo = tree.GetMappedLineSpan(newSpan); var originalLineInfo = tree.GetLineSpan(newSpan); return new DiagnosticData( diagnostic.Id, diagnostic.Category, diagnostic.Message, diagnostic.ENUMessageForBingSearch, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.CustomTags, diagnostic.Properties, diagnostic.Workspace, diagnostic.ProjectId, new DiagnosticDataLocation(diagnostic.DocumentId, newSpan, originalFilePath: originalLineInfo.Path, originalStartLine: originalLineInfo.StartLinePosition.Line, originalStartColumn: originalLineInfo.StartLinePosition.Character, originalEndLine: originalLineInfo.EndLinePosition.Line, originalEndColumn: originalLineInfo.EndLinePosition.Character, mappedFilePath: mappedLineInfo.GetMappedFilePathIfExist(), mappedStartLine: mappedLineInfo.StartLinePosition.Line, mappedStartColumn: mappedLineInfo.StartLinePosition.Character, mappedEndLine: mappedLineInfo.EndLinePosition.Line, mappedEndColumn: mappedLineInfo.EndLinePosition.Character), description: diagnostic.Description, helpLink: diagnostic.HelpLink, isSuppressed: diagnostic.IsSuppressed); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, SyntaxTree tree, TextSpan? span, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, tree, span)).Select(d => DiagnosticData.Create(document, d)) : null; } private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, SyntaxTree tree, TextSpan? span) { if (diagnostic == null) { return false; } if (diagnostic.Location == null || diagnostic.Location == Location.None) { return false; } if (diagnostic.Location.SourceTree != tree) { return false; } if (span == null) { return true; } return span.Value.Contains(diagnostic.Location.SourceSpan); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics) { if (diagnostics == null) { yield break; } foreach (var diagnostic in diagnostics) { if (diagnostic.Location == null || diagnostic.Location == Location.None) { yield return DiagnosticData.Create(project, diagnostic); continue; } var document = project.GetDocument(diagnostic.Location.SourceTree); if (document == null) { continue; } yield return DiagnosticData.Create(document, diagnostic); } } private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var tree = await userDiagnosticDriver.Document.GetSyntaxTreeAsync(userDiagnosticDriver.CancellationToken).ConfigureAwait(false); var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, tree, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(DiagnosticAnalyzerDriver userDiagnosticDriver, DiagnosticAnalyzer analyzer) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, analyzer, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(analyzer); var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(analyzer).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private void ClearDocumentStates( Document document, IEnumerable<StateSet> states, bool raiseEvent, bool includeProjectState, CancellationToken cancellationToken) { // Compiler + User diagnostics foreach (var state in states) { for (var stateType = 0; stateType < s_stateTypeCount; stateType++) { if (!includeProjectState && stateType == (int)StateType.Project) { // don't re-set project state type continue; } cancellationToken.ThrowIfCancellationRequested(); ClearDocumentState(document, state, (StateType)stateType, raiseEvent); } } } private void ClearDocumentState(Document document, StateSet stateSet, StateType type, bool raiseEvent) { var state = stateSet.GetState(type); // remove saved info state.Remove(document.Id); if (raiseEvent) { // raise diagnostic updated event var documentId = document.Id; var solutionArgs = new SolutionArgument(document); RaiseDiagnosticsUpdated(type, document.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } } private void ClearProjectStatesAsync(Project project, IEnumerable<StateSet> states, CancellationToken cancellationToken) { foreach (var document in project.Documents) { ClearDocumentStates(document, states, raiseEvent: true, includeProjectState: true, cancellationToken: cancellationToken); } foreach (var stateSet in states) { cancellationToken.ThrowIfCancellationRequested(); ClearProjectState(project, stateSet); } } private void ClearProjectState(Project project, StateSet stateSet) { var state = stateSet.GetState(StateType.Project); // remove saved cache state.Remove(project.Id); // raise diagnostic updated event var solutionArgs = new SolutionArgument(project); RaiseDiagnosticsUpdated(StateType.Project, project.Id, stateSet, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } private async Task ClearExistingDiagnostics(Document document, StateSet stateSet, StateType type, CancellationToken cancellationToken) { var state = stateSet.GetState(type); var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearDocumentState(document, stateSet, type, raiseEvent: true); } } private async Task ClearExistingDiagnostics(Project project, StateSet stateSet, CancellationToken cancellationToken) { var state = stateSet.GetState(StateType.Project); var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false); if (existingData?.Items.Length > 0) { ClearProjectState(project, stateSet); } } private static string GetSyntaxLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetSemanticLogMessage(Document document, TextSpan? span, DiagnosticAnalyzer analyzer) { return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", analyzer.ToString()); } private static string GetProjectLogMessage(Project project, DiagnosticAnalyzer analyzer) { return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, analyzer.ToString()); } private static string GetResetLogMessage(Document document) { return string.Format("document reset: {0}", document.FilePath ?? document.Name); } private static string GetOpenLogMessage(Document document) { return string.Format("document open: {0}", document.FilePath ?? document.Name); } private static string GetRemoveLogMessage(DocumentId id) { return string.Format("document remove: {0}", id.ToString()); } private static string GetRemoveLogMessage(ProjectId id) { return string.Format("project remove: {0}", id.ToString()); } public override Task NewSolutionSnapshotAsync(Solution newSolution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using System.Security.Permissions; namespace System.DirectoryServices.AccountManagement { [DirectoryRdnPrefix("CN")] public class AuthenticablePrincipal : Principal { // // Public Properties // // Enabled property private bool _enabled = false; // the actual property value private LoadState _enabledChanged = LoadState.NotSet; // change-tracking public Nullable<bool> Enabled { get { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // Different stores have different defaults as to the Enabled setting // (AD: creates disabled by default; SAM: creates enabled by default). // So if the principal is unpersisted (and thus we may not know what store it's // going to end up in), we'll just return null unless they previously // set an explicit value. if (this.unpersisted && (_enabledChanged != LoadState.Changed)) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthenticablePrincipal", "Enabled: returning null, unpersisted={0}, enabledChanged={1}", this.unpersisted, _enabledChanged); return null; } return HandleGet<bool>(ref _enabled, PropertyNames.AuthenticablePrincipalEnabled, ref _enabledChanged); } set { // Make sure we're not disposed or deleted. Although HandleGet/HandleSet will check this, // we need to check these before we do anything else. CheckDisposedOrDeleted(); // We don't want to let them set a null value. if (!value.HasValue) throw new ArgumentNullException(nameof(value)); HandleSet<bool>(ref _enabled, value.Value, ref _enabledChanged, PropertyNames.AuthenticablePrincipalEnabled); } } // // AccountInfo-related properties/methods // private AccountInfo _accountInfo = null; private AccountInfo AccountInfo { get { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (_accountInfo == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "AccountInfo: creating new AccountInfo"); _accountInfo = new AccountInfo(this); } return _accountInfo; } } public Nullable<DateTime> AccountLockoutTime { get { return this.AccountInfo.AccountLockoutTime; } } public Nullable<DateTime> LastLogon { get { return this.AccountInfo.LastLogon; } } public PrincipalValueCollection<string> PermittedWorkstations { get { return this.AccountInfo.PermittedWorkstations; } } public byte[] PermittedLogonTimes { get { return this.AccountInfo.PermittedLogonTimes; } set { this.AccountInfo.PermittedLogonTimes = value; } } public Nullable<DateTime> AccountExpirationDate { get { return this.AccountInfo.AccountExpirationDate; } set { this.AccountInfo.AccountExpirationDate = value; } } public bool SmartcardLogonRequired { get { return this.AccountInfo.SmartcardLogonRequired; } set { this.AccountInfo.SmartcardLogonRequired = value; } } public bool DelegationPermitted { get { return this.AccountInfo.DelegationPermitted; } set { this.AccountInfo.DelegationPermitted = value; } } public int BadLogonCount { get { return this.AccountInfo.BadLogonCount; } } public string HomeDirectory { get { return this.AccountInfo.HomeDirectory; } set { this.AccountInfo.HomeDirectory = value; } } public string HomeDrive { get { return this.AccountInfo.HomeDrive; } set { this.AccountInfo.HomeDrive = value; } } public string ScriptPath { get { return this.AccountInfo.ScriptPath; } set { this.AccountInfo.ScriptPath = value; } } public bool IsAccountLockedOut() { return this.AccountInfo.IsAccountLockedOut(); } public void UnlockAccount() { this.AccountInfo.UnlockAccount(); } // // PasswordInfo-related properties/methods // private PasswordInfo _passwordInfo = null; private PasswordInfo PasswordInfo { get { // Make sure we're not disposed or deleted. CheckDisposedOrDeleted(); if (_passwordInfo == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "PasswordInfo: creating new PasswordInfo"); _passwordInfo = new PasswordInfo(this); } return _passwordInfo; } } public Nullable<DateTime> LastPasswordSet { get { return this.PasswordInfo.LastPasswordSet; } } public Nullable<DateTime> LastBadPasswordAttempt { get { return this.PasswordInfo.LastBadPasswordAttempt; } } public bool PasswordNotRequired { get { return this.PasswordInfo.PasswordNotRequired; } set { this.PasswordInfo.PasswordNotRequired = value; } } public bool PasswordNeverExpires { get { return this.PasswordInfo.PasswordNeverExpires; } set { this.PasswordInfo.PasswordNeverExpires = value; } } public bool UserCannotChangePassword { get { return this.PasswordInfo.UserCannotChangePassword; } set { this.PasswordInfo.UserCannotChangePassword = value; } } public bool AllowReversiblePasswordEncryption { get { return this.PasswordInfo.AllowReversiblePasswordEncryption; } set { this.PasswordInfo.AllowReversiblePasswordEncryption = value; } } internal AdvancedFilters rosf; public virtual AdvancedFilters AdvancedSearchFilter { get { return rosf; } } public void SetPassword(string newPassword) { this.PasswordInfo.SetPassword(newPassword); } public void ChangePassword(string oldPassword, string newPassword) { this.PasswordInfo.ChangePassword(oldPassword, newPassword); } public void ExpirePasswordNow() { this.PasswordInfo.ExpirePasswordNow(); } public void RefreshExpiredPassword() { this.PasswordInfo.RefreshExpiredPassword(); } // Certificates property private X509Certificate2Collection _certificates = new X509Certificate2Collection(); private List<string> _certificateOriginalThumbprints = new List<string>(); private LoadState _X509Certificate2CollectionLoaded = LoadState.NotSet; public X509Certificate2Collection Certificates { get { return HandleGet<X509Certificate2Collection>(ref _certificates, PropertyNames.AuthenticablePrincipalCertificates, ref _X509Certificate2CollectionLoaded); } } // // Public Methods // public static PrincipalSearchResult<AuthenticablePrincipal> FindByLockoutTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLockoutTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByLogonTime(PrincipalContext context, DateTime time, MatchType type) { return FindByLogonTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByExpirationTime(PrincipalContext context, DateTime time, MatchType type) { return FindByExpirationTime<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByBadPasswordAttempt(PrincipalContext context, DateTime time, MatchType type) { return FindByBadPasswordAttempt<AuthenticablePrincipal>(context, time, type); } public static PrincipalSearchResult<AuthenticablePrincipal> FindByPasswordSetTime(PrincipalContext context, DateTime time, MatchType type) { return FindByPasswordSetTime<AuthenticablePrincipal>(context, time, type); } // // Protected implementations // protected static PrincipalSearchResult<T> FindByLockoutTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByLockoutTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByLogonTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByLogonTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByExpirationTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByExpirationTime(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByBadPasswordAttempt<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByBadPasswordAttempt(time, type, typeof(T))); } protected static PrincipalSearchResult<T> FindByPasswordSetTime<T>(PrincipalContext context, DateTime time, MatchType type) { CheckFindByArgs(context, time, type, typeof(T)); return new PrincipalSearchResult<T>(context.QueryCtx.FindByPasswordSetTime(time, type, typeof(T))); } // // Private implementation // internal protected AuthenticablePrincipal(PrincipalContext context) { if (context == null) throw new ArgumentException(SR.NullArguments); this.ContextRaw = context; this.unpersisted = true; this.rosf = new AdvancedFilters(this); } internal protected AuthenticablePrincipal(PrincipalContext context, string samAccountName, string password, bool enabled) : this(context) { if (samAccountName != null) { this.SamAccountName = samAccountName; } if (password != null) { this.SetPassword(password); } this.Enabled = enabled; } static internal AuthenticablePrincipal MakeAuthenticablePrincipal(PrincipalContext ctx) { AuthenticablePrincipal ap = new AuthenticablePrincipal(ctx); ap.unpersisted = false; return ap; } private static void CheckFindByArgs(PrincipalContext context, DateTime time, MatchType type, Type subtype) { if ((subtype != typeof(AuthenticablePrincipal)) && (!subtype.IsSubclassOf(typeof(AuthenticablePrincipal)))) throw new ArgumentException(SR.AuthenticablePrincipalMustBeSubtypeOfAuthPrinc); if (context == null) throw new ArgumentNullException(nameof(context)); if (subtype == null) throw new ArgumentNullException(nameof(subtype)); } // // Load/Store // // // Loading with query results // internal override void LoadValueIntoProperty(string propertyName, object value) { switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: LoadCertificateCollection((List<byte[]>)value); RefreshOriginalThumbprintList(); _X509Certificate2CollectionLoaded = LoadState.Loaded; break; case PropertyNames.AuthenticablePrincipalEnabled: _enabled = (bool)value; _enabledChanged = LoadState.Loaded; break; default: if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { // If this is the first AccountInfo attribute we're loading, // we'll need to create the AccountInfo to hold it if (_accountInfo == null) _accountInfo = new AccountInfo(this); _accountInfo.LoadValueIntoProperty(propertyName, value); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { // If this is the first PasswordInfo attribute we're loading, // we'll need to create the PasswordInfo to hold it if (_passwordInfo == null) _passwordInfo = new PasswordInfo(this); _passwordInfo.LoadValueIntoProperty(propertyName, value); } else { base.LoadValueIntoProperty(propertyName, value); } break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal override bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: return HasCertificateCollectionChanged(); case PropertyNames.AuthenticablePrincipalEnabled: return _enabledChanged == LoadState.Changed; default: // Check if the property is supported by AdvancedFilter class. // If writeable properties are added to the rosf class then we will need // to add some type of tag to the property names to differentiate them here bool? val = rosf.GetChangeStatusForProperty(propertyName); if (val.HasValue == true) return val.Value; if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { if (_accountInfo == null) return false; return _accountInfo.GetChangeStatusForProperty(propertyName); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { if (_passwordInfo == null) return false; return _passwordInfo.GetChangeStatusForProperty(propertyName); } else { return base.GetChangeStatusForProperty(propertyName); } } } // Given a property name, returns the current value for the property. internal override object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case PropertyNames.AuthenticablePrincipalCertificates: return _certificates; case PropertyNames.AuthenticablePrincipalEnabled: return _enabled; default: object val = rosf.GetValueForProperty(propertyName); if (null != val) return val; if (propertyName.StartsWith(PropertyNames.AcctInfoPrefix, StringComparison.Ordinal)) { if (_accountInfo == null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(AcctInfo): shouldn't be here"); throw new InvalidOperationException(); } return _accountInfo.GetValueForProperty(propertyName); } else if (propertyName.StartsWith(PropertyNames.PwdInfoPrefix, StringComparison.Ordinal)) { if (_passwordInfo == null) { // Should never happen, since GetChangeStatusForProperty returned false Debug.Fail("AuthenticablePrincipal.GetValueForProperty(PwdInfo): shouldn't be here"); throw new InvalidOperationException(); } return _passwordInfo.GetValueForProperty(propertyName); } else { return base.GetValueForProperty(propertyName); } } } // Reset all change-tracking status for all properties on the object to "unchanged". internal override void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "ResetAllChangeStatus"); _enabledChanged = (_enabledChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; RefreshOriginalThumbprintList(); if (_accountInfo != null) { _accountInfo.ResetAllChangeStatus(); } if (_passwordInfo != null) { _passwordInfo.ResetAllChangeStatus(); } rosf.ResetAllChangeStatus(); base.ResetAllChangeStatus(); } // // Certificate support routines // // Given a list of certs (expressed as byte[]s), loads them into // the certificate collection private void LoadCertificateCollection(List<byte[]> certificatesToLoad) { // To support reload _certificates.Clear(); Debug.Assert(_certificates.Count == 0); GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "LoadCertificateCollection: loading {0} certs", certificatesToLoad.Count); foreach (byte[] rawCert in certificatesToLoad) { try { _certificates.Import(rawCert); } catch (System.Security.Cryptography.CryptographicException) { // skip the invalid certificate GlobalDebug.WriteLineIf(GlobalDebug.Warn, "AuthenticablePrincipal", "LoadCertificateCollection: skipped bad cert"); continue; } } } // Regenerates the certificateOriginalThumbprints list based on what's // currently in the certificate collection private void RefreshOriginalThumbprintList() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "RefreshOriginalThumbprintList: resetting thumbprints"); _certificateOriginalThumbprints.Clear(); foreach (X509Certificate2 certificate in _certificates) { _certificateOriginalThumbprints.Add(certificate.Thumbprint); } } // Returns true if the certificate collection has changed since the last time // certificateOriginalThumbprints was refreshed (i.e., since the last time // RefreshOriginalThumbprintList was called) private bool HasCertificateCollectionChanged() { // If the size isn't the same, the collection has certainly changed if (_certificates.Count != _certificateOriginalThumbprints.Count) { GlobalDebug.WriteLineIf( GlobalDebug.Info, "AuthenticablePrincipal", "HasCertificateCollectionChanged: original count {0}, current count{1}", _certificateOriginalThumbprints.Count, _certificates.Count); return true; } // Make a copy of the thumbprint list, so we can alter the copy without effecting the original. List<string> remainingOriginalThumbprints = new List<string>(_certificateOriginalThumbprints); foreach (X509Certificate2 certificate in _certificates) { string thumbprint = certificate.Thumbprint; // If we found a cert whose thumbprint wasn't in the thumbprints list, // it was inserted --> collection has changed if (!remainingOriginalThumbprints.Contains(thumbprint)) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "AuthenticablePrincipal", "RefreshOriginalThumbprintList: found inserted cert"); return true; } // We remove the thumbprint from the list so that if, for some reason, they inserted // a duplicate of a certificate that was already in the list, we'll detect it as an insert // when we encounter that cert a second time remainingOriginalThumbprints.Remove(thumbprint); } // If a certificate was deleted, there are two possibilities: // (1) The removal caused the size to change. We'll have caught it above and returned true. // (2) The size didn't change (because there was also an insert). We'll have caught the insert // above and returned true. Note that even if they insert a duplicate of a cert that was // already in the collection, we'll catch it because we remove the thumbprint from the // local copy of the thumbprint list each time we use that thumbprint. Debug.Assert(remainingOriginalThumbprints.Count == 0); return false; } } }