context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//--------------------------------------------------------------------------- // // <copyright file="PolyQuadraticBezierSegment.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class PolyQuadraticBezierSegment : PathSegment { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new PolyQuadraticBezierSegment Clone() { return (PolyQuadraticBezierSegment)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new PolyQuadraticBezierSegment CloneCurrentValue() { return (PolyQuadraticBezierSegment)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// Points - PointCollection. Default value is new FreezableDefaultValueFactory(PointCollection.Empty). /// </summary> public PointCollection Points { get { return (PointCollection) GetValue(PointsProperty); } set { SetValueInternal(PointsProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new PolyQuadraticBezierSegment(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // Points // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the PolyQuadraticBezierSegment.Points property. /// </summary> public static readonly DependencyProperty PointsProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal static PointCollection s_Points = PointCollection.Empty; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static PolyQuadraticBezierSegment() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // Debug.Assert(s_Points == null || s_Points.IsFrozen, "Detected context bound default value PolyQuadraticBezierSegment.s_Points (See OS Bug #947272)."); // Initializations Type typeofThis = typeof(PolyQuadraticBezierSegment); PointsProperty = RegisterProperty("Points", typeof(PointCollection), typeofThis, new FreezableDefaultValueFactory(PointCollection.Empty), null, null, /* isIndependentlyAnimated = */ false, /* coerceValueCallback */ null); } #endregion Constructors } }
// // MockHttpRequestHandler.cs // // Author: // Pasin Suriyentrakorn <[email protected]> // // Copyright (c) 2014 Couchbase Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Net.Http; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Linq; using System.IO; using Newtonsoft.Json.Linq; namespace Couchbase.Lite.Tests { public class MockHttpRequestHandler : HttpClientHandler { #region Global Delegates public delegate HttpResponseMessage HttpResponseDelegate(HttpRequestMessage request); #endregion #region Constructors public MockHttpRequestHandler(bool defaultFail = true) { responders = new Dictionary<string, HttpResponseDelegate>(); CapturedRequests = new List<HttpRequestMessage>(); if(defaultFail) AddDefaultResponders(); _defaultFail = defaultFail; } #endregion #region Instance Members private bool _defaultFail; public Int32 ResponseDelayMilliseconds { get; set; } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Delay(); var requestDeepCopy = CopyRequest(request); capturedRequests.Add(requestDeepCopy); HttpResponseDelegate responder; if(!responders.TryGetValue("*", out responder)) { foreach(var urlPattern in responders.Keys) { if (request.RequestUri.PathAndQuery.Contains(urlPattern)) { responder = responders[urlPattern]; break; } } } if (responder != null) { HttpResponseMessage message = null; try { message = responder(request); } catch(Exception e) { var tcs = new TaskCompletionSource<HttpResponseMessage>(); tcs.SetException(e); return tcs.Task; } Task<HttpResponseMessage> retVal = Task.FromResult<HttpResponseMessage>(message); NotifyResponseListeners(request, message); if (message is RequestCorrectHttpMessage) return base.SendAsync(request, cancellationToken); return retVal; } else if(_defaultFail) { throw new Exception("No responders matched for url pattern: " + request.RequestUri.PathAndQuery); } return base.SendAsync(request, cancellationToken); } public void SetResponder(string urlPattern, HttpResponseDelegate responder) { responders[urlPattern] = responder; } public void ClearCapturedRequests() { capturedRequests.Clear(); } public void AddDefaultResponders() { AddResponderFakeBulkDocs(); AddResponderRevDiffsAllMissing(); AddResponderFakeLocalDocumentUpdateIOException(); } public void AddResponderFakeBulkDocs() { HttpResponseDelegate responder = (request) => FakeBulkDocs(request); SetResponder("_bulk_docs", responder); } public void AddResponderRevDiffsAllMissing() { HttpResponseDelegate responder = (request) => FakeRevsDiff(request); SetResponder("_revs_diff", responder); } public void AddResponderFakeLocalDocumentUpdateIOException() { HttpResponseDelegate responder = (request) => FakeLocalDocumentUpdateIOException(request); SetResponder("_local", responder); } public void AddResponderFailAllRequests(HttpStatusCode statusCode) { HttpResponseDelegate responder = (request) => new HttpResponseMessage(statusCode); SetResponder("*", responder); } public void AddResponderThrowExceptionAllRequests() { HttpResponseDelegate responder = (request) => { throw new WebException("Test WebException", WebExceptionStatus.UnknownError); }; SetResponder("*", responder); } public void AddResponderFakeLocalDocumentUpdate404() { var json = "{\"error\":\"not_found\",\"reason\":\"missing\"}"; HttpResponseDelegate responder = (request) => GenerateHttpResponseMessage(HttpStatusCode.NotFound, null, json); SetResponder("_local", responder); } public void AddResponderReturnInvalidChangesFeedJson() { var json = "{\"results\":[wedon'tneednoquotes]}"; HttpResponseDelegate responder = (request) => GenerateHttpResponseMessage(HttpStatusCode.Accepted, null, json); SetResponder("_changes", responder); } public void AddResponderReturnEmptyChangesFeed() { var json = "{\"results\":[]}"; HttpResponseDelegate responder = (request) => GenerateHttpResponseMessage(HttpStatusCode.Accepted, null, json); SetResponder("_changes", responder); } public void ClearResponders() { responders.Clear(); } #endregion #region Non-Public Instance Members private IDictionary <string, HttpResponseDelegate> responders; private IList <HttpRequestMessage> capturedRequests; internal IList<HttpRequestMessage> CapturedRequests { private set { capturedRequests = value; } get { var snapshot = new List<HttpRequestMessage>(capturedRequests); return snapshot; } } private HttpRequestMessage CopyRequest(HttpRequestMessage request) { //The Windows version of HttpClient uncontrollably disposes the //HttpContent of an HttpRequestMessage once the message is sent //so we need to make a copy of it to store in the capturedRequests //collection var retVal = new HttpRequestMessage(request.Method, request.RequestUri) { Version = request.Version }; foreach (var header in request.Headers) { retVal.Headers.Add(header.Key, header.Value); } //Expand as needed if (request.Content is ByteArrayContent) { byte[] data = request.Content.ReadAsByteArrayAsync().Result; retVal.Content = new ByteArrayContent(data); } else { retVal.Content = request.Content; } return retVal; } private void Delay() { if (ResponseDelayMilliseconds > 0) { Thread.Sleep(ResponseDelayMilliseconds); } } private void NotifyResponseListeners(HttpRequestMessage request, HttpResponseMessage response) { // TODO: } #endregion #region Static Members public static IDictionary<string, object> GetJsonMapFromRequest(HttpRequestMessage request) { var bytesTask = request.Content.ReadAsByteArrayAsync(); bytesTask.Wait(TimeSpan.FromSeconds(3)); var value = Manager.GetObjectMapper().ReadValue<object>(bytesTask.Result); IDictionary<string, object> jsonMap = null; if (value is JObject) { jsonMap = ((JObject)value).ToObject<IDictionary<string, object>>(); } else { jsonMap = (IDictionary<string, object>)value; } return jsonMap; } public static HttpResponseMessage GenerateHttpResponseMessage(IDictionary<string, object> content) { var message = new HttpResponseMessage(HttpStatusCode.OK); if (content != null) { var bytes = Manager.GetObjectMapper().WriteValueAsBytes<IDictionary<string, object>>(content).ToArray(); var byteContent = new ByteArrayContent(bytes); message.Content = byteContent; } return message; } public static HttpResponseMessage GenerateHttpResponseMessage(IList<IDictionary<string, object>> content) { var message = new HttpResponseMessage(HttpStatusCode.OK); if (content != null) { var bytes = Manager.GetObjectMapper().WriteValueAsBytes(content).ToArray(); var byteContent = new ByteArrayContent(bytes); message.Content = byteContent; } return message; } public static HttpResponseMessage GenerateHttpResponseMessage(HttpStatusCode statusCode, string statusMesg, string responseJson) { var message = new HttpResponseMessage(statusCode); if (statusMesg != null) { message.ReasonPhrase = statusMesg; } if (responseJson != null) { message.Content = new StringContent(responseJson); } return message; } public static HttpResponseMessage FakeBulkDocs(HttpRequestMessage request) { var jsonMap = GetJsonMapFromRequest(request); var responseList = new List<IDictionary<string, object>>(); var docs = ((JArray)jsonMap["docs"]).ToList(); foreach (JObject doc in docs) { IDictionary<string, object> responseListItem = new Dictionary<string, object>(); responseListItem["id"] = doc["_id"]; responseListItem["rev"] = doc["_rev"]; responseList.Add(responseListItem); } var response = GenerateHttpResponseMessage(responseList); return response; } public static HttpResponseDelegate TransientErrorResponder(Int32 statusCode, string statusMesg) { HttpResponseDelegate responder = (request) => { if (statusCode == -1) { throw new IOException("Fake IO Exception from TransientErrorResponder"); } return GenerateHttpResponseMessage((HttpStatusCode)statusCode, statusMesg, null); }; return responder; } /// <summary> /// Transform Request JSON: /// { /// "doc2-1384988871931": ["1-b52e6d59-4151-4802-92fb-7e34ceff1e92"], /// "doc1-1384988871931": ["2-e776a593-6b61-44ee-b51a-0bdf205c9e13"] /// } /// /// Into Response JSON: /// { /// "doc1-1384988871931": { /// "missing": ["2-e776a593-6b61-44ee-b51a-0bdf205c9e13"] /// }, /// "doc2-1384988871931": { /// "missing": ["1-b52e6d59-4151-4802-92fb-7e34ceff1e92"] /// } /// } /// </summary> /// <returns>The revs diff.</returns> /// <param name="httpUriRequest">Http URI request.</param> public static HttpResponseMessage FakeRevsDiff(HttpRequestMessage request) { IDictionary<string, object> jsonMap = GetJsonMapFromRequest(request); IDictionary<string, object> responseMap = new Dictionary<string, object>(); foreach (string key in jsonMap.Keys) { IDictionary<string, object> missingMap = new Dictionary<string, object>(); missingMap["missing"] = jsonMap[key]; responseMap[key] = missingMap; } var response = GenerateHttpResponseMessage(responseMap); return response; } public static HttpResponseMessage FakeLocalDocumentUpdateIOException(HttpRequestMessage httpUriRequest) { throw new IOException("Throw exception on purpose for purposes of testSaveRemoteCheckpointNoResponse()"); } #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using OrchardCore.Environment.Extensions; using OrchardCore.Environment.Shell.Builders; using OrchardCore.Environment.Shell.Descriptor.Models; using OrchardCore.Environment.Shell.Events; using OrchardCore.Environment.Shell.Models; using OrchardCore.Environment.Shell.Scope; namespace OrchardCore.Environment.Shell { /// <summary> /// All <see cref="ShellContext"/> are pre-created when <see cref="InitializeAsync"/> is called on startup and where we first load /// all <see cref="ShellSettings"/> that we also need to register in the <see cref="IRunningShellTable"/> to serve incoming requests. /// For each <see cref="ShellContext"/> a service container and then a request pipeline are only built on the first matching request. /// </summary> public class ShellHost : IShellHost, IDisposable { private const int ReloadShellMaxRetriesCount = 9; private readonly IShellSettingsManager _shellSettingsManager; private readonly IShellContextFactory _shellContextFactory; private readonly IRunningShellTable _runningShellTable; private readonly IExtensionManager _extensionManager; private readonly ILogger _logger; private bool _initialized; private readonly ConcurrentDictionary<string, ShellContext> _shellContexts = new ConcurrentDictionary<string, ShellContext>(); private readonly ConcurrentDictionary<string, ShellSettings> _shellSettings = new ConcurrentDictionary<string, ShellSettings>(); private readonly ConcurrentDictionary<string, SemaphoreSlim> _shellSemaphores = new ConcurrentDictionary<string, SemaphoreSlim>(); private SemaphoreSlim _initializingSemaphore = new SemaphoreSlim(1); public ShellHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IExtensionManager extensionManager, ILogger<ShellHost> logger) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _extensionManager = extensionManager; _logger = logger; } public ShellsEvent LoadingAsync { get; set; } public ShellEvent ReleasingAsync { get; set; } public ShellEvent ReloadingAsync { get; set; } public async Task InitializeAsync() { if (!_initialized) { // Prevent concurrent requests from creating all shells multiple times await _initializingSemaphore.WaitAsync(); try { if (!_initialized) { await PreCreateAndRegisterShellsAsync(); } } finally { _initialized = true; _initializingSemaphore.Release(); } } } public async Task<ShellContext> GetOrCreateShellContextAsync(ShellSettings settings) { ShellContext shell = null; while (shell == null) { if (!_shellContexts.TryGetValue(settings.Name, out shell)) { var semaphore = _shellSemaphores.GetOrAdd(settings.Name, (name) => new SemaphoreSlim(1)); await semaphore.WaitAsync(); try { if (!_shellContexts.TryGetValue(settings.Name, out shell)) { shell = await CreateShellContextAsync(settings); AddAndRegisterShell(shell); } } finally { semaphore.Release(); } } if (shell.Released) { // If the context is released, it is removed from the dictionary so that the next iteration // or a new call on 'GetOrCreateShellContextAsync()' will recreate a new shell context. _shellContexts.TryRemove(settings.Name, out _); shell = null; } } return shell; } public async Task<ShellScope> GetScopeAsync(ShellSettings settings) { ShellScope scope = null; while (scope == null) { if (!_shellContexts.TryGetValue(settings.Name, out var shellContext)) { shellContext = await GetOrCreateShellContextAsync(settings); } // We create a scope before checking if the shell has been released. scope = shellContext.CreateScope(); // If CreateScope() returned null, the shell is released. We then remove it and // retry with the hope to get one that won't be released before we create a scope. if (scope == null) { // If the context is released, it is removed from the dictionary so that the next // iteration or a new call on 'GetScopeAsync()' will recreate a new shell context. _shellContexts.TryRemove(settings.Name, out _); } } return scope; } public async Task UpdateShellSettingsAsync(ShellSettings settings) { settings.VersionId = IdGenerator.GenerateId(); await _shellSettingsManager.SaveSettingsAsync(settings); await ReloadShellContextAsync(settings); } /// <summary> /// A feature is enabled / disabled, the tenant needs to be released so that a new shell will be built. /// </summary> public Task ChangedAsync(ShellDescriptor descriptor, ShellSettings settings) => ReleaseShellContextAsync(settings); /// <summary> /// Reloads the settings and releases the shell so that a new one will be /// built for subsequent requests, while existing requests get flushed. /// </summary> /// <param name="settings">The <see cref="ShellSettings"/> to reload.</param> /// <param name="eventSource"> /// Whether the related <see cref="ShellEvent"/> is invoked. /// </param> public async Task ReloadShellContextAsync(ShellSettings settings, bool eventSource = true) { if (ReloadingAsync != null && eventSource && settings.State != TenantState.Initializing) { foreach (var d in ReloadingAsync.GetInvocationList()) { await ((ShellEvent)d)(settings.Name); } } // A disabled shell still in use will be released by its last scope. if (!CanReleaseShell(settings)) { _runningShellTable.Remove(settings); return; } if (settings.State != TenantState.Initializing) { settings = await _shellSettingsManager.LoadSettingsAsync(settings.Name); } var count = 0; while (count < ReloadShellMaxRetriesCount) { count++; if (_shellContexts.TryRemove(settings.Name, out var context)) { _runningShellTable.Remove(settings); context.Release(); } // Add a 'PlaceHolder' allowing to retrieve the settings until the shell will be rebuilt. if (!_shellContexts.TryAdd(settings.Name, new ShellContext.PlaceHolder { Settings = settings })) { // Atomicity: We may have been the last to load the settings but unable to add the shell. continue; } _shellSettings[settings.Name] = settings; if (CanRegisterShell(settings)) { _runningShellTable.Add(settings); } if (settings.State == TenantState.Initializing) { return; } var currentVersionId = settings.VersionId; settings = await _shellSettingsManager.LoadSettingsAsync(settings.Name); // Consistency: We may have been the last to add the shell but not with the last settings. if (settings.VersionId == currentVersionId) { return; } } throw new ShellHostReloadException( $"Unable to reload the tenant '{settings.Name}' as too many concurrent processes are trying to do so."); } /// <summary> /// Releases a shell so that a new one will be built for subsequent requests. /// Note: Can be used to free up resources after a given time of inactivity. /// </summary> /// <param name="settings">The <see cref="ShellSettings"/> to reload.</param> /// <param name="eventSource"> /// Whether the related <see cref="ShellEvent"/> is invoked. /// </param> public async Task ReleaseShellContextAsync(ShellSettings settings, bool eventSource = true) { if (ReleasingAsync != null && eventSource && settings.State != TenantState.Initializing) { foreach (var d in ReleasingAsync.GetInvocationList()) { await ((ShellEvent)d)(settings.Name); } } // A disabled shell still in use will be released by its last scope. if (!CanReleaseShell(settings)) { return; } if (_shellContexts.TryRemove(settings.Name, out var context)) { context.Release(); } // Add a 'PlaceHolder' allowing to retrieve the settings until the shell will be rebuilt. if (_shellContexts.TryAdd(settings.Name, new ShellContext.PlaceHolder { Settings = settings })) { _shellSettings[settings.Name] = settings; } return; } public IEnumerable<ShellContext> ListShellContexts() => _shellContexts.Values.ToArray(); /// <summary> /// Tries to retrieve the shell context associated with the specified tenant. /// The shell may have been temporarily removed while releasing or reloading. /// </summary> public bool TryGetShellContext(string name, out ShellContext shellContext) => _shellContexts.TryGetValue(name, out shellContext); /// <summary> /// Tries to retrieve the shell settings associated with the specified tenant. /// </summary> public bool TryGetSettings(string name, out ShellSettings settings) => _shellSettings.TryGetValue(name, out settings); /// <summary> /// Retrieves all shell settings. /// </summary> public IEnumerable<ShellSettings> GetAllSettings() => _shellSettings.Values.ToArray(); private async Task PreCreateAndRegisterShellsAsync() { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Start creation of shells"); } // Load all extensions and features so that the controllers are registered in // 'ITypeFeatureProvider' and their areas defined in the application conventions. await _extensionManager.LoadFeaturesAsync(); if (LoadingAsync != null) { foreach (var d in LoadingAsync.GetInvocationList()) { await ((ShellsEvent)d)(); } } // Is there any tenant right now? var allSettings = (await _shellSettingsManager.LoadSettingsAsync()).Where(CanCreateShell).ToArray(); var defaultSettings = allSettings.FirstOrDefault(s => s.Name == ShellHelper.DefaultShellName); // The 'Default' tenant is not running, run the Setup. if (defaultSettings?.State != TenantState.Running) { var setupContext = await CreateSetupContextAsync(defaultSettings); AddAndRegisterShell(setupContext); } // Pre-create and register all tenant shells. foreach (var settings in allSettings) { AddAndRegisterShell(new ShellContext.PlaceHolder { Settings = settings }); }; if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Done pre-creating and registering shells"); } } /// <summary> /// Creates a shell context based on shell settings /// </summary> private Task<ShellContext> CreateShellContextAsync(ShellSettings settings) { if (settings.State == TenantState.Uninitialized) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for tenant '{TenantName}' setup", settings.Name); } return _shellContextFactory.CreateSetupContextAsync(settings); } else if (settings.State == TenantState.Disabled) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating disabled shell context for tenant '{TenantName}'", settings.Name); } return Task.FromResult(new ShellContext { Settings = settings }); } else if (settings.State == TenantState.Running || settings.State == TenantState.Initializing) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for tenant '{TenantName}'", settings.Name); } return _shellContextFactory.CreateShellContextAsync(settings); } else { throw new InvalidOperationException("Unexpected shell state for " + settings.Name); } } /// <summary> /// Creates a transient shell for the default tenant's setup. /// </summary> private Task<ShellContext> CreateSetupContextAsync(ShellSettings defaultSettings) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for root setup."); } if (defaultSettings == null) { // Creates a default shell settings based on the configuration. var shellSettings = _shellSettingsManager.CreateDefaultSettings(); shellSettings.Name = ShellHelper.DefaultShellName; shellSettings.State = TenantState.Uninitialized; defaultSettings = shellSettings; } return _shellContextFactory.CreateSetupContextAsync(defaultSettings); } /// <summary> /// Adds the shell and registers its settings in RunningShellTable /// </summary> private void AddAndRegisterShell(ShellContext context) { if (_shellContexts.TryAdd(context.Settings.Name, context)) { _shellSettings[context.Settings.Name] = context.Settings; if (CanRegisterShell(context)) { RegisterShellSettings(context.Settings); } } } /// <summary> /// Whether or not a shell can be activated and added to the running shells. /// </summary> private bool CanRegisterShell(ShellContext context) { if (!CanRegisterShell(context.Settings)) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Skipping shell context registration for tenant '{TenantName}'", context.Settings.Name); } return false; } return true; } /// <summary> /// Registers the shell settings in RunningShellTable /// </summary> private void RegisterShellSettings(ShellSettings settings) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Registering shell context for tenant '{TenantName}'", settings.Name); } _runningShellTable.Add(settings); } /// <summary> /// Whether or not a shell can be added to the list of available shells. /// </summary> private bool CanCreateShell(ShellSettings shellSettings) { return shellSettings.State == TenantState.Running || shellSettings.State == TenantState.Uninitialized || shellSettings.State == TenantState.Initializing || shellSettings.State == TenantState.Disabled; } /// <summary> /// Whether or not a shell can be activated and added to the running shells. /// </summary> private bool CanRegisterShell(ShellSettings shellSettings) { return shellSettings.State == TenantState.Running || shellSettings.State == TenantState.Uninitialized || shellSettings.State == TenantState.Initializing; } /// <summary> /// Whether or not a shell can be released and removed from the list, false if disabled and still in use. /// Note: A disabled shell still in use will be released by its last scope, and keeping it in the list /// prevents a consumer from creating a new one that would have a null service provider. /// </summary> private bool CanReleaseShell(ShellSettings settings) { return settings.State != TenantState.Disabled || _shellContexts.TryGetValue(settings.Name, out var value) && value.ActiveScopes == 0; } public void Dispose() { foreach (var shell in ListShellContexts()) { shell.Dispose(); } } } }
//Copyright (c) 2017 Jan Pluskal // //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.ComponentModel; using System.Linq; using AppIdent.Accord; using AppIdent.Misc; using Framework.Models; using NetfoxFrameworkAPI.Tests; using NetfoxFrameworkAPI.Tests.Properties; using NUnit.Framework; namespace AppIdent.Tests { [TestFixture] public class AppIdentServiceTests : FrameworkBaseTests { [SetUp] public void SetUp() { this.SetUpInMemory(); } public AppIdentService AppIdentService { get; set; } = new AppIdentService(); public void ProcessPcapFile(string pcapFilePath) { Console.WriteLine($"{DateTime.Now}, adding capture: {pcapFilePath}"); this.FrameworkController.ProcessCapture(this.PrepareCaptureForProcessing(pcapFilePath)); } [Test] public void CreateApplicationProtocolModels_particioning_1() { var nowDateTime = DateTime.Now; this.AppIdentTestContext = new AppIdentTestContext(nameof(this.CreateApplicationProtocolModels_particioning_1), nowDateTime) { MinFlows = 10, TrainingToVerificationRation = 1, }; this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_dnsHttpTls_cap); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext.TrainingToVerificationRation); this.AppIdentTestContext.Save(appIdentDataSource); var actual = appIdentDataSource.TrainingSet.Length + (appIdentDataSource?.VerificationSet?.Length ?? 0); Assert.AreEqual(57, actual); var context = new AppIdentTestContext(nameof(this.RandomForestsCrossValidationTest_2), nowDateTime) { MinFlows = 10, TrainingToVerificationRation = 1, }; var source = context.LoadAppIdentDataSource(); Assert.AreEqual(57, source.TrainingSet.Length + (source?.VerificationSet?.Length ?? 0)); } [Test] public void CreateApplicationProtocolModels_particioning_CreateDataSource() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.CreateApplicationProtocolModels_particioning_CreateDataSource)) { MinFlows = 30, TrainingToVerificationRation = 1, }; var pcapSource = new AppIdentPcapSource(); pcapSource.AddTesting(@"D:\pcaps\AppIdent-TestingData\captured\", "*.cap|*.pcap", true); this.AppIdentTestContext.Save(pcapSource); foreach (var pcap in pcapSource.TestingPcaps) { this.ProcessPcapFile(pcap); } var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext.TrainingToVerificationRation); this.AppIdentTestContext.Save(appIdentDataSource); } [Test] public void RandomForestsCrossValidationTest_2() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.RandomForestsCrossValidationTest_2)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, CrossValidationFolds = 10, TrainingToVerificationRation = 1, }; this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_dnsHttpTls_cap); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows,this.AppIdentTestContext.TrainingToVerificationRation); var featureSelector = this.AppIdentService.EliminateCorelatedFeatures(appIdentDataSource, this.AppIdentTestContext.FeatureSelectionTreshold, this.AppIdentTestContext); var bestParameters = this.AppIdentService.RandomForestGetBestParameters(appIdentDataSource, featureSelector, this.AppIdentTestContext); var classificationStatisticsMeter = this.AppIdentService.RandomForestCrossValidation(appIdentDataSource, this.AppIdentTestContext.FeatureSelector, bestParameters, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(); } [Test] public void RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_fast() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_fast)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, CrossValidationFolds = 10, }; this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_streamSkypeHttpTls_cap); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); var featureSelector = this.AppIdentService.EliminateCorelatedFeatures(appIdentDataSource, this.AppIdentTestContext.FeatureSelectionTreshold, this.AppIdentTestContext); var bestParameters = this.AppIdentService.RandomForestGetBestParameters(appIdentDataSource,featureSelector, this.AppIdentTestContext); this.L7Conversations.Clear(); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_streamSkypeHttpTls_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_dnsHttpTls_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_learn1_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_refSkype_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_testM1_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_testM2_cap); appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); var classificationStatisticsMeter = this.AppIdentService.RandomForestCrossValidation(appIdentDataSource, this.AppIdentTestContext.FeatureSelector, bestParameters, this.AppIdentTestContext.CrossValidationFolds, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(); } public AppIdentTestContext AppIdentTestContext { get; set; } [Test] public void RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_appIdent1() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_appIdent1)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, CrossValidationFolds = 10, }; this.ProcessPcapFile(@"D:\pcaps\AppIdent-TestingData\captured\pc_13\20-4\data0.cap"); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); var featureSelector = this.AppIdentService.EliminateCorelatedFeatures(appIdentDataSource, this.AppIdentTestContext.FeatureSelectionTreshold, this.AppIdentTestContext); var bestParameters = this.AppIdentService.RandomForestGetBestParameters(appIdentDataSource, featureSelector, this.AppIdentTestContext); this.L7Conversations.Clear(); this.ProcessPcapFile(@"D:\pcaps\AppIdent-TestingData\captured\pc_14\20-4\data0.cap"); this.ProcessPcapFile(@"D:\pcaps\AppIdent-TestingData\captured\pc_15\20-4\data0.cap"); this.ProcessPcapFile(@"D:\pcaps\AppIdent-TestingData\captured\pc_16\20-4\data0.cap"); this.ProcessPcapFile(@"D:\pcaps\AppIdent-TestingData\captured\pc_17\20-4\data0.cap"); appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); this.AppIdentTestContext.Save(appIdentDataSource); var classificationStatisticsMeter = this.AppIdentService.RandomForestCrossValidation(appIdentDataSource, this.AppIdentTestContext.FeatureSelector, bestParameters, this.AppIdentTestContext.CrossValidationFolds, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(); } [Test] public void RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_ICDF() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.RandomForestsCrossValidationTest_LearnCompletelyDifferentPcap_ICDF)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, CrossValidationFolds = 2 }; var pcapSource = new AppIdentPcapSource(); pcapSource.AddTesting(@"D:\pcaps\AppIdent-TestingData\captured\pc_13\20-4\data0.cap"); pcapSource.AddVerification(@"D:\pcaps\AppIdent-TestingData\captured\","*.cap|*.pcap",true); this.AppIdentTestContext.Save(pcapSource); foreach (var pcap in pcapSource.TestingPcaps){this.ProcessPcapFile(pcap);} var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); var featureSelector = this.AppIdentService.EliminateCorelatedFeatures(appIdentDataSource, this.AppIdentTestContext.FeatureSelectionTreshold, this.AppIdentTestContext); var bestParameters = this.AppIdentService.RandomForestGetBestParameters(appIdentDataSource, featureSelector, this.AppIdentTestContext); this.L7Conversations.Clear(); foreach (var pcap in pcapSource.VerificationPcaps) { this.ProcessPcapFile(pcap); } appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows); var classificationStatisticsMeter = this.AppIdentService.RandomForestCrossValidation(appIdentDataSource, featureSelector, bestParameters, this.AppIdentTestContext.CrossValidationFolds, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(); } [Test] public void EPI_FullFeatureSet_fast() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.EPI_FullFeatureSet_fast)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, TrainingToVerificationRation = 0.7 }; this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_streamSkypeHttpTls_cap); var featureSelector = new FeatureSelector(); this.L7Conversations.Clear(); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_streamSkypeHttpTls_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_dnsHttpTls_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_learn1_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_refSkype_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_testM1_cap); this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_testM2_cap); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext.TrainingToVerificationRation); var classificationStatisticsMeter = this.AppIdentService.EpiClasify(appIdentDataSource, featureSelector, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(classificationStatisticsMeter); this.AppIdentTestContext.Save(); } [Test] public void EPI_FullFeatureSet_ICDF() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.EPI_FullFeatureSet_ICDF)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, TrainingToVerificationRation = 0.7 }; var pcapSource = new AppIdentPcapSource(); var featureSelector = new FeatureSelector(); pcapSource.AddTesting(@"D:\pcaps\AppIdent-TestingData\captured\", "*.cap|*.pcap", true); this.AppIdentTestContext.Save(pcapSource); foreach (var pcap in pcapSource.TestingPcaps) { this.ProcessPcapFile(pcap); } var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows,this.AppIdentTestContext.TrainingToVerificationRation); var classificationStatisticsMeter = this.AppIdentService.EpiClasify(appIdentDataSource, featureSelector, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(classificationStatisticsMeter); this.AppIdentTestContext.Save(); } [Test] public void EPI_FeatureSelection_fast() { this.AppIdentTestContext = new AppIdentTestContext(nameof(this.EPI_FeatureSelection_fast)) { MinFlows = 10, FeatureSelectionTreshold = 0.5, TrainingToVerificationRation = 0.7 }; this.ProcessPcapFile(SnoopersPcaps.Default.app_identification_streamSkypeHttpTls_cap); var appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext.TrainingToVerificationRation); var featureSelector = this.AppIdentService.EliminateCorelatedFeatures(appIdentDataSource, this.AppIdentTestContext.FeatureSelectionTreshold, this.AppIdentTestContext); this.L7Conversations.Clear(); var pcapSource = new AppIdentPcapSource(); pcapSource.AddTesting(@"D:\pcaps\AppIdent-TestingData\captured\", "*.cap|*.pcap", true); this.AppIdentTestContext.Save(pcapSource); foreach (var pcap in pcapSource.TestingPcaps) { this.ProcessPcapFile(pcap); } appIdentDataSource = this.AppIdentService.CreateAppIdentDataSource(this.L7Conversations, this.AppIdentTestContext.MinFlows, this.AppIdentTestContext.TrainingToVerificationRation); var classificationStatisticsMeter = this.AppIdentService.EpiClasify(appIdentDataSource, featureSelector, this.AppIdentTestContext); classificationStatisticsMeter.PrintResults(); this.AppIdentTestContext.Save(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace DataCollection.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest(ITestOutputHelper output) { _log = output; } [Fact] public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.False(nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_AccessInstanceProperties_NoExceptions_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); if (nic.Name.StartsWith("en") || nic.Name == "lo0") { // Ethernet, WIFI and loopback should have known status. Assert.True((nic.OperationalStatus == OperationalStatus.Up) || (nic.OperationalStatus == OperationalStatus.Down)); } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); Assert.True(nic.NetworkInterfaceType == NetworkInterfaceType.Loopback); return; // Only check IPv4 loopback } } } } [Fact] [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [Fact] [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] public void BasicTest_GetIPInterfaceStatistics_Success_Bsd() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 and https://github.com/Microsoft/WSL/issues/3561 public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [Theory] [PlatformSpecific(~(TestPlatforms.OSX|TestPlatforms.FreeBSD))] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
// 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.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void Connect_ConnectTwice_NotSupported(int invalidatingAction) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction) { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); }); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); }); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); }); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); }); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { // Unlike other tests that reuse a static Socket instance, this test avoids doing so // to work around a behavior of .NET 4.7.2. See https://github.com/dotnet/corefx/issues/29481 // for more details. using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<NotSupportedException>(() => s.BeginConnect( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); } using (var s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<NotSupportedException>(() => { s.ConnectAsync( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); }); } } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); }); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); }); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); }); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); }); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); }); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("addresses", () => { GetSocket().ConnectAsync(new IPAddress[0], 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); }); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); }); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void EndConnect_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndConnect(Task.CompletedTask)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void EndSend_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSend(Task.CompletedTask)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); }); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); }); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void EndSendto_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSendTo(Task.CompletedTask)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("endPoint", () => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null)); } } }
using DevProLauncher.Config; using DevProLauncher.Helpers; using DevProLauncher.Network.Data; using DevProLauncher.Network.Enums; using DevProLauncher.Windows.Components; using DevProLauncher.Windows.Enums; using DevProLauncher.Windows.MessageBoxs; using ServiceStack.Text; using System; using System.Collections.Generic; using System.Drawing; using System.Globalization; using System.Linq; using System.Windows.Forms; namespace DevProLauncher.Windows { public sealed partial class ChatFrm : Form { private Dictionary<string, List<UserData>> m_channelData = new Dictionary<string, List<UserData>>(); private readonly Dictionary<string, PmWindowFrm> m_pmWindows = new Dictionary<string, PmWindowFrm>(); private List<UserData> m_filterUsers; public bool Autoscroll = true; public bool Joinchannel = false; private bool m_onlineMode; private bool m_friendMode; private Timer m_searchReset; private bool m_autoJoined; private LanguageInfo lang = Program.LanguageManager.Translation; public ChatFrm() { InitializeComponent(); TopLevel = false; Dock = DockStyle.Fill; Visible = true; m_searchReset = new Timer { Interval = 1000 }; m_filterUsers = new List<UserData>(); //chat packets Program.ChatServer.UserListUpdate += UpdateUserList; Program.ChatServer.UpdateUserInfo += UpdateUserInfo; Program.ChatServer.FriendList += CreateFriendList; Program.ChatServer.TeamList += CreateTeamList; Program.ChatServer.JoinChannel += ChannelAccept; Program.ChatServer.ChatMessage += WriteMessage; Program.ChatServer.DuelRequest += HandleDuelRequest; Program.ChatServer.TeamRequest += HandleTeamRequest; Program.ChatServer.DuelAccepted += StartDuelRequest; Program.ChatServer.DuelRefused += DuelRequestRefused; Program.ChatServer.ChannelUserList += UpdateOrAddChannelList; Program.ChatServer.AddUserToChannel += AddChannelUser; Program.ChatServer.RemoveUserFromChannel += RemoveChannelUser; //form events ChannelTabs.SelectedIndexChanged += UpdateChannelList; UserSearch.Enter += UserSearch_Enter; UserSearch.Leave += UserSearch_Leave; UserSearch.TextChanged += UserSearch_TextChanged; UserListTabs.SelectedIndexChanged += UserSearch_Reset; ChatInput.KeyPress += ChatInput_KeyPress; ChannelList.DoubleClick += List_DoubleClick; UserList.DoubleClick += List_DoubleClick; m_searchReset.Tick += SearchTick; ApplyOptionEvents(); ChannelList.MouseUp += UserList_MouseUp; UserList.MouseUp += UserList_MouseUp; IgnoreList.MouseUp += IgnoreList_MouseUp; //custom form drawing ChannelList.DrawItem += UserList_DrawItem; UserList.DrawItem += UserList_DrawItem; ChatHelper.LoadChatTags(); LoadIgnoreList(); ApplyTranslations(); ApplyChatSettings(); WriteSystemMessage(lang.chatMsg1); WriteSystemMessage(lang.chatMsg2); } public void LoadDefaultChannel() { if (!string.IsNullOrEmpty(Program.Config.DefaultChannel) && !m_autoJoined) { ChatWindow channel = GetChatWindow(Program.Config.DefaultChannel); if (channel == null) { Program.ChatServer.SendPacket(DevServerPackets.JoinChannel, Program.Config.DefaultChannel); m_autoJoined = true; } } } private void SearchTick(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new Action<object, EventArgs>(SearchTick), sender, e); return; } if (userSearchBtn.Text == "1") { userSearchBtn.Enabled = true; adminSearchBtn.Enabled = true; teamSearchBtn.Enabled = true; friendSearchBtn.Enabled = true; userSearchBtn.Text = lang.chatBtnUser; adminSearchBtn.Text = lang.chatBtnAdmin; teamSearchBtn.Text = lang.chatBtnTeam; friendSearchBtn.Text = lang.chatBtnFriend; m_searchReset.Enabled = false; } else { int value = Int32.Parse(userSearchBtn.Text); userSearchBtn.Text = (value - 1).ToString(); adminSearchBtn.Text = (value - 1).ToString(); teamSearchBtn.Text = (value - 1).ToString(); friendSearchBtn.Text = (value - 1).ToString(); } } private void EnableSearchReset() { UserListTab.Focus(); userSearchBtn.Enabled = false; adminSearchBtn.Enabled = false; teamSearchBtn.Enabled = false; friendSearchBtn.Enabled = false; userSearchBtn.Text = "5"; adminSearchBtn.Text = "5"; teamSearchBtn.Text = "5"; friendSearchBtn.Text = "5"; m_searchReset.Enabled = true; } private void ApplyOptionEvents() { foreach (var checkBox in tableLayoutPanel14.Controls.OfType<CheckBox>()) { checkBox.CheckStateChanged += Option_CheckStateChanged; } foreach (FontFamily fontFamily in FontFamily.Families.Where(fontFamily => fontFamily.IsStyleAvailable(FontStyle.Regular))) { FontList.Items.Add(fontFamily.Name); } FontList.SelectedIndexChanged += FontSettings_Changed; FontSize.ValueChanged += FontSettings_Changed; } public void ApplyChatSettings() { ChatInput.BackColor = Program.Config.ChatBGColor.ToColor(); ChatInput.ForeColor = Program.Config.NormalTextColor.ToColor(); UserSearch.BackColor = Program.Config.ChatBGColor.ToColor(); UserList.BackColor = Program.Config.ChatBGColor.ToColor(); ChannelList.BackColor = Program.Config.ChatBGColor.ToColor(); IgnoreList.BackColor = Program.Config.ChatBGColor.ToColor(); IgnoreList.ForeColor = Program.Config.NormalTextColor.ToColor(); BackgroundColorBtn.BackColor = Program.Config.ChatBGColor.ToColor(); NormalTextColorBtn.BackColor = Program.Config.NormalTextColor.ToColor(); BotColorBtn.BackColor = Program.Config.BotColor.ToColor(); Level4ColorBtn.BackColor = Program.Config.Level4Color.ToColor(); Level3ColorBtn.BackColor = Program.Config.Level3Color.ToColor(); Level2ColorBtn.BackColor = Program.Config.Level2Color.ToColor(); Level1ColorBtn.BackColor = Program.Config.Level1Color.ToColor(); NormalUserColorBtn.BackColor = Program.Config.Level0Color.ToColor(); ServerColorBtn.BackColor = Program.Config.ServerMsgColor.ToColor(); MeColorBtn.BackColor = Program.Config.MeMsgColor.ToColor(); JoinColorBtn.BackColor = Program.Config.JoinColor.ToColor(); LeaveColorBtn.BackColor = Program.Config.LeaveColor.ToColor(); SystemColorBtn.BackColor = Program.Config.SystemColor.ToColor(); HideJoinLeavechk.Checked = Program.Config.HideJoinLeave; Colorblindchk.Checked = Program.Config.ColorBlindMode; Timestampchk.Checked = Program.Config.ShowTimeStamp; DuelRequestchk.Checked = Program.Config.RefuseDuelRequests; pmwindowchk.Checked = Program.Config.PmWindows; usernamecolorchk.Checked = Program.Config.UsernameColors; refuseteamchk.Checked = Program.Config.RefuseTeamInvites; pmnotificationchk.Checked = Program.Config.PmNotifications; if (!string.IsNullOrEmpty(Program.Config.ChatFont)) { if (FontList.Items.Contains(Program.Config.ChatFont)) { FontList.SelectedItem = Program.Config.ChatFont; } } FontSize.Value = Program.Config.ChatSize; } public void ApplyTranslations() { //options groupBox7.Text = lang.chatoptionsGb2; groupBox5.Text = lang.chatoptionsGb3; HideJoinLeavechk.Text = lang.chatoptionsLblHideJoinLeave; pmwindowchk.Text = lang.chatoptionsLblPmWindows; Colorblindchk.Text = lang.chatoptionsLblColorBlindMode; usernamecolorchk.Text = lang.chatoptionsLblUserColors; refuseteamchk.Text = lang.chatoptionsLblRefuseTeamInvites; Timestampchk.Text = lang.chatoptionsLblShowTimeStamp; DuelRequestchk.Text = lang.chatoptionsLblRefuseDuelRequests; pmnotificationchk.Text = lang.chatoptionsLblPmWindowsNotification; groupBox1.Text = lang.chatoptionsFontTitle; label1.Text = lang.chatoptionsFontLbl; label2.Text = lang.chatoptionsFontSize; label13.Text = lang.chatoptionsLblChatBackground; label12.Text = lang.chatoptionsLblNormalText; label11.Text = lang.chatoptionsLblLevel98; //label10.Text = lang.chatoptionsLblLevel2; label9.Text = lang.chatoptionsLblLevel1; label4.Text = lang.chatoptionsLblNormalUser; label7.Text = lang.chatoptionsLblServerMessages; label8.Text = lang.chatoptionsLblMeMessage; label14.Text = lang.chatoptionsLblJoin; label15.Text = lang.chatoptionsLblLeave; label16.Text = lang.chatoptionsLblSystem; userSearchBtn.Text = lang.chatBtnUser; adminSearchBtn.Text = lang.chatBtnAdmin; teamSearchBtn.Text = lang.chatBtnTeam; friendSearchBtn.Text = lang.chatBtnFriend; ChannelListBtn.Text = lang.chatBtnChannel; LeaveBtn.Text = lang.chatBtnLeave; UserTab.Text = lang.chatUserTab; IgnoreTab.Text = lang.chatIgnoreTab; OptionsTab.Text = lang.chatOptionTab; ChannelTab.Text = lang.chatChannelTab; UserListTab.Text = lang.chatUserListTab; } public void LoadIgnoreList() { string[] users = Program.Config.IgnoreList.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (string user in users) { IgnoreList.Items.Add(user.ToLower()); } } private void JoinChannel(string channel) { Program.ChatServer.SendPacket(DevServerPackets.JoinChannel, channel); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo, "System", "Join request for " + channel + " has been sent.")); } private void LeaveChannel(string channel) { Program.ChatServer.SendPacket(DevServerPackets.LeaveChannel, channel); if (GetChatWindow(channel) != null) { ChannelTabs.TabPages.Remove(GetChatWindow(channel)); Program.Config.ChatChannels.Remove(channel); Program.SaveConfig(Program.ConfigurationFilename, Program.Config); } } private void ChannelAccept(string channel) { if (InvokeRequired) { Invoke(new Action<string>(ChannelAccept), channel); return; } if (GetChatWindow(channel) == null) { ChannelTabs.TabPages.Add(new ChatWindow(channel, false)); ChannelTabs.SelectedTab = GetChatWindow(channel); if (!Program.Config.ChatChannels.Contains(channel)) { Program.Config.ChatChannels.Add(channel); Program.SaveConfig(Program.ConfigurationFilename, Program.Config); } } if (!string.IsNullOrEmpty(Program.UserInfo.team) && GetChatWindow(MessageType.Team.ToString()) == null) { ChannelTabs.TabPages.Add(new ChatWindow(MessageType.Team.ToString(), false)); } WriteMessage(new ChatMessage(MessageType.Server, CommandType.None, Program.UserInfo, "Server", "Join request for " + channel + " accepted.")); if (!Joinchannel) { Joinchannel = true; if (GetChatWindow(MessageType.System.ToString()) != null) { ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.System.ToString())); } } } public void WriteMessage(ChatMessage message) { if (InvokeRequired) { Invoke(new Action<ChatMessage>(WriteMessage), message); return; } if (message.from != null && IgnoreUser(message.from)) { return; } ChatWindow window; if ((MessageType)message.type == MessageType.Server || (MessageType)message.type == MessageType.System) { window = (ChatWindow)ChannelTabs.SelectedTab; if (window == null) { window = new ChatWindow(((MessageType)message.type).ToString(), true) { IsSystemtab = true }; ChannelTabs.TabPages.Add(window); window.WriteMessage(message, Autoscroll); } else window.WriteMessage(message, Autoscroll); } else if ((MessageType)message.type == MessageType.Join || (MessageType)message.type == MessageType.Leave || message.channel == null) { window = GetChatWindow(message.channel) ?? (ChatWindow)ChannelTabs.SelectedTab; if (window == null) { window = new ChatWindow(message.type.ToString(CultureInfo.InvariantCulture), true) { IsSystemtab = true }; ChannelTabs.TabPages.Add(window); window.WriteMessage(message, Autoscroll); } else window.WriteMessage(message, Autoscroll); } else if ((MessageType)message.type == MessageType.PrivateMessage && Program.Config.PmWindows) { if (m_pmWindows.ContainsKey(message.channel)) { m_pmWindows[message.channel].WriteMessage(message); } else { m_pmWindows.Add(message.channel, new PmWindowFrm(message.channel, true)); m_pmWindows[message.channel].WriteMessage(message); m_pmWindows[message.channel].Show(); m_pmWindows[message.channel].FormClosed += Chat_frm_FormClosed; } } else if ((MessageType)message.type == MessageType.Team) { window = GetChatWindow(((MessageType)message.type).ToString()); if (window == null) { window = new ChatWindow(((MessageType)message.type).ToString(), (MessageType)message.type == MessageType.PrivateMessage); ChannelTabs.TabPages.Add(window); window.WriteMessage(message, Autoscroll); } else window.WriteMessage(message, Autoscroll); } else { window = GetChatWindow(message.channel); if (window == null) { window = new ChatWindow(message.channel, (MessageType)message.type == MessageType.PrivateMessage); ChannelTabs.TabPages.Add(window); } window.WriteMessage(message, Autoscroll); } } public bool IgnoreUser(UserData user) { return IgnoreList.Items.Contains(user.username.ToLower()) && user.rank < 1; } public void WriteSystemMessage(string message) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, message)); } private ChatWindow GetChatWindow(string name) { return ChannelTabs.TabPages.Cast<ChatWindow>().FirstOrDefault(x => x.Name == name); } private void Chat_frm_FormClosed(object sender, EventArgs e) { m_pmWindows.Remove(((PmWindowFrm)sender).Name); } private void UserSearch_Enter(object sender, EventArgs e) { if (UserSearch.Text == "Search") { UserSearch.ForeColor = Program.Config.NormalTextColor.ToColor(); UserSearch.Text = ""; } } private void UserSearch_Leave(object sender, EventArgs e) { if (UserSearch.Text == "") { UserSearch.ForeColor = SystemColors.WindowFrame; UserSearch.Text = "Search"; } } private void UserSearch_Reset(object sender, EventArgs e) { UserSearch.ForeColor = SystemColors.WindowFrame; UserSearch.Text = "Search"; } private void UserSearch_TextChanged(object sender, EventArgs e) { if (UserListTabs.SelectedTab.Name == ChannelTab.Name) { ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab; if (window != null) { if (m_channelData.ContainsKey(window.Name)) { IEnumerable<UserData> users = m_channelData[window.Name]; if (!string.IsNullOrEmpty(UserSearch.Text) && UserSearch.ForeColor != SystemColors.WindowFrame) { users = users.Where(user => user.username.ToLower().Contains(UserSearch.Text.ToLower())); } ChannelList.Items.Clear(); ChannelList.Items.AddRange(users.ToArray<object>()); } } } else { if (!string.IsNullOrEmpty(UserSearch.Text) && UserSearch.ForeColor != SystemColors.WindowFrame) { UserList.Items.Clear(); foreach (UserData user in m_filterUsers) { if (user.username.ToLower().Contains(UserSearch.Text.ToLower())) UserList.Items.Add(user); } } else { UserList.Items.Clear(); UserList.Items.AddRange(m_filterUsers.ToArray()); } } } private void UpdateUserInfo(UserData user) { Program.UserInfo = user; Program.MainForm.UpdateUsername(); if (!string.IsNullOrEmpty(Program.UserInfo.team)) LoadTeamWindow(); } private void UpdateChannelList(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new Action<object, EventArgs>(UpdateChannelList), sender, e); return; } ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab; if (window != null) { if (m_channelData.ContainsKey(window.Name)) { List<UserData> users = m_channelData[window.Name]; ChannelList.Items.Clear(); ChannelList.Items.AddRange(users.ToArray()); } } else { ChannelList.Items.Clear(); } } private void UpdateOrAddChannelList(ChannelUsers users) { if (m_channelData.ContainsKey(users.Name)) m_channelData[users.Name] = new List<UserData>(users.Users); else m_channelData.Add(users.Name, new List<UserData>(users.Users)); UpdateChannelList(this, EventArgs.Empty); } private void AddOrRemoveChannelUser(UserData channelUser, bool remove) { if (InvokeRequired) { Invoke(new Action<UserData, bool>(AddOrRemoveChannelUser), channelUser, remove); return; } UserData toRemove = null; foreach (UserData user in ChannelList.Items) { if (user.username == channelUser.username) toRemove = user; } if (toRemove != null) ChannelList.Items.Remove(toRemove); if (!remove) { ChannelList.Items.Add(channelUser); } } private void AddChannelUser(ChannelUsers user) { if (InvokeRequired) { Invoke(new Action<ChannelUsers>(AddChannelUser), user); return; } if (m_channelData.ContainsKey(user.Name)) { UserData founduser = null; foreach (UserData channeluser in m_channelData[user.Name]) { if (channeluser.username == user.Users[0].username) founduser = channeluser; } if (founduser == null) m_channelData[user.Name].Add(user.Users[0]); else { m_channelData[user.Name].Remove(founduser); m_channelData[user.Name].Add(user.Users[0]); } } ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab; if (window != null) { if (user.Name == window.Name) AddOrRemoveChannelUser(user.Users[0], false); } } private void RemoveChannelUser(ChannelUsers user) { if (InvokeRequired) { Invoke(new Action<ChannelUsers>(RemoveChannelUser), user); return; } if (m_channelData.ContainsKey(user.Name)) { UserData founduser = null; foreach (UserData channeluser in m_channelData[user.Name]) { if (channeluser.username == user.Users[0].username) founduser = channeluser; } if (founduser != null) m_channelData[user.Name].Remove(founduser); } ChatWindow window = (ChatWindow)ChannelTabs.SelectedTab; if (window != null) { if (user.Name == window.Name) AddOrRemoveChannelUser(user.Users[0], true); } } private void UpdateUserList(UserData[] userlist) { if (InvokeRequired) { Invoke(new Action<UserData[]>(UpdateUserList), (object)userlist); return; } m_onlineMode = false; m_friendMode = false; UserList.Items.Clear(); UserList.Items.AddRange(userlist); m_filterUsers.Clear(); m_filterUsers.AddRange(userlist); } private void LoadTeamWindow() { if (InvokeRequired) { Invoke(new Action(LoadTeamWindow)); return; } if (GetChatWindow(MessageType.Team.ToString()) == null) { ChannelTabs.TabPages.Add(new ChatWindow(MessageType.Team.ToString(), false)); } } public void CreateFriendList(UserData[] friends) { if (InvokeRequired) { Invoke(new Action<UserData[]>(CreateFriendList), (object)friends); return; } m_friendMode = true; m_onlineMode = true; UserList.Items.Clear(); UserList.Items.AddRange(friends); m_filterUsers.Clear(); m_filterUsers.AddRange(friends); } public void CreateTeamList(UserData[] users) { if (InvokeRequired) { Invoke(new Action<UserData[]>(CreateTeamList), (object)users); return; } m_onlineMode = true; UserList.Items.Clear(); UserList.Items.AddRange(users); m_filterUsers.Clear(); m_filterUsers.AddRange(users); } private void UserList_DrawItem(object sender, DrawItemEventArgs e) { ListBox list = (ListBox)sender; e.DrawBackground(); bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected); int index = e.Index; if (index == -1) return; if (index < 0 && index >= list.Items.Count) { e.DrawFocusRectangle(); return; } UserData user = (UserData)list.Items[index]; Graphics g = e.Graphics; g.FillRectangle((selected) ? (Program.Config.ColorBlindMode ? new SolidBrush(Color.Black) : new SolidBrush(Color.Blue)) : new SolidBrush(Program.Config.ChatBGColor.ToColor()), e.Bounds); if (!m_onlineMode) { if (user.usertag != "" || user.rank > 0 && user.rank < 99) { // Print text g.DrawString("[", e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(Program.Config.NormalTextColor.ToColor())), list.GetItemRectangle(index).Location); string title; title = user.usertag; //switch (user.rank) //{ // case 1: // title = "Helper"; // break; // case 2: // title = "TD"; // break; // case 3: // title = "Mod"; // break; // case 4: // title = "SMod"; // break; // case 98: // title = "Bot"; // break; // /* // case 99: // title = "Dev"; // break; // //*/ // default: // title = user.usertag; // break; //} g.DrawString(title, e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : ChatMessage.GetUserColor(user.rank)), new Point( list.GetItemRectangle(index).Location.X + (int)g.MeasureString("[", e.Font).Width - 1, list.GetItemRectangle(index).Location.Y)); g.DrawString("]", e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(Program.Config.NormalTextColor.ToColor())), new Point( list.GetItemRectangle(index).Location.X + (int)g.MeasureString("[" + title, e.Font).Width, list.GetItemRectangle(index).Location.Y)); if (user.getUserColor().ToArgb() == Color.Black.ToArgb()) { g.DrawString(user.username, e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(Program.Config.NormalTextColor.ToColor())), new Point( list.GetItemRectangle(index).Location.X + (int)g.MeasureString("[" + title + "]", e.Font).Width, list.GetItemRectangle(index).Location.Y)); } else { g.DrawString(user.username, e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(user.getUserColor())), new Point( list.GetItemRectangle(index).Location.X + (int)g.MeasureString("[" + title + "]", e.Font).Width, list.GetItemRectangle(index).Location.Y)); } } else { if (user.getUserColor().ToArgb() == Color.Black.ToArgb()) { // Print text g.DrawString(user.username, e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(Program.Config.NormalTextColor.ToColor())), list.GetItemRectangle(index).Location); } else { // Print text g.DrawString(user.username, e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : new SolidBrush(user.getUserColor())), list.GetItemRectangle(index).Location); } } } else { //// Print text g.DrawString((Program.Config.ColorBlindMode ? (user.Online ? user.username + " (Online)" : user.username + " (Offline)") : user.username), e.Font, (selected) ? Brushes.White : (Program.Config.ColorBlindMode ? Brushes.Black : (user.Online ? Brushes.Green : Brushes.Red)), list.GetItemRectangle(index).Location); } e.DrawFocusRectangle(); } private void ApplyNewColor(object sender, EventArgs e) { var button = (Button)sender; var selectcolor = new ColorDialog { Color = button.BackColor, AllowFullOpen = true }; if (selectcolor.ShowDialog() == DialogResult.OK) { switch (button.Name) { case "BackgroundColorBtn": Program.Config.ChatBGColor = new SerializableColor(selectcolor.Color); break; case "SystemColorBtn": Program.Config.SystemColor = new SerializableColor(selectcolor.Color); break; case "LeaveColorBtn": Program.Config.LeaveColor = new SerializableColor(selectcolor.Color); break; case "JoinColorBtn": Program.Config.JoinColor = new SerializableColor(selectcolor.Color); break; case "MeColorBtn": Program.Config.MeMsgColor = new SerializableColor(selectcolor.Color); break; case "ServerColorBtn": Program.Config.ServerMsgColor = new SerializableColor(selectcolor.Color); break; case "NormalUserColorBtn": Program.Config.Level0Color = new SerializableColor(selectcolor.Color); break; case "Level1ColorBtn": Program.Config.Level1Color = new SerializableColor(selectcolor.Color); break; case "Level2ColorBtn": Program.Config.Level2Color = new SerializableColor(selectcolor.Color); break; case "Level3ColorBtn": Program.Config.Level3Color = new SerializableColor(selectcolor.Color); break; case "Level4ColorBtn": Program.Config.Level4Color = new SerializableColor(selectcolor.Color); break; case "BotColorBtn": Program.Config.BotColor = new SerializableColor(selectcolor.Color); break; case "NormalTextColorBtn": Program.Config.NormalTextColor = new SerializableColor(selectcolor.Color); break; } button.BackColor = selectcolor.Color; Program.SaveConfig(Program.ConfigurationFilename, Program.Config); ApplyChatSettings(); } } private bool HandleCommand(string part, ChatWindow selectedTab) { var cmd = part.Substring(1).ToLower(); switch (cmd) { case "me": if (selectedTab == null) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "No channel Selected.")); return false; } var isTeam = selectedTab.Name == MessageType.Team.ToString(); Program.ChatServer.SendMessage(isTeam ? MessageType.Team : MessageType.Message, CommandType.Me, selectedTab.Name, ChatInput.Text.Substring(part.Length).Trim()); break; case "join": JoinChannel(ChatInput.Text.Substring(part.Length).Trim()); break; case "leave": if (selectedTab == null) { return false; } if (selectedTab.IsPrivate) { ChannelTabs.TabPages.Remove(selectedTab); } else { LeaveChannel(selectedTab.Name); } break; case "ping": Program.ChatServer.SendPacket(DevServerPackets.Ping); break; case "autoscroll": Autoscroll = !Autoscroll; WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, (Autoscroll ? "AutoScroll Enabled." : "AutoScroll Disabled."))); break; case "help": WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Basic Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/me - Displays Username, and then your Message")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/join - Joins another channel")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/leave - Leaves the channel you're currently in")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/autoscroll - Enable/Disable autoscroll")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ping - Ping the server")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/help - Displays the list you're reading now")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/uptime - Displays how long the server has been online")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/stats - Shows how many users are online, dueling, and how many duels")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/mute username hours - (Channel Owners/Admins) Prevents a user from sending any messages in a certain channel for a certain amount of hours.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unmute username - (Channel Owners/Admins) Allows a muted user to send messages again")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/setmotd message - (Channel Owners/Admins) Sets a message of the day that is sent to users when they join the channel.")); if (Program.UserInfo.rank == 1) WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, " -- Level 1 users are classed as helpers and don't need any extra commands")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/msg - Sends a server message")); if (Program.UserInfo.rank > 1) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- TD Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/kick username reason - Kicks a user")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/msg - Sends a server message")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/smsg - Sends a launcher message which is displayed on the bottom of the launcher")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getaccounts username - Gets a list of accounts for the the inputted username")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/cmute roomname - Mutes a room so that only admins can speak")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/cunmute roomname - Unmutes a room that was muted.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/roomowner roomname - Gets the creator of a channel")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/killroom roomname - forces a chat channel to close")); } if (Program.UserInfo.rank > 2) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Mod Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getuid username - Gets the UID of a username")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gmute username hours - Globally mutes a user for X hours. ( if hours is empty, it's 24hours )")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gunmute username - Unmutes a user that was muted globally")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/gumuteall - Clears all GMutes")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/info username - Gives info of an user.")); } if (Program.UserInfo.rank > 3) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- SMod Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/shutdown [false]/[forced] servername - instructs the duel server to shutdown. If 'forced' is added: Does not wait for games to finish. Do not use false if you use Forced.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/restart [false]/[forced] servername - instructs the duel server to restart. If 'forced' is added: Does not wait for games to finish. Do not use false if you use Forced.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/kill [forced]- Kills all crashed cores. If 'forced' is added: Kills all cores (including running games).")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ban username time reason - Bans a user, time format has to be in hours (max 730 hours), also you must give a reason.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/banusername username - Bans a user's username")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getservers - Gives duel servers listed")); } if (Program.UserInfo.rank == 99) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team Leader Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ban username time reason - Bans a user, time format has to be in hours, also you must give a reason.")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unban username - Unbans a user")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/ip username - Gets a users IP")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/banip ip - Bans an IP")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/unbanip ip - Unbans IP")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/getbanlist - Gets ban list")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/op username level - Sets a users level")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/setmps number - Changes the messages per second")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/addpoints username amount - Adds DevPoints to the given username")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/removepoints username amount - Removes DevPoints to the given username")); } if (Program.UserInfo.teamRank >= 0 && Program.UserInfo.team != string.Empty) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/leaveteam - leaves the team")); } if (Program.UserInfo.teamRank >= 1) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team User Level 1 Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamadd username - adds a user to the team")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamremove username - removes a user from the team")); } if (Program.UserInfo.teamRank == 99) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "-- Team User Level 99 Commands --")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamdisband - disbands the team")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamop username level - promotes a user in the team")); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "/teamchangeleader username - changes the leader of a team")); } break; case "teamdisband": if (MessageBox.Show("Are you sure?", "Confirm team disband", MessageBoxButtons.YesNo) == DialogResult.Yes) { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() })); } break; case "setmotd": Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text })); break; case "mute": case "unmute": Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text })); break; case "info": Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() + "|" + ChannelTabs.SelectedTab.Text })); break; default: Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = cmd.ToUpper(), Data = ChatInput.Text.Substring(part.Length).Trim() })); break; } return true; } private void ChatInput_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar != 13 || string.IsNullOrWhiteSpace(ChatInput.Text)) { return; } string[] parts = ChatInput.Text.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var selectedTab = (ChatWindow)ChannelTabs.SelectedTab; if (parts[0].StartsWith("/")) { if (!HandleCommand(parts[0], selectedTab)) { return; } } else { if (selectedTab == null) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "No channel Selected.")); return; } if (selectedTab.IsSystemtab) { ChatInput.Clear(); return; } if (selectedTab.IsPrivate) { WriteMessage(new ChatMessage(MessageType.PrivateMessage, CommandType.None, Program.UserInfo, selectedTab.Name, ChatInput.Text)); Program.ChatServer.SendMessage(MessageType.PrivateMessage, CommandType.None, selectedTab.Name, ChatInput.Text); } else { var isTeam = selectedTab.Name == MessageType.Team.ToString(); Program.ChatServer.SendMessage(isTeam ? MessageType.Team : MessageType.Message, CommandType.None, selectedTab.Name, ChatInput.Text); } } ChatInput.Clear(); e.Handled = true; } private void Option_CheckStateChanged(object sender, EventArgs e) { var check = (CheckBox)sender; switch (check.Name) { case "Colorblindchk": Program.Config.ColorBlindMode = check.Checked; break; case "Timestampchk": Program.Config.ShowTimeStamp = check.Checked; break; case "DuelRequestchk": Program.Config.RefuseDuelRequests = check.Checked; break; case "HideJoinLeavechk": Program.Config.HideJoinLeave = check.Checked; break; case "usernamecolorchk": Program.Config.UsernameColors = usernamecolorchk.Checked; break; case "refuseteamchk": Program.Config.RefuseTeamInvites = refuseteamchk.Checked; break; case "pmwindowchk": Program.Config.PmWindows = check.Checked; if (Program.Config.PmWindows) { ChannelTabs.TabPages .Cast<ChatWindow>() .Where(x => x.IsPrivate) .ToList() .ForEach(window => ChannelTabs.TabPages.Remove(window)); } else { m_pmWindows.Values.ToList().ForEach(x => x.Close()); } break; case "pmnotificationchk": Program.Config.PmNotifications = pmnotificationchk.Checked; break; } Program.SaveConfig(Program.ConfigurationFilename, Program.Config); } private void UserList_MouseUp(object sender, MouseEventArgs e) { ListBox list = (ListBox)sender; if (e.Button == MouseButtons.Right) { int index = list.IndexFromPoint(e.Location); if (index == -1) { return; } list.SelectedIndex = index; if (list.SelectedItem == null) { return; } ContextMenuStrip mnu = new ContextMenuStrip(); ToolStripMenuItem mnuprofile = new ToolStripMenuItem(Program.LanguageManager.Translation.chatViewProfile); ToolStripMenuItem mnuduel = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRequestDuel); ToolStripMenuItem mnufriend = new ToolStripMenuItem(Program.LanguageManager.Translation.chatAddFriend); ToolStripMenuItem mnuignore = new ToolStripMenuItem(Program.LanguageManager.Translation.chatIgnoreUser); ToolStripMenuItem mnukick = new ToolStripMenuItem(Program.LanguageManager.Translation.chatKick); ToolStripMenuItem mnmute = new ToolStripMenuItem(Program.LanguageManager.Translation.chatMute); ToolStripMenuItem mnuban = new ToolStripMenuItem(Program.LanguageManager.Translation.chatBan); ToolStripMenuItem mnuremovefriend = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRemoveFriend); ToolStripMenuItem mnuremoveteam = new ToolStripMenuItem(Program.LanguageManager.Translation.chatTeamRemove); ToolStripMenuItem mnuspectateuser = new ToolStripMenuItem(Program.LanguageManager.Translation.chatSpectate); mnukick.Click += KickUser; mnmute.Click += MuteUser; mnuban.Click += BanUser; mnuprofile.Click += ViewProfile; mnuduel.Click += RequestDuel; mnufriend.Click += AddFriend; mnuignore.Click += IgnoreUser; mnuremovefriend.Click += RemoveFriend; mnuremoveteam.Click += RemoveFromTeam; mnuspectateuser.Click += SpectateUser; if (!m_onlineMode) { mnu.Items.AddRange(new ToolStripItem[] { mnuprofile, mnuduel, mnuspectateuser, mnufriend, mnuignore }); if (Program.UserInfo.rank > 1) mnu.Items.Add(mnukick); if (Program.UserInfo.rank > 3) mnu.Items.Add(mnuban); if (Program.UserInfo.rank > 1) mnu.Items.Add(mnmute); } else { UserData user = (UserData)list.SelectedItem; mnu.Items.Add(mnuprofile); if (user.Online) { mnu.Items.AddRange(new ToolStripItem[] { mnuduel, mnuspectateuser }); } if (m_friendMode) mnu.Items.Add(mnuremovefriend); else { if (Program.UserInfo.teamRank > 0) mnu.Items.Add(mnuremoveteam); } } mnu.Show(list, e.Location); } } private void BanUser(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; /* if (list.SelectedItem != null && MessageBox.Show("Are you sure you want to ban " + ((UserData)list.SelectedItem).username, "Ban User", MessageBoxButtons.YesNo) == DialogResult.Yes) { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString( new PacketCommand { Command = "BAN", Data = ((UserData)list.SelectedItem).username })); } */ var input = new BanFrm(Program.LanguageManager.Translation.banTitle, Program.LanguageManager.Translation.banMessageLbl, Program.LanguageManager.Translation.banTimeLbl, Program.LanguageManager.Translation.banReasonLbl, Program.LanguageManager.Translation.banConfirm, Program.LanguageManager.Translation.banCancel); if ((!(list.SelectedItems.Count > 1))) { if ((input.ShowDialog() == DialogResult.OK)) { try { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString( new PacketCommand { Command = "BAN", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text + " " + input.inputBox2.Text })); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } private void KickUser(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; if (list.SelectedItem == null) { return; } /* Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString( new PacketCommand { Command = "KICK", Data = ((UserData)list.SelectedItem).username })); */ var input = new BanFrm(Program.LanguageManager.Translation.kickTitle, Program.LanguageManager.Translation.kickMessageLbl, Program.LanguageManager.Translation.kickReasonLbl, "", Program.LanguageManager.Translation.kickConfirm, Program.LanguageManager.Translation.kickCancel); input.inputBox2.Visible = false; if ((!(list.SelectedItems.Count > 1))) { if ((input.ShowDialog() == DialogResult.OK)) { try { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString( new PacketCommand { Command = "KICK", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text })); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } private void MuteUser(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; var input = new BanFrm(Program.LanguageManager.Translation.muteTitle, Program.LanguageManager.Translation.muteMessageLbl, Program.LanguageManager.Translation.muteTimeLbl, Program.LanguageManager.Translation.muteReasonLbl, Program.LanguageManager.Translation.muteConfirm, Program.LanguageManager.Translation.muteCancel); if ((!(list.SelectedItems.Count > 1))) { if ((input.ShowDialog() == DialogResult.OK)) { try { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString( new PacketCommand { Command = "MUTE", Data = ((UserData)list.SelectedItem).username + " " + input.inputBox1.Text + " " + input.inputBox2.Text + "|" + ChannelTabs.SelectedTab.Text })); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } private void SpectateUser(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; if (list.SelectedItem == null) return; Program.ChatServer.SendPacket(DevServerPackets.SpectateUser, ((UserData)list.SelectedItem).username); } private void AddFriend(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; if (list.SelectedItem == null) return; if (((UserData)list.SelectedItem).username == Program.UserInfo.username) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot be your own friend.")); return; } WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " has been added to your friend list.")); Program.ChatServer.SendPacket(DevServerPackets.AddFriend, ((UserData)list.SelectedItem).username); } private void IgnoreUser(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; if (((UserData)list.SelectedItem).username == Program.UserInfo.username) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot ignore yourself.")); return; } if (IgnoreList.Items.Contains(((UserData)list.SelectedItem).username.ToLower())) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " is already on your ignore list.")); return; } IgnoreList.Items.Add(((UserData)list.SelectedItem).username.ToLower()); SaveIgnoreList(); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)list.SelectedItem).username + " has been added to your ignore list.")); } private void RemoveFromTeam(object sender, EventArgs e) { if (UserList.SelectedIndex == -1) { return; } if (MessageBox.Show("Are you sure?", "Remove User", MessageBoxButtons.YesNo) == DialogResult.Yes) { Program.ChatServer.SendPacket(DevServerPackets.ChatCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = "TEAMREMOVE", Data = ((UserData)UserList.SelectedItem).username })); } } private void RemoveFriend(object sender, EventArgs e) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, ((UserData)UserList.SelectedItem).username + " has been removed from your friendlist.")); Program.ChatServer.SendPacket(DevServerPackets.RemoveFriend, ((UserData)UserList.SelectedItem).username); UserList.Items.Remove(UserList.SelectedItem); } private void ViewProfile(object sender, EventArgs e) { ListBox list = (UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList); if (list.SelectedItem == null) return; var profile = new ProfileFrm(list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username); profile.ShowDialog(); } private void RequestDuel(object sender, EventArgs e) { ListBox list = (UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList); if (list.SelectedItem == null) { return; } if ((list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username) == Program.UserInfo.username) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You cannot duel request your self.")); } else { var form = new Host(); ServerInfo server = Program.MainForm.GameWindow.GetServer(false); if (server == null) { MessageBox.Show("No Server Available."); return; } Program.ChatServer.SendPacket(DevServerPackets.RequestDuel, JsonSerializer.SerializeToString( new DuelRequest { username = list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username, duelformatstring = form.GenerateURI(false), server = server.serverName })); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "Duel request sent to " + (list.SelectedItem is string ? list.SelectedItem.ToString() : ((UserData)list.SelectedItem).username) + ".")); } } private void HandleDuelRequest(DuelRequest command) { if (InvokeRequired) { Invoke(new Action<DuelRequest>(HandleDuelRequest), command); return; } if (Program.Config.RefuseDuelRequests || IgnoreList.Items.Contains(command.username.ToLower())) { Program.ChatServer.SendPacket(DevServerPackets.RefuseDuel); return; } RoomInfos info = RoomInfos.FromName(command.duelformatstring); var request = new DuelRequestFrm( command.username + Program.LanguageManager.Translation.DuelReqestMessage + Environment.NewLine + Program.LanguageManager.Translation.DuelRequestMode + RoomInfos.GameMode(info.mode) + Program.LanguageManager.Translation.DuelRequestRules + RoomInfos.GameRule(info.rule) + Program.LanguageManager.Translation.DuelRequestBanlist + LauncherHelper.GetBanListFromInt(info.banListType)); if (request.ShowDialog() == DialogResult.Yes) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You accepted " + command.username + " duel request.")); Program.ChatServer.SendPacket(DevServerPackets.AcceptDuel); } else { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "You refused " + command.username + " duel request.")); Program.ChatServer.SendPacket(DevServerPackets.RefuseDuel); } } public void StartDuelRequest(DuelRequest request) { ServerInfo server = null; if (Program.ServerList.ContainsKey(request.server)) server = Program.ServerList[request.server]; if (server != null) { LauncherHelper.GenerateConfig(server, request.duelformatstring); LauncherHelper.RunGame("-j"); } } public void DuelRequestRefused() { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, "Your duel request has been refused.")); } private void HandleTeamRequest(PacketCommand command) { if (InvokeRequired) { Invoke(new Action<PacketCommand>(HandleTeamRequest), command); return; } switch (command.Command) { case "JOIN": if (Program.Config.RefuseTeamInvites) { Program.ChatServer.SendPacket(DevServerPackets.TeamCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = "AUTOREFUSE" })); return; } if (MessageBox.Show(command.Data + " has invited you to join a team.", "Team Request", MessageBoxButtons.YesNo) == DialogResult.Yes) { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have accepted the team invite.")); Program.ChatServer.SendPacket(DevServerPackets.TeamCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = "ACCEPT" })); } else { WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have refused the team invite.")); Program.ChatServer.SendPacket(DevServerPackets.TeamCommand, JsonSerializer.SerializeToString(new PacketCommand { Command = "REFUSE" })); } break; case "LEAVE": Program.UserInfo.team = string.Empty; Program.UserInfo.teamRank = 0; ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString())); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have left the team.")); break; case "REMOVED": Program.UserInfo.team = string.Empty; Program.UserInfo.teamRank = 0; ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString())); WriteMessage(new ChatMessage(MessageType.System, CommandType.None, Program.UserInfo.username, "You have been removed from the team.")); break; case "DISBAND": if (Program.UserInfo.team == command.Data) { Program.UserInfo.team = string.Empty; Program.UserInfo.teamRank = 0; ChannelTabs.TabPages.Remove(GetChatWindow(MessageType.Team.ToString())); } break; } } private void IgnoreList_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { int index = IgnoreList.IndexFromPoint(e.Location); if (index == -1) { return; } IgnoreList.SelectedIndex = index; var mnu = new ContextMenuStrip(); var mnuremoveignore = new ToolStripMenuItem(Program.LanguageManager.Translation.chatRemoveIgnore); mnuremoveignore.Click += UnignoreUser; mnu.Items.Add(mnuremoveignore); mnu.Show(IgnoreList, e.Location); } } private void UnignoreUser(object sender, EventArgs e) { if (IgnoreList.SelectedItem == null) { return; } WriteMessage(new ChatMessage(MessageType.System, CommandType.None, null, IgnoreList.SelectedItem + " has been removed from your ignore list.")); IgnoreList.Items.Remove(IgnoreList.SelectedItem); SaveIgnoreList(); } private void SaveIgnoreList() { var ignoredusers = new string[IgnoreList.Items.Count]; // ReSharper disable CoVariantArrayConversion IgnoreList.Items.CopyTo(ignoredusers, 0); // ReSharper restore CoVariantArrayConversion string ignorestring = string.Join(",", ignoredusers); Program.Config.IgnoreList = ignorestring; Program.SaveConfig(Program.ConfigurationFilename, Program.Config); } private void FontSettings_Changed(object sender, EventArgs e) { var box = sender as ComboBox; var down = sender as NumericUpDown; if (box != null) { ComboBox fontstyle = box; Program.Config.ChatFont = fontstyle.SelectedItem.ToString(); } else if (down != null) { NumericUpDown size = down; Program.Config.ChatSize = size.Value; } foreach (ChatWindow tab in ChannelTabs.TabPages) { tab.ApplyNewSettings(); } foreach (var form in m_pmWindows.Values) { form.ApplyNewSettings(); } Program.SaveConfig(Program.ConfigurationFilename, Program.Config); } private void List_DoubleClick(object sender, EventArgs e) { ListBox list = UserListTabs.SelectedTab.Name == ChannelTab.Name ? ChannelList : UserList; if (list.SelectedIndex == -1) return; string user = list.Name == ChannelList.Name || list.Name == UserList.Name ? ((UserData)list.SelectedItem).username : list.SelectedItem.ToString(); if (Program.Config.PmWindows) { if (!m_pmWindows.ContainsKey(user)) { m_pmWindows.Add(user, new PmWindowFrm(user, true)); m_pmWindows[user].Show(); m_pmWindows[user].FormClosed += Chat_frm_FormClosed; } else { m_pmWindows[user].BringToFront(); } } else { if (GetChatWindow(user) == null) { ChannelTabs.TabPages.Add(new ChatWindow(user, true)); ChannelTabs.SelectedTab = GetChatWindow(user); } else { ChannelTabs.SelectedTab = GetChatWindow(user); } } } private void ChannelListBtn_Click(object sender, EventArgs e) { var channellist = new ChannelListFrm(); channellist.ShowDialog(); } private void LeaveBtn_Click(object sender, EventArgs e) { if (ChannelTabs.SelectedIndex != -1) { var selectedTab = (ChatWindow)ChannelTabs.SelectedTab; if (selectedTab.IsPrivate) { ChannelTabs.TabPages.Remove(selectedTab); } else { LeaveChannel(selectedTab.Text); } } } private void userSearchBtn_Click(object sender, EventArgs e) { string searchinfo = UserSearch.ForeColor == SystemColors.WindowFrame ? string.Empty : UserSearch.Text; Program.ChatServer.SendPacket(DevServerPackets.UserList, JsonSerializer.SerializeToString(new PacketCommand() { Command = "USERS", Data = searchinfo })); EnableSearchReset(); } private void adminSearchBtn_Click(object sender, EventArgs e) { string searchinfo = UserSearch.ForeColor == SystemColors.WindowFrame ? string.Empty : UserSearch.Text; Program.ChatServer.SendPacket(DevServerPackets.UserList, JsonSerializer.SerializeToString(new PacketCommand() { Command = "ADMIN", Data = searchinfo })); EnableSearchReset(); } private void teamSearchBtn_Click(object sender, EventArgs e) { Program.ChatServer.SendPacket(DevServerPackets.UserList, JsonSerializer.SerializeToString(new PacketCommand() { Command = "TEAM", Data = string.Empty })); EnableSearchReset(); } private void friendSearchBtn_Click(object sender, EventArgs e) { Program.ChatServer.SendPacket(DevServerPackets.UserList, JsonSerializer.SerializeToString(new PacketCommand() { Command = "FRIENDS", Data = string.Empty })); EnableSearchReset(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: this file was generated from 'xd.xml' using System.ServiceModel; namespace System.IdentityModel { internal class IdentityModelStringsVersion1 : IdentityModelStrings { public const string String0 = "Algorithm"; public const string String1 = "URI"; public const string String2 = "Reference"; public const string String3 = "Id"; public const string String4 = "Transforms"; public const string String5 = "Transform"; public const string String6 = "DigestMethod"; public const string String7 = "DigestValue"; public const string String8 = "http://www.w3.org/2000/09/xmldsig#"; public const string String9 = "http://www.w3.org/2000/09/xmldsig#enveloped-signature"; public const string String10 = "KeyInfo"; public const string String11 = "Signature"; public const string String12 = "SignedInfo"; public const string String13 = "CanonicalizationMethod"; public const string String14 = "SignatureMethod"; public const string String15 = "SignatureValue"; public const string String16 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; public const string String17 = "Timestamp"; public const string String18 = "Created"; public const string String19 = "Expires"; public const string String20 = "http://www.w3.org/2001/10/xml-exc-c14n#"; public const string String21 = "PrefixList"; public const string String22 = "InclusiveNamespaces"; public const string String23 = "ec"; public const string String24 = "Access"; public const string String25 = "AccessDecision"; public const string String26 = "Action"; public const string String27 = "Advice"; public const string String28 = "Assertion"; public const string String29 = "AssertionID"; public const string String30 = "AssertionIDReference"; public const string String31 = "Attribute"; public const string String32 = "AttributeName"; public const string String33 = "AttributeNamespace"; public const string String34 = "AttributeStatement"; public const string String35 = "AttributeValue"; public const string String36 = "Audience"; public const string String37 = "AudienceRestrictionCondition"; public const string String38 = "AuthenticationInstant"; public const string String39 = "AuthenticationMethod"; public const string String40 = "AuthenticationStatement"; public const string String41 = "AuthorityBinding"; public const string String42 = "AuthorityKind"; public const string String43 = "AuthorizationDecisionStatement"; public const string String44 = "Binding"; public const string String45 = "Condition"; public const string String46 = "Conditions"; public const string String47 = "Decision"; public const string String48 = "DoNotCacheCondition"; public const string String49 = "Evidence"; public const string String50 = "IssueInstant"; public const string String51 = "Issuer"; public const string String52 = "Location"; public const string String53 = "MajorVersion"; public const string String54 = "MinorVersion"; public const string String55 = "urn:oasis:names:tc:SAML:1.0:assertion"; public const string String56 = "NameIdentifier"; public const string String57 = "Format"; public const string String58 = "NameQualifier"; public const string String59 = "Namespace"; public const string String60 = "NotBefore"; public const string String61 = "NotOnOrAfter"; public const string String62 = "saml"; public const string String63 = "Statement"; public const string String64 = "Subject"; public const string String65 = "SubjectConfirmation"; public const string String66 = "SubjectConfirmationData"; public const string String67 = "ConfirmationMethod"; public const string String68 = "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key"; public const string String69 = "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"; public const string String70 = "SubjectLocality"; public const string String71 = "DNSAddress"; public const string String72 = "IPAddress"; public const string String73 = "SubjectStatement"; public const string String74 = "urn:oasis:names:tc:SAML:1.0:am:unspecified"; public const string String75 = "xmlns"; public const string String76 = "Resource"; public const string String77 = "UserName"; public const string String78 = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName"; public const string String79 = "EmailName"; public const string String80 = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"; public const string String81 = "u"; public const string String82 = "KeyName"; public const string String83 = "Type"; public const string String84 = "MgmtData"; public const string String85 = ""; public const string String86 = "KeyValue"; public const string String87 = "RSAKeyValue"; public const string String88 = "Modulus"; public const string String89 = "Exponent"; public const string String90 = "X509Data"; public const string String91 = "X509IssuerSerial"; public const string String92 = "X509IssuerName"; public const string String93 = "X509SerialNumber"; public const string String94 = "X509Certificate"; public const string String95 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; public const string String96 = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; public const string String97 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; public const string String98 = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; public const string String99 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; public const string String100 = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; public const string String101 = "http://www.w3.org/2001/04/xmlenc#des-cbc"; public const string String102 = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; public const string String103 = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; public const string String104 = "http://www.w3.org/2000/09/xmldsig#hmac-sha1"; public const string String105 = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; public const string String106 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1"; public const string String107 = "http://www.w3.org/2001/04/xmlenc#ripemd160"; public const string String108 = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; public const string String109 = "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; public const string String110 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; public const string String111 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; public const string String112 = "http://www.w3.org/2000/09/xmldsig#sha1"; public const string String113 = "http://www.w3.org/2001/04/xmlenc#sha256"; public const string String114 = "http://www.w3.org/2001/04/xmlenc#sha512"; public const string String115 = "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"; public const string String116 = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; public const string String117 = "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap"; public const string String118 = "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap"; public const string String119 = "o"; public const string String120 = "Nonce"; public const string String121 = "Password"; public const string String122 = "PasswordText"; public const string String123 = "Username"; public const string String124 = "UsernameToken"; public const string String125 = "BinarySecurityToken"; public const string String126 = "EncodingType"; public const string String127 = "KeyIdentifier"; public const string String128 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"; public const string String129 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#HexBinary"; public const string String130 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text"; public const string String131 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier"; public const string String132 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ"; public const string String133 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ1510"; public const string String134 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID"; public const string String135 = "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license"; public const string String136 = "FailedAuthentication"; public const string String137 = "InvalidSecurityToken"; public const string String138 = "InvalidSecurity"; public const string String139 = "SecurityTokenReference"; public const string String140 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; public const string String141 = "Security"; public const string String142 = "ValueType"; public const string String143 = "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1"; public const string String144 = "k"; public const string String145 = "SignatureConfirmation"; public const string String146 = "Value"; public const string String147 = "TokenType"; public const string String148 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1"; public const string String149 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"; public const string String150 = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1"; public const string String151 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"; public const string String152 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"; public const string String153 = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID"; public const string String154 = "EncryptedHeader"; public const string String155 = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"; public const string String156 = "http://www.w3.org/2001/04/xmlenc#"; public const string String157 = "DataReference"; public const string String158 = "EncryptedData"; public const string String159 = "EncryptionMethod"; public const string String160 = "CipherData"; public const string String161 = "CipherValue"; public const string String162 = "ReferenceList"; public const string String163 = "Encoding"; public const string String164 = "MimeType"; public const string String165 = "CarriedKeyName"; public const string String166 = "Recipient"; public const string String167 = "EncryptedKey"; public const string String168 = "KeyReference"; public const string String169 = "e"; public const string String170 = "http://www.w3.org/2001/04/xmlenc#Element"; public const string String171 = "http://www.w3.org/2001/04/xmlenc#Content"; public const string String172 = "http://schemas.xmlsoap.org/ws/2005/02/sc"; public const string String173 = "DerivedKeyToken"; public const string String174 = "Length"; public const string String175 = "SecurityContextToken"; public const string String176 = "Generation"; public const string String177 = "Label"; public const string String178 = "Offset"; public const string String179 = "Properties"; public const string String180 = "Identifier"; public const string String181 = "Cookie"; public const string String182 = "RenewNeeded"; public const string String183 = "BadContextToken"; public const string String184 = "c"; public const string String185 = "http://schemas.xmlsoap.org/ws/2005/02/sc/dk"; public const string String186 = "http://schemas.xmlsoap.org/ws/2005/02/sc/sct"; public const string String187 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT"; public const string String188 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT"; public const string String189 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew"; public const string String190 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew"; public const string String191 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel"; public const string String192 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel"; public const string String193 = "RequestSecurityTokenResponseCollection"; public const string String194 = "http://schemas.xmlsoap.org/ws/2005/02/trust"; public const string String195 = "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret"; public const string String196 = "AUTH-HASH"; public const string String197 = "RequestSecurityTokenResponse"; public const string String198 = "KeySize"; public const string String199 = "RequestedTokenReference"; public const string String200 = "AppliesTo"; public const string String201 = "Authenticator"; public const string String202 = "CombinedHash"; public const string String203 = "BinaryExchange"; public const string String204 = "Lifetime"; public const string String205 = "RequestedSecurityToken"; public const string String206 = "Entropy"; public const string String207 = "RequestedProofToken"; public const string String208 = "ComputedKey"; public const string String209 = "RequestSecurityToken"; public const string String210 = "RequestType"; public const string String211 = "Context"; public const string String212 = "BinarySecret"; public const string String213 = "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego"; public const string String214 = "http://schemas.microsoft.com/net/2004/07/secext/TLSNego"; public const string String215 = "t"; public const string String216 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue"; public const string String217 = "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue"; public const string String218 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue"; public const string String219 = "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey"; public const string String220 = "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1"; public const string String221 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce"; public const string String222 = "RenewTarget"; public const string String223 = "CancelTarget"; public const string String224 = "RequestedTokenCancelled"; public const string String225 = "RequestedAttachedReference"; public const string String226 = "RequestedUnattachedReference"; public const string String227 = "IssuedTokens"; public const string String228 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew"; public const string String229 = "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel"; public const string String230 = "KeyType"; public const string String231 = "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey"; public const string String232 = "Claims"; public const string String233 = "InvalidRequest"; public const string String234 = "UseKey"; public const string String235 = "SignWith"; public const string String236 = "EncryptWith"; public const string String237 = "EncryptionAlgorithm"; public const string String238 = "CanonicalizationAlgorithm"; public const string String239 = "ComputedKeyAlgorithm"; public const string String240 = "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego"; public const string String241 = "http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego"; public const string String242 = "trust"; public const string String243 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Issue"; public const string String244 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Issue"; public const string String245 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue"; public const string String246 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/AsymmetricKey"; public const string String247 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/SymmetricKey"; public const string String248 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Nonce"; public const string String249 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/CK/PSHA1"; public const string String250 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/PublicKey"; public const string String251 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512"; public const string String252 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512#BinarySecret"; public const string String253 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTRC/IssueFinal"; public const string String254 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Renew"; public const string String255 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Renew"; public const string String256 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/RenewFinal"; public const string String257 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/Cancel"; public const string String258 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/Cancel"; public const string String259 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/CancelFinal"; public const string String260 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Renew"; public const string String261 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Cancel"; public const string String262 = "KeyWrapAlgorithm"; public const string String263 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer"; public const string String264 = "SecondaryParameters"; public const string String265 = "Dialect"; public const string String266 = "http://schemas.xmlsoap.org/ws/2005/05/identity"; public const string String267 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk/p_sha1"; public const string String268 = "sc"; public const string String269 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/dk"; public const string String270 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512/sct"; public const string String271 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT"; public const string String272 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT"; public const string String273 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Renew"; public const string String274 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Renew"; public const string String275 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RST/SCT/Cancel"; public const string String276 = "http://docs.oasis-open.org/ws-sx/ws-trust/200512/RSTR/SCT/Cancel"; public const string String277 = "http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512"; public const string String278 = "Instance"; public override int Count { get { return 279; } } public override string this[int index] { get { DiagnosticUtility.DebugAssert(index >= 0 && index < this.Count, "The index is out of range. It should be greater than or equal to 0 and less than" + this.Count.ToString()); switch (index) { case 0: return String0; case 1: return String1; case 2: return String2; case 3: return String3; case 4: return String4; case 5: return String5; case 6: return String6; case 7: return String7; case 8: return String8; case 9: return String9; case 10: return String10; case 11: return String11; case 12: return String12; case 13: return String13; case 14: return String14; case 15: return String15; case 16: return String16; case 17: return String17; case 18: return String18; case 19: return String19; case 20: return String20; case 21: return String21; case 22: return String22; case 23: return String23; case 24: return String24; case 25: return String25; case 26: return String26; case 27: return String27; case 28: return String28; case 29: return String29; case 30: return String30; case 31: return String31; case 32: return String32; case 33: return String33; case 34: return String34; case 35: return String35; case 36: return String36; case 37: return String37; case 38: return String38; case 39: return String39; case 40: return String40; case 41: return String41; case 42: return String42; case 43: return String43; case 44: return String44; case 45: return String45; case 46: return String46; case 47: return String47; case 48: return String48; case 49: return String49; case 50: return String50; case 51: return String51; case 52: return String52; case 53: return String53; case 54: return String54; case 55: return String55; case 56: return String56; case 57: return String57; case 58: return String58; case 59: return String59; case 60: return String60; case 61: return String61; case 62: return String62; case 63: return String63; case 64: return String64; case 65: return String65; case 66: return String66; case 67: return String67; case 68: return String68; case 69: return String69; case 70: return String70; case 71: return String71; case 72: return String72; case 73: return String73; case 74: return String74; case 75: return String75; case 76: return String76; case 77: return String77; case 78: return String78; case 79: return String79; case 80: return String80; case 81: return String81; case 82: return String82; case 83: return String83; case 84: return String84; case 85: return String85; case 86: return String86; case 87: return String87; case 88: return String88; case 89: return String89; case 90: return String90; case 91: return String91; case 92: return String92; case 93: return String93; case 94: return String94; case 95: return String95; case 96: return String96; case 97: return String97; case 98: return String98; case 99: return String99; case 100: return String100; case 101: return String101; case 102: return String102; case 103: return String103; case 104: return String104; case 105: return String105; case 106: return String106; case 107: return String107; case 108: return String108; case 109: return String109; case 110: return String110; case 111: return String111; case 112: return String112; case 113: return String113; case 114: return String114; case 115: return String115; case 116: return String116; case 117: return String117; case 118: return String118; case 119: return String119; case 120: return String120; case 121: return String121; case 122: return String122; case 123: return String123; case 124: return String124; case 125: return String125; case 126: return String126; case 127: return String127; case 128: return String128; case 129: return String129; case 130: return String130; case 131: return String131; case 132: return String132; case 133: return String133; case 134: return String134; case 135: return String135; case 136: return String136; case 137: return String137; case 138: return String138; case 139: return String139; case 140: return String140; case 141: return String141; case 142: return String142; case 143: return String143; case 144: return String144; case 145: return String145; case 146: return String146; case 147: return String147; case 148: return String148; case 149: return String149; case 150: return String150; case 151: return String151; case 152: return String152; case 153: return String153; case 154: return String154; case 155: return String155; case 156: return String156; case 157: return String157; case 158: return String158; case 159: return String159; case 160: return String160; case 161: return String161; case 162: return String162; case 163: return String163; case 164: return String164; case 165: return String165; case 166: return String166; case 167: return String167; case 168: return String168; case 169: return String169; case 170: return String170; case 171: return String171; case 172: return String172; case 173: return String173; case 174: return String174; case 175: return String175; case 176: return String176; case 177: return String177; case 178: return String178; case 179: return String179; case 180: return String180; case 181: return String181; case 182: return String182; case 183: return String183; case 184: return String184; case 185: return String185; case 186: return String186; case 187: return String187; case 188: return String188; case 189: return String189; case 190: return String190; case 191: return String191; case 192: return String192; case 193: return String193; case 194: return String194; case 195: return String195; case 196: return String196; case 197: return String197; case 198: return String198; case 199: return String199; case 200: return String200; case 201: return String201; case 202: return String202; case 203: return String203; case 204: return String204; case 205: return String205; case 206: return String206; case 207: return String207; case 208: return String208; case 209: return String209; case 210: return String210; case 211: return String211; case 212: return String212; case 213: return String213; case 214: return String214; case 215: return String215; case 216: return String216; case 217: return String217; case 218: return String218; case 219: return String219; case 220: return String220; case 221: return String221; case 222: return String222; case 223: return String223; case 224: return String224; case 225: return String225; case 226: return String226; case 227: return String227; case 228: return String228; case 229: return String229; case 230: return String230; case 231: return String231; case 232: return String232; case 233: return String233; case 234: return String234; case 235: return String235; case 236: return String236; case 237: return String237; case 238: return String238; case 239: return String239; case 240: return String240; case 241: return String241; case 242: return String242; case 243: return String243; case 244: return String244; case 245: return String245; case 246: return String246; case 247: return String247; case 248: return String248; case 249: return String249; case 250: return String250; case 251: return String251; case 252: return String252; case 253: return String253; case 254: return String254; case 255: return String255; case 256: return String256; case 257: return String257; case 258: return String258; case 259: return String259; case 260: return String260; case 261: return String261; case 262: return String262; case 263: return String263; case 264: return String264; case 265: return String265; case 266: return String266; case 267: return String267; case 268: return String268; case 269: return String269; case 270: return String270; case 271: return String271; case 272: return String272; case 273: return String273; case 274: return String274; case 275: return String275; case 276: return String276; case 277: return String277; case 278: return String278; default: return null; } } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Globalization; using System.Text; using System.Reflection; using Microsoft.PowerShell.Commands; using Dbg = System.Diagnostics.Debug; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation { /// <summary> /// Defines session capabilities provided by a PowerShell session /// </summary> /// <seealso cref="System.Management.Automation.Runspaces.InitialSessionState.CreateRestricted"/> /// <seealso cref="System.Management.Automation.CommandMetadata.GetRestrictedCommands"/> [Flags] public enum SessionCapabilities { /// <summary> /// Session with <see cref="RemoteServer"/> capabilities can be made available on a server /// that wants to provide a full user experience to PowerShell clients. /// Clients connecting to the server will be able to use implicit remoting /// (Import-PSSession, Export-PSSession) as well as interactive remoting (Enter-PSSession, Exit-PSSession). /// </summary> RemoteServer = 0x1, /// <summary> /// Session with <see cref="WorkflowServer"/> capabibilities can be made available on /// a server that wants to provide workflow hosting capabilities in the /// specified end points. All jobs commands as well as commands for /// implicit remoting and interactive remoting will be made available /// </summary> WorkflowServer = 0x2, /// <summary> /// Include language capabilities /// </summary> Language = 0x4 } /// <summary> /// This class represents the compiled metadata for a command type. /// </summary> [DebuggerDisplay("CommandName = {Name}; Type = {CommandType}")] public sealed class CommandMetadata { #region Public Constructor /// <summary> /// Constructs a CommandMetada object for the given CLS complaint type /// <paramref name="commandType"/>. /// </summary> /// <param name="commandType"> /// CLS complaint type to inspect for Cmdlet metadata. /// </param> /// <exception cref="ArgumentNullException"> /// commandType is null. /// </exception> /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> public CommandMetadata(Type commandType) { Init(null, null, commandType, false); } /// <summary> /// Construct a CommandMetadata object for the given commandInfo /// </summary> /// <param name="commandInfo"> /// The commandInfo object to construct CommandMetadata for /// </param> /// <exception cref="ArgumentNullException"> /// commandInfo is null. /// </exception> /// <exception cref="PSNotSupportedException"> /// If the commandInfo is an alias to an unknown command, or if the commandInfo /// is an unsupported command type. /// </exception> public CommandMetadata(CommandInfo commandInfo) : this(commandInfo, false) { } /// <summary> /// Construct a CommandMetadata object for the given commandInfo /// </summary> /// <param name="commandInfo"> /// The commandInfo object to construct CommandMetadata for /// </param> /// <param name="shouldGenerateCommonParameters"> /// Should common parameters be included in the metadata? /// </param> /// <exception cref="ArgumentNullException"> /// commandInfo is null. /// </exception> /// <exception cref="PSNotSupportedException"> /// If the commandInfo is an alias to an unknown command, or if the commandInfo /// is an unsupported command type. /// </exception> public CommandMetadata(CommandInfo commandInfo, bool shouldGenerateCommonParameters) { if (commandInfo == null) { throw PSTraceSource.NewArgumentNullException("commandInfo"); } while (commandInfo is AliasInfo) { commandInfo = ((AliasInfo)commandInfo).ResolvedCommand; if (commandInfo == null) { throw PSTraceSource.NewNotSupportedException(); } } CmdletInfo cmdletInfo; ExternalScriptInfo scriptInfo; FunctionInfo funcInfo; if ((cmdletInfo = commandInfo as CmdletInfo) != null) { Init(commandInfo.Name, cmdletInfo.FullName, cmdletInfo.ImplementingType, shouldGenerateCommonParameters); } else if ((scriptInfo = commandInfo as ExternalScriptInfo) != null) { // Accessing the script block property here reads and parses the script Init(scriptInfo.ScriptBlock, scriptInfo.Path, shouldGenerateCommonParameters); _wrappedCommandType = CommandTypes.ExternalScript; } else if ((funcInfo = commandInfo as FunctionInfo) != null) { Init(funcInfo.ScriptBlock, funcInfo.Name, shouldGenerateCommonParameters); _wrappedCommandType = commandInfo.CommandType; } else { throw PSTraceSource.NewNotSupportedException(); } } /// <summary> /// Construct a CommandMetadata object for a script file. /// </summary> /// <param name="path">The path to the script file.</param> public CommandMetadata(string path) { string scriptName = IO.Path.GetFileName(path); ExternalScriptInfo scriptInfo = new ExternalScriptInfo(scriptName, path); Init(scriptInfo.ScriptBlock, path, false); _wrappedCommandType = CommandTypes.ExternalScript; } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> CommandMetadata object. /// Instances of Attribute and Type classes are copied by reference. /// </summary> /// <param name="other">object to copy</param> public CommandMetadata(CommandMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } Name = other.Name; ConfirmImpact = other.ConfirmImpact; _defaultParameterSetFlag = other._defaultParameterSetFlag; _defaultParameterSetName = other._defaultParameterSetName; _implementsDynamicParameters = other._implementsDynamicParameters; SupportsShouldProcess = other.SupportsShouldProcess; SupportsPaging = other.SupportsPaging; SupportsTransactions = other.SupportsTransactions; this.CommandType = other.CommandType; _wrappedAnyCmdlet = other._wrappedAnyCmdlet; _wrappedCommand = other._wrappedCommand; _wrappedCommandType = other._wrappedCommandType; _parameters = new Dictionary<string, ParameterMetadata>(other.Parameters.Count, StringComparer.OrdinalIgnoreCase); // deep copy if (other.Parameters != null) { foreach (KeyValuePair<string, ParameterMetadata> entry in other.Parameters) { _parameters.Add(entry.Key, new ParameterMetadata(entry.Value)); } } // deep copy of the collection, collection items (Attributes) copied by reference if (other._otherAttributes == null) { _otherAttributes = null; } else { _otherAttributes = new Collection<Attribute>(new List<Attribute>(other._otherAttributes.Count)); foreach (Attribute attribute in other._otherAttributes) { _otherAttributes.Add(attribute); } } // not copying those fields/members as they are untouched (and left set to null) // by public constructors, so we can't rely on those fields/members to be set // when CommandMetadata comes from a user _staticCommandParameterMetadata = null; } /// <summary> /// Constructor used by implicit remoting /// </summary> internal CommandMetadata( string name, CommandTypes commandType, bool isProxyForCmdlet, string defaultParameterSetName, bool supportsShouldProcess, ConfirmImpact confirmImpact, bool supportsPaging, bool supportsTransactions, bool positionalBinding, Dictionary<string, ParameterMetadata> parameters) { Name = _wrappedCommand = name; _wrappedCommandType = commandType; _wrappedAnyCmdlet = isProxyForCmdlet; _defaultParameterSetName = defaultParameterSetName; SupportsShouldProcess = supportsShouldProcess; SupportsPaging = supportsPaging; ConfirmImpact = confirmImpact; SupportsTransactions = supportsTransactions; PositionalBinding = positionalBinding; this.Parameters = parameters; } private void Init(string name, string fullyQualifiedName, Type commandType, bool shouldGenerateCommonParameters) { Name = name; this.CommandType = commandType; if (commandType != null) { ConstructCmdletMetadataUsingReflection(); _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } // Use fully qualified name if available. _wrappedCommand = !string.IsNullOrEmpty(fullyQualifiedName) ? fullyQualifiedName : Name; _wrappedCommandType = CommandTypes.Cmdlet; _wrappedAnyCmdlet = true; } private void Init(ScriptBlock scriptBlock, string name, bool shouldGenerateCommonParameters) { if (scriptBlock.UsesCmdletBinding) { _wrappedAnyCmdlet = true; } else { // Ignore what was passed in, there are no common parameters if cmdlet binding is not used. shouldGenerateCommonParameters = false; } CmdletBindingAttribute cmdletBindingAttribute = scriptBlock.CmdletBindingAttribute; if (cmdletBindingAttribute != null) { ProcessCmdletAttribute(cmdletBindingAttribute); } else if (scriptBlock.UsesCmdletBinding) { _defaultParameterSetName = null; } Obsolete = scriptBlock.ObsoleteAttribute; _scriptBlock = scriptBlock; _wrappedCommand = Name = name; _shouldGenerateCommonParameters = shouldGenerateCommonParameters; } #endregion #region ctor /// <summary> /// Gets the metdata for the specified cmdlet from the cache or creates /// a new instance if its not in the cache. /// </summary> /// /// <param name="commandName"> /// The name of the command that this metadata represents. /// </param> /// /// <param name="cmdletType"> /// The cmdlet to get the metadata for. /// </param> /// /// <param name="context"> /// The current engine context. /// </param> /// /// <returns> /// The CommandMetadata for the specified cmdlet. /// </returns> /// /// <exception cref="ArgumentException"> /// If <paramref name="commandName"/> is null or empty. /// </exception> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdletType"/> is null. /// </exception> /// /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal static CommandMetadata Get(string commandName, Type cmdletType, ExecutionContext context) { if (String.IsNullOrEmpty(commandName)) { throw PSTraceSource.NewArgumentException("commandName"); } CommandMetadata result = null; if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryGetValue(cmdletTypeName, out result); } if (result == null) { result = new CommandMetadata(commandName, cmdletType, context); if ((context != null) && (cmdletType != null)) { string cmdletTypeName = cmdletType.AssemblyQualifiedName; s_commandMetadataCache.TryAdd(cmdletTypeName, result); } } return result; } // Get /// <summary> /// Constructs an instance of CommandMetadata using reflection against a bindable object /// </summary> /// /// <param name="commandName"> /// The name of the command that this metadata represents. /// </param> /// /// <param name="cmdletType"> /// An instance of an object type that can be used to bind MSH parameters. A type is /// considered bindable if it has at least one field and/or property that is decorated /// with the ParameterAttribute. /// </param> /// /// <param name="context"> /// The current engine context. If null, the command and type metadata will be generated /// and will not be cached. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="cmdletType"/> is null. /// </exception> /// /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal CommandMetadata(string commandName, Type cmdletType, ExecutionContext context) { if (String.IsNullOrEmpty(commandName)) { throw PSTraceSource.NewArgumentException("commandName"); } Name = commandName; this.CommandType = cmdletType; if (cmdletType != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(cmdletType, context, false); ConstructCmdletMetadataUsingReflection(); _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, true); _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); _staticCommandParameterMetadata.MakeReadOnly(); } } /// <summary> /// Constructor for creating command metadata from a script block. /// </summary> /// <param name="scriptblock"></param> /// <param name="context"></param> /// <param name="commandName"></param> /// <remarks> /// Unlike cmdlet based on a C# type where cmdlet metadata and parameter /// metadata is created through reflecting the implementation type, script /// cmdlet has different way for constructing metadata. /// /// 1. Metadata for cmdlet itself comes from cmdlet statement, which /// is parsed into CmdletDeclarationNode and then converted into /// a CmdletAttribute object. /// 2. Metadata for parameter comes from parameter declaration statement, /// which is parsed into parameter nodes with parameter annotations. /// Information in ParameterNodes is eventually transformed into a /// dictionary of RuntimeDefinedParameters. /// /// By the time this constructor is called, information about CmdletAttribute /// and RuntimeDefinedParameters for the script block has been setup with /// the scriptblock object. /// /// </remarks> internal CommandMetadata(ScriptBlock scriptblock, string commandName, ExecutionContext context) { if (scriptblock == null) { throw PSTraceSource.NewArgumentException("scriptblock"); } CmdletBindingAttribute cmdletBindingAttribute = scriptblock.CmdletBindingAttribute; if (cmdletBindingAttribute != null) { ProcessCmdletAttribute(cmdletBindingAttribute); } else { _defaultParameterSetName = null; } Obsolete = scriptblock.ObsoleteAttribute; Name = commandName; this.CommandType = typeof(PSScriptCmdlet); if (scriptblock.HasDynamicParameters) { _implementsDynamicParameters = true; } InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(scriptblock.RuntimeDefinedParameters, false, scriptblock.UsesCmdletBinding); _staticCommandParameterMetadata = MergeParameterMetadata(context, parameterMetadata, scriptblock.UsesCmdletBinding); _defaultParameterSetFlag = _staticCommandParameterMetadata.GenerateParameterSetMappingFromMetadata(_defaultParameterSetName); _staticCommandParameterMetadata.MakeReadOnly(); } #endregion ctor #region Public Properties /// <summary> /// Gets the name of the command this metadata represents /// </summary> public string Name { get; set; } = String.Empty; /// <summary> /// The Type which this CommandMetadata represents. /// </summary> public Type CommandType { get; private set; } // The ScriptBlock which this CommandMetadata represents. private ScriptBlock _scriptBlock; /// <summary> /// Gets/Sets the default parameter set name /// </summary> public string DefaultParameterSetName { get { return _defaultParameterSetName; } set { if (string.IsNullOrEmpty(value)) { value = ParameterAttribute.AllParameterSets; } _defaultParameterSetName = value; } } private string _defaultParameterSetName = ParameterAttribute.AllParameterSets; /// <summary> /// True if the cmdlet declared that it supports ShouldProcess, false otherwise. /// </summary> /// <value></value> public bool SupportsShouldProcess { get; set; } /// <summary> /// True if the cmdlet declared that it supports Paging, false otherwise. /// </summary> /// <value></value> public bool SupportsPaging { get; set; } /// <summary> /// When true, the command will auto-generate appropriate parameter metadata to support positional /// parameters if the script hasn't already specified multiple parameter sets or specified positions /// explicitly via the <see cref="ParameterAttribute"/>. /// </summary> public bool PositionalBinding { get; set; } = true; /// <summary> /// True if the cmdlet declared that it supports transactions, false otherwise. /// </summary> /// <value></value> public bool SupportsTransactions { get; set; } /// <summary> /// Related link URI for Get-Help -Online /// </summary> [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] public string HelpUri { get; set; } = String.Empty; /// <summary> /// The remoting capabilities of this cmdlet, when exposed in a context /// with ambient remoting. /// </summary> public RemotingCapability RemotingCapability { get { RemotingCapability currentRemotingCapability = _remotingCapability; if ((currentRemotingCapability == Automation.RemotingCapability.PowerShell) && ((this.Parameters != null) && this.Parameters.ContainsKey("ComputerName"))) { _remotingCapability = Automation.RemotingCapability.SupportedByCommand; } return _remotingCapability; } set { _remotingCapability = value; } } private RemotingCapability _remotingCapability = RemotingCapability.PowerShell; /// <summary> /// Indicates the "destructiveness" of the command operation and /// when it should be confirmed. This is only effective when /// the command calls ShouldProcess, which should only occur when /// SupportsShouldProcess is specified. /// </summary> /// <value></value> public ConfirmImpact ConfirmImpact { get; set; } = ConfirmImpact.Medium; /// <summary> /// Gets the parameter data for this command /// </summary> public Dictionary<string, ParameterMetadata> Parameters { get { if (_parameters == null) { // Return parameters for a script block if (_scriptBlock != null) { InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(_scriptBlock.RuntimeDefinedParameters, false, _scriptBlock.UsesCmdletBinding); MergedCommandParameterMetadata mergedCommandParameterMetadata = MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters); _parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata); } else if (this.CommandType != null) { // Construct compiled parameter metada from this InternalParameterMetadata parameterMetadata = InternalParameterMetadata.Get(this.CommandType, null, false); MergedCommandParameterMetadata mergedCommandParameterMetadata = MergeParameterMetadata(null, parameterMetadata, _shouldGenerateCommonParameters); // Construct parameter metadata from compiled parameter metadata // compiled parameter metadata is used for internal purposes. It has lots of information // which is used by ParameterBinder. _parameters = ParameterMetadata.GetParameterMetadata(mergedCommandParameterMetadata); } } return _parameters; } private set { _parameters = value; } } private Dictionary<string, ParameterMetadata> _parameters; private bool _shouldGenerateCommonParameters; /// <summary> /// Gets or sets the obsolete attribute on the command /// </summary> /// <value></value> internal ObsoleteAttribute Obsolete { get; set; } #endregion #region internal members /// <summary> /// Gets the merged metadata for the command including cmdlet declared parameters, /// common parameters, and (optionally) ShouldProcess and Transactions parameters /// </summary> /// <value></value> internal MergedCommandParameterMetadata StaticCommandParameterMetadata { get { return _staticCommandParameterMetadata; } } private readonly MergedCommandParameterMetadata _staticCommandParameterMetadata; /// <summary> /// True if the cmdlet implements dynamic parameters, or false otherwise /// </summary> /// <value></value> internal bool ImplementsDynamicParameters { get { return _implementsDynamicParameters; } } private bool _implementsDynamicParameters; /// <summary> /// Gets the bit in the parameter set map for the default parameter set. /// </summary> /// internal uint DefaultParameterSetFlag { get { return _defaultParameterSetFlag; } set { _defaultParameterSetFlag = value; } } private uint _defaultParameterSetFlag; /// <summary> /// A collection of attributes that were declared at the cmdlet level but were not /// recognized by the engine. /// </summary> private readonly Collection<Attribute> _otherAttributes = new Collection<Attribute>(); // command this CommandMetadata instance is intended to wrap private string _wrappedCommand; // the type of command this CommandMetadata instance is intended to wrap private CommandTypes _wrappedCommandType; // The CommandType for a script cmdlet is not CommandTypes.Cmdlet, yet // proxy generation needs to know the difference between script and script cmdlet. private bool _wrappedAnyCmdlet; internal bool WrappedAnyCmdlet { get { return _wrappedAnyCmdlet; } } internal CommandTypes WrappedCommandType { get { return _wrappedCommandType; } } #endregion internal members #region helper methods /// <summary> /// Constructs the command metadata by using reflection against the /// CLR type. /// </summary> /// /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// private void ConstructCmdletMetadataUsingReflection() { Diagnostics.Assert( CommandType != null, "This method should only be called when constructed with the Type"); // Determine if the cmdlet implements dynamic parameters by looking for the interface Type dynamicParametersType = CommandType.GetInterface(typeof(IDynamicParameters).Name, true); if (dynamicParametersType != null) { _implementsDynamicParameters = true; } // Process the attributes on the cmdlet var customAttributes = CommandType.GetTypeInfo().GetCustomAttributes(false); foreach (Attribute attribute in customAttributes) { CmdletAttribute cmdletAttribute = attribute as CmdletAttribute; if (cmdletAttribute != null) { ProcessCmdletAttribute(cmdletAttribute); this.Name = cmdletAttribute.VerbName + "-" + cmdletAttribute.NounName; } else if (attribute is ObsoleteAttribute) { Obsolete = (ObsoleteAttribute)attribute; } else { _otherAttributes.Add(attribute); } } } // ConstructCmdletMetadataUsingReflection /// <summary> /// Extracts the cmdlet data from the CmdletAttribute /// </summary> /// /// <param name="attribute"> /// The CmdletAttribute to process /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="attribute"/> is null. /// </exception> /// /// <exception cref="ParsingMetadataException"> /// If more than int.MaxValue parameter-sets are defined for the command. /// </exception> /// private void ProcessCmdletAttribute(CmdletCommonMetadataAttribute attribute) { if (attribute == null) { throw PSTraceSource.NewArgumentNullException("attribute"); } // Process the default parameter set name _defaultParameterSetName = attribute.DefaultParameterSetName; // Check to see if the cmdlet supports ShouldProcess SupportsShouldProcess = attribute.SupportsShouldProcess; // Determine the cmdlet's impact confirmation ConfirmImpact = attribute.ConfirmImpact; // Check to see if the cmdlet supports paging SupportsPaging = attribute.SupportsPaging; // Check to see if the cmdlet supports transactions SupportsTransactions = attribute.SupportsTransactions; // Grab related link HelpUri = attribute.HelpUri; // Remoting support _remotingCapability = attribute.RemotingCapability; // Check to see if the cmdlet uses positional binding var cmdletBindingAttribute = attribute as CmdletBindingAttribute; if (cmdletBindingAttribute != null) { PositionalBinding = cmdletBindingAttribute.PositionalBinding; } } // ProcessCmdletAttribute /// <summary> /// Merges parameter metadata from different sources: those that are coming from Type, /// CommonParameters, should process etc. /// </summary> /// <param name="context"></param> /// <param name="parameterMetadata"></param> /// <param name="shouldGenerateCommonParameters"> /// true if metadata info about Verbose,Debug etc needs to be generated. /// false otherwise. /// </param> private MergedCommandParameterMetadata MergeParameterMetadata(ExecutionContext context, InternalParameterMetadata parameterMetadata, bool shouldGenerateCommonParameters) { // Create an instance of the static metadata class MergedCommandParameterMetadata staticCommandParameterMetadata = new MergedCommandParameterMetadata(); // First add the metadata for the formal cmdlet parameters staticCommandParameterMetadata.AddMetadataForBinder( parameterMetadata, ParameterBinderAssociation.DeclaredFormalParameters); // Now add the common parameters metadata if (shouldGenerateCommonParameters) { InternalParameterMetadata commonParametersMetadata = InternalParameterMetadata.Get(typeof(CommonParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( commonParametersMetadata, ParameterBinderAssociation.CommonParameters); // If the command supports ShouldProcess, add the metadata for // those parameters if (this.SupportsShouldProcess) { InternalParameterMetadata shouldProcessParametersMetadata = InternalParameterMetadata.Get(typeof(ShouldProcessParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( shouldProcessParametersMetadata, ParameterBinderAssociation.ShouldProcessParameters); } // If the command supports paging, add the metadata for // those parameters if (this.SupportsPaging) { InternalParameterMetadata pagingParametersMetadata = InternalParameterMetadata.Get(typeof(PagingParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( pagingParametersMetadata, ParameterBinderAssociation.PagingParameters); } // If the command supports transactions, add the metadata for // those parameters if (this.SupportsTransactions) { InternalParameterMetadata transactionParametersMetadata = InternalParameterMetadata.Get(typeof(TransactionParameters), context, false); staticCommandParameterMetadata.AddMetadataForBinder( transactionParametersMetadata, ParameterBinderAssociation.TransactionParameters); } } return staticCommandParameterMetadata; } // MergeParameterMetadata #endregion helper methods #region Proxy Command generation /// <summary> /// Gets the ScriptCmdlet in string format /// </summary> /// <returns></returns> internal string GetProxyCommand(string helpComment, bool generateDynamicParameters) { if (string.IsNullOrEmpty(helpComment)) { helpComment = string.Format(CultureInfo.InvariantCulture, @" .ForwardHelpTargetName {0} .ForwardHelpCategory {1} ", _wrappedCommand, _wrappedCommandType); } string dynamicParamblock = String.Empty; if (generateDynamicParameters && this.ImplementsDynamicParameters) { dynamicParamblock = String.Format(CultureInfo.InvariantCulture, @" dynamicparam {{{0}}} ", GetDynamicParamBlock()); } string result = string.Format(CultureInfo.InvariantCulture, @"{0} param({1}) {2}begin {{{3}}} process {{{4}}} end {{{5}}} <# {6} #> ", GetDecl(), GetParamBlock(), dynamicParamblock, GetBeginBlock(), GetProcessBlock(), GetEndBlock(), CodeGeneration.EscapeBlockCommentContent(helpComment)); return result; } internal string GetDecl() { string result = ""; string separator = ""; if (_wrappedAnyCmdlet) { StringBuilder decl = new StringBuilder("[CmdletBinding("); if (!string.IsNullOrEmpty(_defaultParameterSetName)) { decl.Append(separator); decl.Append("DefaultParameterSetName='"); decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(_defaultParameterSetName)); decl.Append("'"); separator = ", "; } if (SupportsShouldProcess) { decl.Append(separator); decl.Append("SupportsShouldProcess=$true"); separator = ", "; decl.Append(separator); decl.Append("ConfirmImpact='"); decl.Append(ConfirmImpact); decl.Append("'"); } if (SupportsPaging) { decl.Append(separator); decl.Append("SupportsPaging=$true"); separator = ", "; } if (SupportsTransactions) { decl.Append(separator); decl.Append("SupportsTransactions=$true"); separator = ", "; } if (PositionalBinding == false) { decl.Append(separator); decl.Append("PositionalBinding=$false"); separator = ", "; } if (!string.IsNullOrEmpty(HelpUri)) { decl.Append(separator); decl.Append("HelpUri='"); decl.Append(CodeGeneration.EscapeSingleQuotedStringContent(HelpUri)); decl.Append("'"); separator = ", "; } if (_remotingCapability != RemotingCapability.PowerShell) { decl.Append(separator); decl.Append("RemotingCapability='"); decl.Append(_remotingCapability); decl.Append("'"); separator = ", "; } decl.Append(")]"); result = decl.ToString(); } return result; } internal string GetParamBlock() { if (Parameters.Keys.Count > 0) { StringBuilder parameters = new StringBuilder(); string prefix = string.Concat(Environment.NewLine, " "); string paramDataPrefix = null; foreach (var pair in Parameters) { if (paramDataPrefix != null) { parameters.Append(paramDataPrefix); } else { // syntax for parameter separation : comma followed by new-line. paramDataPrefix = string.Concat(",", Environment.NewLine); } // generate the parameter proxy and append to the list string paramData = pair.Value.GetProxyParameterData(prefix, pair.Key, _wrappedAnyCmdlet); parameters.Append(paramData); } return parameters.ToString(); } return ""; } internal string GetBeginBlock() { string result; if (string.IsNullOrEmpty(_wrappedCommand)) { string error = ProxyCommandStrings.CommandMetadataMissingCommandName; throw new InvalidOperationException(error); } string commandOrigin = "$myInvocation.CommandOrigin"; // For functions, don't proxy the command origin, otherwise they will // be subject to the runspace restrictions if (_wrappedCommandType == CommandTypes.Function) { commandOrigin = ""; } if (_wrappedAnyCmdlet) { result = string.Format(CultureInfo.InvariantCulture, @" try {{ $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) {{ $PSBoundParameters['OutBuffer'] = 1 }} $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($PSCmdlet) }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType, commandOrigin ); } else { result = string.Format(CultureInfo.InvariantCulture, @" try {{ $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType, commandOrigin ); } return result; } internal string GetProcessBlock() { return @" try { $steppablePipeline.Process($_) } catch { throw } "; } internal string GetDynamicParamBlock() { return string.Format(CultureInfo.InvariantCulture, @" try {{ $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}, $PSBoundParameters) $dynamicParams = @($targetCmd.Parameters.GetEnumerator() | Microsoft.PowerShell.Core\Where-Object {{ $_.Value.IsDynamic }}) if ($dynamicParams.Length -gt 0) {{ $paramDictionary = [Management.Automation.RuntimeDefinedParameterDictionary]::new() foreach ($param in $dynamicParams) {{ $param = $param.Value if(-not $MyInvocation.MyCommand.Parameters.ContainsKey($param.Name)) {{ $dynParam = [Management.Automation.RuntimeDefinedParameter]::new($param.Name, $param.ParameterType, $param.Attributes) $paramDictionary.Add($param.Name, $dynParam) }} }} return $paramDictionary }} }} catch {{ throw }} ", CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), _wrappedCommandType); } internal string GetEndBlock() { return @" try { $steppablePipeline.End() } catch { throw } "; } #endregion #region Helper methods for restricting commands needed by implicit and interactive remoting internal const string isSafeNameOrIdentifierRegex = @"^[-._:\\\p{Ll}\p{Lu}\p{Lt}\p{Lo}\p{Nd}\p{Lm}]{1,100}$"; private static CommandMetadata GetRestrictedCmdlet(string cmdletName, string defaultParameterSet, string helpUri, params ParameterMetadata[] parameters) { Dictionary<string, ParameterMetadata> parametersDictionary = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (ParameterMetadata parameter in parameters) { parametersDictionary.Add(parameter.Name, parameter); } // isProxyForCmdlet: // 1a. we would want to set it to false to get rid of unused common parameters // (like OutBuffer - see bug Windows 7: #402213) // 1b. otoh common parameters are going to be present anyway on all proxy functions // that the host generates for its cmdlets that need cmdletbinding, so // we should make sure that common parameters are safe, not hide them // 2. otoh without cmdletbinding() unspecified parameters get bound to $null which might // unnecessarily trigger validation attribute failures - see bug Windows 7: #477218 CommandMetadata metadata = new CommandMetadata( name: cmdletName, commandType: CommandTypes.Cmdlet, isProxyForCmdlet: true, defaultParameterSetName: defaultParameterSet, supportsShouldProcess: false, confirmImpact: ConfirmImpact.None, supportsPaging: false, supportsTransactions: false, positionalBinding: true, parameters: parametersDictionary); metadata.HelpUri = helpUri; return metadata; } private static CommandMetadata GetRestrictedGetCommand() { // remote Get-Command called by Import/Export-PSSession to get metadata for remote commands that user wants to import // remote Get-Command is also called by interactive remoting before entering the remote session to verify // that Out-Default and Exit-PSSession commands are present in the remote session // value passed directly from Import-PSSession -CommandName to Get-Command -Name // can't really restrict beyond basics ParameterMetadata nameParameter = new ParameterMetadata("Name", typeof(string[])); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); nameParameter.Attributes.Add(new ValidateCountAttribute(0, 1000)); // value passed directly from Import-PSSession -PSSnapIn to Get-Command -Module // can't really restrict beyond basics ParameterMetadata moduleParameter = new ParameterMetadata("Module", typeof(string[])); moduleParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); moduleParameter.Attributes.Add(new ValidateCountAttribute(0, 100)); // value passed directly from Import-PSSession -ArgumentList to Get-Command -ArgumentList // can't really restrict beyond basics ParameterMetadata argumentListParameter = new ParameterMetadata("ArgumentList", typeof(object[])); argumentListParameter.Attributes.Add(new ValidateCountAttribute(0, 100)); // value passed directly from Import-PSSession -CommandType to Get-Command -CommandType // can't really restrict beyond basics ParameterMetadata commandTypeParameter = new ParameterMetadata("CommandType", typeof(CommandTypes)); // we do allow -ListImported switch ParameterMetadata listImportedParameter = new ParameterMetadata("ListImported", typeof(SwitchParameter)); // Need to expose ShowCommandInfo parameter for remote ShowCommand support. ParameterMetadata showCommandInfo = new ParameterMetadata("ShowCommandInfo", typeof(SwitchParameter)); return GetRestrictedCmdlet( "Get-Command", null, // defaultParameterSet "http://go.microsoft.com/fwlink/?LinkID=113309", // helpUri nameParameter, moduleParameter, argumentListParameter, commandTypeParameter, listImportedParameter, showCommandInfo); } private static CommandMetadata GetRestrictedGetFormatData() { // remote Get-FormatData called by Import/Export-PSSession to get F&O metadata from remote session // value passed directly from Import-PSSession -FormatTypeName to Get-FormatData -TypeName // can't really restrict beyond basics ParameterMetadata typeNameParameter = new ParameterMetadata("TypeName", typeof(string[])); typeNameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); typeNameParameter.Attributes.Add(new ValidateCountAttribute(0, 1000)); return GetRestrictedCmdlet("Get-FormatData", null, "http://go.microsoft.com/fwlink/?LinkID=144303", typeNameParameter); } private static CommandMetadata GetRestrictedGetHelp() { // remote Get-Help is called when help for implicit remoting proxy tries to fetch help content for a remote command // This should only be called with 1 "safe" command name (unless ipsn is called with -Force) // (it seems ok to disallow getting help for "unsafe" commands [possible when ipsn is called with -Force] // - host can always generate its own proxy for Get-Help if it cares about "unsafe" command names) ParameterMetadata nameParameter = new ParameterMetadata("Name", typeof(string)); nameParameter.Attributes.Add(new ValidatePatternAttribute(isSafeNameOrIdentifierRegex)); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); // This should only be called with 1 valid category ParameterMetadata categoryParameter = new ParameterMetadata("Category", typeof(string[])); categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames(typeof(HelpCategory)))); categoryParameter.Attributes.Add(new ValidateCountAttribute(0, 1)); return GetRestrictedCmdlet("Get-Help", null, "http://go.microsoft.com/fwlink/?LinkID=113316", nameParameter, categoryParameter); } private static CommandMetadata GetRestrictedSelectObject() { // remote Select-Object is called by Import/Export-PSSession to // 1) restrict what properties are serialized // 2) artificially increase serialization depth of selected properties (especially "Parameters" property) // only called with a fixed set of values string[] validPropertyValues = new string[] { "ModuleName", "Namespace", "OutputType", "Count", "HelpUri", "Name", "CommandType", "ResolvedCommandName", "DefaultParameterSet", "CmdletBinding", "Parameters" }; ParameterMetadata propertyParameter = new ParameterMetadata("Property", typeof(string[])); propertyParameter.Attributes.Add(new ValidateSetAttribute(validPropertyValues)); propertyParameter.Attributes.Add(new ValidateCountAttribute(1, validPropertyValues.Length)); // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Select-Object", null, "http://go.microsoft.com/fwlink/?LinkID=113387", propertyParameter, inputParameter); } private static CommandMetadata GetRestrictedMeasureObject() { // remote Measure-Object is called by Import/Export-PSSession to measure how many objects // it is going to receive and to display a nice progress bar // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Measure-Object", null, "http://go.microsoft.com/fwlink/?LinkID=113349", inputParameter); } private static CommandMetadata GetRestrictedOutDefault() { // remote Out-Default is called by interactive remoting (without any parameters, only using pipelines to pass data) // needed for pipeline input if cmdlet binding has to be used (i.e. if Windows 7: #477218 is not fixed) ParameterMetadata inputParameter = new ParameterMetadata("InputObject", typeof(object)); inputParameter.ParameterSets.Add( ParameterAttribute.AllParameterSets, new ParameterSetMetadata( int.MinValue, // not positional ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, null)); // no help message return GetRestrictedCmdlet("Out-Default", null, "http://go.microsoft.com/fwlink/?LinkID=113362", inputParameter); } private static CommandMetadata GetRestrictedExitPSSession() { // remote Exit-PSSession is not called by PowerShell, but is needed so that users // can exit an interactive remoting session return GetRestrictedCmdlet("Exit-PSSession", null, "http://go.microsoft.com/fwlink/?LinkID=135210"); // no parameters are used } /// <summary> /// Returns a dictionary from a command name to <see cref="CommandMetadata"/> describing /// how that command can be restricted to limit attack surface while still being usable /// by features included in <paramref name="sessionCapabilities"/>. /// /// For example the implicit remoting feature /// (included in <see cref="SessionCapabilities.RemoteServer"/>) /// doesn't use all parameters of Get-Help /// and uses only a limited set of argument values for the parameters it does use. /// /// <see cref="CommandMetadata"/> can be passed to <see cref="ProxyCommand.Create(CommandMetadata)"/> method to generate /// a body of a proxy function that forwards calls to the actual cmdlet, while exposing only the parameters /// listed in <see cref="CommandMetadata"/>. Exposing only the restricted proxy function while making /// the actual cmdlet and its aliases private can help in reducing attack surface of the remoting server. /// </summary> /// <returns></returns> /// <seealso cref="System.Management.Automation.Runspaces.InitialSessionState.CreateRestricted(SessionCapabilities)"/> public static Dictionary<string, CommandMetadata> GetRestrictedCommands(SessionCapabilities sessionCapabilities) { List<CommandMetadata> restrictedCommands = new List<CommandMetadata>(); // all remoting cmdlets need to be included for workflow scenarios as wel if (SessionCapabilities.RemoteServer == (sessionCapabilities & SessionCapabilities.RemoteServer)) { restrictedCommands.AddRange(GetRestrictedRemotingCommands()); } if (SessionCapabilities.WorkflowServer == (sessionCapabilities & SessionCapabilities.WorkflowServer)) { #if CORECLR // Workflow Not Supported On PowerShell Core throw PSTraceSource.NewNotSupportedException(ParserStrings.WorkflowNotSupportedInPowerShellCore); #else restrictedCommands.AddRange(GetRestrictedRemotingCommands()); restrictedCommands.AddRange(GetRestrictedJobCommands()); #endif } Dictionary<string, CommandMetadata> result = new Dictionary<string, CommandMetadata>(StringComparer.OrdinalIgnoreCase); foreach (CommandMetadata restrictedCommand in restrictedCommands) { result.Add(restrictedCommand.Name, restrictedCommand); } return result; } private static Collection<CommandMetadata> GetRestrictedRemotingCommands() { Collection<CommandMetadata> remotingCommands = new Collection<CommandMetadata> { GetRestrictedGetCommand(), GetRestrictedGetFormatData(), GetRestrictedSelectObject(), GetRestrictedGetHelp(), GetRestrictedMeasureObject(), GetRestrictedExitPSSession(), GetRestrictedOutDefault() }; return remotingCommands; } #if !CORECLR // Not referenced on CSS private static Collection<CommandMetadata> GetRestrictedJobCommands() { // all the job cmdlets take a Name parameter. This needs to be // restricted to safenames in order to allow only valid wildcards // construct the parameterset metadata ParameterSetMetadata nameParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata instanceIdParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata idParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata stateParameterSet = new ParameterSetMetadata(int.MinValue, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata commandParameterSet = new ParameterSetMetadata(int.MinValue, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata filterParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata jobParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.Mandatory, string.Empty); ParameterSetMetadata computerNameParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); ParameterSetMetadata locationParameterSet = new ParameterSetMetadata(0, ParameterSetMetadata.ParameterFlags.Mandatory | ParameterSetMetadata.ParameterFlags.ValueFromPipeline | ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); Dictionary<string, ParameterSetMetadata> parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.NameParameterSet, nameParameterSet); Collection<string> emptyCollection = new Collection<string>(); ParameterMetadata nameParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.NameParameter, parameterSets, typeof(string[])); nameParameter.Attributes.Add(new ValidatePatternAttribute(isSafeNameOrIdentifierRegex)); nameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); // all the other parameters can be safely allowed parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.InstanceIdParameterSet, instanceIdParameterSet); ParameterMetadata instanceIdParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.InstanceIdParameter, parameterSets, typeof(Guid[])); instanceIdParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.SessionIdParameterSet, idParameterSet); ParameterMetadata idParameter = new ParameterMetadata(emptyCollection, false, "Id", parameterSets, typeof(int[])); idParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.StateParameterSet, stateParameterSet); ParameterMetadata stateParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.StateParameter, parameterSets, typeof(JobState)); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.CommandParameterSet, commandParameterSet); ParameterMetadata commandParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.CommandParameter, parameterSets, typeof(string[])); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.FilterParameterSet, filterParameterSet); ParameterMetadata filterParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.FilterParameter, parameterSets, typeof(Hashtable)); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add(JobCmdletBase.JobParameter, jobParameterSet); ParameterMetadata jobParameter = new ParameterMetadata(emptyCollection, false, JobCmdletBase.JobParameter, parameterSets, typeof(Job[])); jobParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); parameterSets.Add("ComputerName", computerNameParameterSet); parameterSets.Add("Location", locationParameterSet); ParameterMetadata jobParameter2 = new ParameterMetadata(emptyCollection, false, JobCmdletBase.JobParameter, parameterSets, typeof(Job[])); // Start-Job is not really required since the user will be using the name // of the workflow to launch them Collection<CommandMetadata> restrictedJobCommands = new Collection<CommandMetadata>(); // Stop-Job cmdlet ParameterMetadata passThruParameter = new ParameterMetadata("PassThru", typeof(SwitchParameter)); ParameterMetadata anyParameter = new ParameterMetadata("Any", typeof(SwitchParameter)); CommandMetadata stopJob = GetRestrictedCmdlet("Stop-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=113413", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(stopJob); // Wait-Job cmdlet ParameterMetadata timeoutParameter = new ParameterMetadata("Timeout", typeof(int)); timeoutParameter.Attributes.Add(new ValidateRangeAttribute(-1, Int32.MaxValue)); CommandMetadata waitJob = GetRestrictedCmdlet("Wait-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=113422", nameParameter, instanceIdParameter, idParameter, jobParameter, stateParameter, filterParameter, anyParameter, timeoutParameter); restrictedJobCommands.Add(waitJob); // Get-Job cmdlet CommandMetadata getJob = GetRestrictedCmdlet("Get-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=113328", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, commandParameter); restrictedJobCommands.Add(getJob); // Receive-Job cmdlet parameterSets = new Dictionary<string, ParameterSetMetadata>(); computerNameParameterSet = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); parameterSets.Add("ComputerName", computerNameParameterSet); ParameterMetadata computerNameParameter = new ParameterMetadata(emptyCollection, false, "ComputerName", parameterSets, typeof(string[])); computerNameParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); computerNameParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); parameterSets = new Dictionary<string, ParameterSetMetadata>(); locationParameterSet = new ParameterSetMetadata(1, ParameterSetMetadata.ParameterFlags.ValueFromPipelineByPropertyName, string.Empty); parameterSets.Add("Location", locationParameterSet); ParameterMetadata locationParameter = new ParameterMetadata(emptyCollection, false, "Location", parameterSets, typeof(string[])); locationParameter.Attributes.Add(new ValidateLengthAttribute(0, 1000)); locationParameter.Attributes.Add(new ValidateNotNullOrEmptyAttribute()); ParameterMetadata norecurseParameter = new ParameterMetadata("NoRecurse", typeof(SwitchParameter)); ParameterMetadata keepParameter = new ParameterMetadata("Keep", typeof(SwitchParameter)); ParameterMetadata waitParameter = new ParameterMetadata("Wait", typeof(SwitchParameter)); ParameterMetadata writeEventsParameter = new ParameterMetadata("WriteEvents", typeof(SwitchParameter)); ParameterMetadata writeJobParameter = new ParameterMetadata("WriteJobInResults", typeof(SwitchParameter)); ParameterMetadata autoRemoveParameter = new ParameterMetadata("AutoRemoveJob", typeof(SwitchParameter)); CommandMetadata receiveJob = GetRestrictedCmdlet("Receive-Job", "Location", "http://go.microsoft.com/fwlink/?LinkID=113372", nameParameter, instanceIdParameter, idParameter, stateParameter, jobParameter2, computerNameParameter, locationParameter, norecurseParameter, keepParameter, waitParameter, writeEventsParameter, writeJobParameter, autoRemoveParameter); restrictedJobCommands.Add(receiveJob); // Remove-Job cmdlet ParameterMetadata forceParameter = new ParameterMetadata("Force", typeof(SwitchParameter)); CommandMetadata removeJob = GetRestrictedCmdlet("Remove-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=113377", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, forceParameter); restrictedJobCommands.Add(removeJob); // Suspend-Job cmdlet CommandMetadata suspendJob = GetRestrictedCmdlet("Suspend-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=210613", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(suspendJob); // Suspend-Job cmdlet CommandMetadata resumeJob = GetRestrictedCmdlet("Resume-Job", JobCmdletBase.SessionIdParameterSet, "http://go.microsoft.com/fwlink/?LinkID=210611", nameParameter, instanceIdParameter, idParameter, stateParameter, filterParameter, jobParameter, passThruParameter); restrictedJobCommands.Add(resumeJob); return restrictedJobCommands; } #endif #endregion #region Command Metadata cache /// <summary> /// The command metadata cache. This is separate from the parameterMetadata cache /// because it is specific to cmdlets. /// </summary> private static System.Collections.Concurrent.ConcurrentDictionary<string, CommandMetadata> s_commandMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary<string, CommandMetadata>(StringComparer.OrdinalIgnoreCase); #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; using System.Diagnostics; using System.Reflection; using System.Runtime.Serialization; using System.Xml; using System.Xml.Serialization; namespace SerializationTestTypes { public enum ComparisionType { DCS, POCO } #region ComparisionType passed as parameter /// <summary> /// A type which does not have DataContract,MessageContract,Serializable,does not implements ISerializable or does not implement IXmlSerializable is considered a POCO type /// While comparing POCO types, Non-public, readonly fields, ReadOnly/ WriteOnly properties and Non-public properties are ignored /// </summary> public static class ComparisonHelper { private const string LogMessage = "Comparing Type = {0} & Value = {1} with Type {2} & Value = {3}"; public static void CompareRecursively(object originalData, object deserializedData, bool approxComparisonForFloatingPointAnd64BitValues = false) { ComparisionType cmpType = ComparisionType.DCS; SerializationMechanism att = ComparisonHelper.GetSerializationMechanism(originalData); if (att.Equals(SerializationMechanism.POCO)) { cmpType = ComparisionType.POCO; } ComparisonHelper.CompareData(originalData, deserializedData, att, cmpType); } private static SerializationMechanism GetSerializationMechanism(object data) { if (data == null) return SerializationMechanism.POCO; SerializationMechanism att = SerializationMechanism.POCO; bool hasDataContractAttribute = data.GetType().GetCustomAttributes(typeof(DataContractAttribute), false).Length > 0; bool hasSerializableAttribute = data.GetType().IsSerializable; bool hasISerializable = typeof(ISerializable).IsAssignableFrom(data.GetType()); bool hasIXmlSerializable = typeof(IXmlSerializable).IsAssignableFrom(data.GetType()); if ( (!hasDataContractAttribute) && (!hasISerializable) && (!hasIXmlSerializable) && (!hasSerializableAttribute) ) { att = SerializationMechanism.POCO; } else { if (hasDataContractAttribute || hasIXmlSerializable) { att = SerializationMechanism.DataContractAttribute; } //CollectionDataContract is handled as part of DataContract containerTypeAttribute if (data.GetType().GetCustomAttributes(typeof(CollectionDataContractAttribute), false).Length > 0) { hasDataContractAttribute = true; } //ISerializable interface is handled as part of Serializable containerTypeAttribute //since if a type implements ISerializable it must be marked with [Serializable] attribute if (data.GetType().GetInterface("ISerializable") != null) { hasSerializableAttribute = true; } if (hasDataContractAttribute && hasISerializable) { att = SerializationMechanism.DataContractAttribute; } else if (hasDataContractAttribute == true && hasISerializable == false) { att = SerializationMechanism.DataContractAttribute; } else if (hasDataContractAttribute == false && (hasISerializable == true || hasSerializableAttribute == true)) { att = SerializationMechanism.SerializableAttribute; } } return att; } /// <summary> /// Throws an exception if mismatch is found /// </summary> /// <param name="originalData"></param> /// <param name="deserializedData"></param> private static void CompareData(object originalData, object deserializedData, SerializationMechanism containerTypeAttribute, ComparisionType cmpType) { if (originalData == null) // both are null, comparison succeeded { return; } if (originalData.GetType().Name.Equals(typeof(System.Runtime.Serialization.ExtensionDataObject).Name)) { return; } //Fail if only one of the objects is null if ((null == originalData) != (null == deserializedData)) { string message = string.Format("Comparision failed: Original data is {0}, deserialized data is {1}", originalData == null ? "null" : "not null", deserializedData == null ? "null" : "not null"); if (originalData != null) { message += string.Format("Contents of Original data are {0}", originalData.ToString()); } if (deserializedData != null) { message += string.Format("Contents of Deserialized data are {0}", deserializedData.ToString()); } throw new Exception(message); } if (originalData is IObjectReference) { //All IObjectReference types implement Equals method which compares the object returned by GetRealObject method bool result = originalData.Equals(deserializedData); if (!result) { throw new Exception("Comparision failed for type " + originalData.GetType().Name); } return; } //Return false if the type of the object is not same Type originalDataType = originalData.GetType(); Type deserializedDataType = deserializedData.GetType(); if (!originalDataType.Equals(deserializedDataType)) { throw new Exception(string.Format("Comparision failed : Original type {0} not same as deserialized type {1}", originalDataType.ToString(), deserializedDataType.ToString())); } object[] dataContractAttributes = originalDataType.GetCustomAttributes(typeof(DataContractAttribute), false); if (dataContractAttributes != null && dataContractAttributes.Length > 0) { DataContractAttribute dataContractAttribute = (DataContractAttribute)dataContractAttributes[0]; if (dataContractAttribute.IsReference) { return; } } MethodInfo equalsMethod = originalDataType.GetMethod("Equals", new Type[] { typeof(object) }); #region "new object()" if (originalDataType == typeof(object)) { return; // deserializedDataType == object as well; objects should be the same } #endregion #region String type else if (originalDataType.Equals(typeof(string))) { if (!originalData.Equals(deserializedData)) { throw new Exception(string.Format("Comparision failed: Original string data {0} is not same as deserialized string data {1}", originalData, deserializedData)); } } #endregion #region XML types else if (originalDataType.Equals(typeof(XmlElement)) || originalDataType.Equals(typeof(XmlNode))) { string originalDataXml = ((XmlNode)originalData).InnerXml; string deserializedDataXml = ((XmlNode)deserializedData).InnerXml; Trace.WriteLine(string.Format(LogMessage, originalDataType, originalDataXml, deserializedDataType, deserializedDataXml)); if (!originalDataXml.Equals(deserializedDataXml)) { throw new Exception(string.Format("Comparision failed: Original XML data ({0}) is not the same as the deserialized XML data ({1})", originalDataXml, deserializedDataXml)); } } #endregion #region Special types else if (originalDataType == typeof(DBNull)) { // only 1 possible value, DBNull.Value if ((((DBNull)originalData) == DBNull.Value) != (((DBNull)deserializedData) == DBNull.Value)) { throw new Exception(string.Format("Different instances of DBNull: original={0}, deserialized={1}", originalData, deserializedData)); } } else if (originalDataType.Equals(typeof(DateTime))) { if (!(((DateTime)originalData).ToUniversalTime().Equals(((DateTime)deserializedData).ToUniversalTime()))) { throw new Exception(string.Format("Comparision failed: Original Datetime ticks {0} is not same as deserialized Datetime ticks {1}", ((DateTime)originalData).Ticks.ToString(), ((DateTime)deserializedData).Ticks.ToString())); } } else if ( (originalDataType.Equals(typeof(TimeSpan))) || (originalDataType.Equals(typeof(Uri))) || (originalDataType.Equals(typeof(XmlQualifiedName))) || (originalDataType.Equals(typeof(Guid))) || (originalDataType.Equals(typeof(decimal))) || (originalDataType.Equals(typeof(DateTimeOffset))) ) { if (!originalData.Equals(deserializedData)) { throw new Exception(string.Format("Comparision failed : Original type data {0} is not same as deserialized type data {1}", originalData.ToString(), deserializedData.ToString())); } } #endregion #region Value Types else if (originalDataType.IsValueType) { //Value types can be Primitive types, Structs, Enums, Bool, User Defined Structs #region Primitive Types //Numeric types, bool if (originalDataType.IsPrimitive) { bool different = !originalData.Equals(deserializedData); if (different) { throw new Exception(string.Format("Comparision failed: Original primitive data {0} is not same as deserialized primitive data {1}", originalData.ToString(), deserializedData.ToString())); } } #endregion #region Enum type else if (originalDataType.IsEnum) { SerializationMechanism enumAttribute = GetSerializationMechanism(originalData); //Verify member is marked with EnumMember attribute and compare the value with the Value property of the enum if (enumAttribute.Equals(SerializationMechanism.DataContractAttribute)) { if (ComparisonHelper.IsMemberMarkedWithEnumMember(originalData, cmpType)) { //Verify this will work for all scenarios if (!originalData.ToString().Equals(deserializedData.ToString())) { throw new Exception(string.Format("Comparision failed: Original enum data {0} is not same as deserialized enum data {1}", originalData.ToString(), deserializedData.ToString())); } } } } #endregion //If not a Primitive and Enum, it has to be a struct #region User defined structs else { #region Compare Fields ComparisonHelper.CompareFields(originalData, deserializedData, containerTypeAttribute, cmpType); #endregion #region Compare properties ComparisonHelper.CompareProperties(originalData, deserializedData, containerTypeAttribute, cmpType); #endregion } #endregion } #endregion #region Types which know how to compare themselves else if (equalsMethod.DeclaringType == originalData.GetType()) { // the type knows how to compare itself, we'll use it if (!originalData.Equals(deserializedData)) { throw new Exception(string.Format("Comparision failed: Original type data {0} is not same as deserialized type data {1}", originalData.ToString(), deserializedData.ToString())); } } #endregion #region IDictionary and IDictionary<T> //Compares generic as well as non-generic dictionary types //Hashtables else if (originalData is IDictionary) { if (deserializedData is IDictionary) { IDictionaryEnumerator originalDataEnum = ((IDictionary)originalData).GetEnumerator(); IDictionaryEnumerator deserializedDataEnum = ((IDictionary)deserializedData).GetEnumerator(); while (originalDataEnum.MoveNext()) { deserializedDataEnum.MoveNext(); DictionaryEntry originalEntry = originalDataEnum.Entry; DictionaryEntry deserializedEntry = deserializedDataEnum.Entry; //Compare the keys and then the values CompareData(originalEntry.Key, deserializedEntry.Key, containerTypeAttribute, cmpType); CompareData(originalEntry.Value, deserializedEntry.Value, containerTypeAttribute, cmpType); } } else { throw new Exception(string.Format("Comparision failed: Original IDictionary type {0} and deserialized IDictionary type {1} are not of same", originalDataType.GetType().ToString(), deserializedDataType.GetType().ToString())); } } #endregion #region IEnumerable,IList,ICollection,IEnumerable<t>,IList<T>,ICollection<T> //Array,Lists,Queues,Stacks etc else if (originalData is IEnumerable) { IEnumerator originalDataEnumerator = ((IEnumerable)originalData).GetEnumerator(); IEnumerator deserializedDataEnumerator = ((IEnumerable)deserializedData).GetEnumerator(); if (null != originalDataEnumerator && null != deserializedDataEnumerator) { while (originalDataEnumerator.MoveNext()) { deserializedDataEnumerator.MoveNext(); CompareData(originalDataEnumerator.Current, deserializedDataEnumerator.Current, containerTypeAttribute, cmpType); } } else { throw new Exception(string.Format("Comparision failed: Original type {0} and deserialized type {1} are not IEnumerable", originalDataType.GetType().ToString(), deserializedDataType.GetType().ToString())); } } #endregion #region Class else if (originalDataType.IsClass) { #region Compare Fields ComparisonHelper.CompareFields(originalData, deserializedData, containerTypeAttribute, cmpType); #endregion #region Compare properties ComparisonHelper.CompareProperties(originalData, deserializedData, containerTypeAttribute, cmpType); #endregion } #endregion } private static bool IsMemberMarkedWithEnumMember(object data, ComparisionType cmpType) { bool isEnumMember = false; //Non-public members are not serialized for POCO types BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; if (cmpType.Equals(ComparisionType.DCS)) { flag = flag | BindingFlags.NonPublic; } FieldInfo info = data.GetType().GetField(data.ToString(), flag); if (null != info) { isEnumMember = info.GetCustomAttributes(typeof(EnumMemberAttribute), false).Length > 0; } return isEnumMember; } /// <summary> /// Iterates through the properties and invokes compare method /// </summary> /// <param name="originalData"></param> /// <param name="deserializedData"></param> /// <param name="containerTypeAttribute"></param> private static void CompareProperties(object originalData, object deserializedData, SerializationMechanism containerTypeAttribute, ComparisionType cmpType) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; //Include private fields for DCS types if (cmpType.Equals(ComparisionType.DCS)) { flag = flag | BindingFlags.NonPublic; } foreach (System.Reflection.PropertyInfo property in originalData.GetType().GetProperties(flag)) { object newData = property.GetValue(originalData, null); SerializationMechanism fieldAttribute = ComparisonHelper.GetSerializationMechanism(newData); if (cmpType.Equals(ComparisionType.DCS)) { if (containerTypeAttribute.Equals(SerializationMechanism.DataContractAttribute)) { if ( (property.GetCustomAttributes(typeof(DataMemberAttribute), false).Length > 0) || (property.GetCustomAttributes(typeof(EnumMemberAttribute), false).Length > 0) ) { //Pass attribute of the complex type for furthur evaluation if (IsComplexType(newData)) { CompareData(newData, property.GetValue(deserializedData, null), fieldAttribute, cmpType); } else //Is a simple type { CompareData(newData, property.GetValue(deserializedData, null), containerTypeAttribute, cmpType); } } } else if (containerTypeAttribute.Equals(SerializationMechanism.SerializableAttribute)) { if (property.GetCustomAttributes(typeof(NonSerializedAttribute), false).Length == 0) { //Pass attribute of the complex type for furthur evaluation if (IsComplexType(newData)) { CompareData(newData, property.GetValue(deserializedData, null), fieldAttribute, cmpType); } else //Is a simple type, so pass Parents attribute { CompareData(newData, property.GetValue(deserializedData, null), containerTypeAttribute, cmpType); } } } } else if (cmpType.Equals(ComparisionType.POCO)) { //Ignore member with [IgnoreDataMember] attribute on a POCO type if (property.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).Length == 0) { //On POCO types, Properties which have both getter and setter will be serialized otherwise ignored if (property.CanRead && property.CanWrite) { //Pass attribute of the complex type for furthur evaluation if (IsComplexType(newData)) { CompareData(newData, property.GetValue(deserializedData, null), fieldAttribute, cmpType); } else //Is a simple type, so pass Parents attribute { CompareData(newData, property.GetValue(deserializedData, null), containerTypeAttribute, cmpType); } } else if (property.CanRead && !property.CanWrite) //Get-Only collection { //Pass attribute of the complex type for furthur evaluation if (IsComplexType(newData)) { CompareData(newData, property.GetValue(deserializedData, null), fieldAttribute, cmpType); } else //Is a simple type, so pass Parents attribute { CompareData(newData, property.GetValue(deserializedData, null), containerTypeAttribute, cmpType); } } } } } } /// <summary> /// </summary> /// <param name="data"></param> /// <returns></returns> public static bool IsComplexType(object data) { bool complexType = false; if (data == null) return false; if ( ((data.GetType().IsValueType) && (!data.GetType().IsPrimitive) && (!data.GetType().IsEnum)) || ((data.GetType().IsClass) && (!(data.GetType().Equals(typeof(string))) )) ) { complexType = true; } return complexType; } private static void CompareFields(object originalData, object deserializedData, SerializationMechanism containerTypeAttribute, ComparisionType cmpType) { //Compare fields //Non-public members are not serialized for POCO types BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static; if (cmpType.Equals(ComparisionType.DCS)) { flag = flag | BindingFlags.NonPublic; } foreach (System.Reflection.FieldInfo field in originalData.GetType().GetFields(flag)) { object newData = field.GetValue(originalData); SerializationMechanism fieldAttribute = GetSerializationMechanism(newData); if (cmpType.Equals(ComparisionType.DCS)) { if (containerTypeAttribute.Equals(SerializationMechanism.DataContractAttribute)) { if ( (field.GetCustomAttributes(typeof(DataMemberAttribute), false).Length > 0) || (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).Length > 0) ) { //Pass attribute of the complex type for furthur evaluation if (ComparisonHelper.IsComplexType(newData)) { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), fieldAttribute, cmpType); } else //Is a simple type { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), containerTypeAttribute, cmpType); } } } else if (containerTypeAttribute.Equals(SerializationMechanism.SerializableAttribute)) { //Do not compare [NonSerialized] members if (!field.IsNotSerialized) { if (ComparisonHelper.IsComplexType(newData)) { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), fieldAttribute, cmpType); } else //Is a simple type { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), containerTypeAttribute, cmpType); } } } } else if (cmpType.Equals(ComparisionType.POCO)) { //ReadOnly fields should be ignored for POCO type //Ignore member with [IgnoreDataMember] attribute on a POCO type if ((!field.IsInitOnly) && (field.GetCustomAttributes(typeof(IgnoreDataMemberAttribute), false).Length == 0)) { if (ComparisonHelper.IsComplexType(newData)) { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), fieldAttribute, cmpType); } else //Is a simple type { ComparisonHelper.CompareData(field.GetValue(originalData), field.GetValue(deserializedData), containerTypeAttribute, cmpType); } } } } } public static bool CompareDoubleApproximately(double d1, double d2) { if ((d1 < 0) != (d2 < 0)) return false; d1 = Math.Abs(d1); d2 = Math.Abs(d2); double max = Math.Max(d1, d2); double min = Math.Min(d1, d2); if (min == 0) return (max == 0); double difference = max - min; double ratio = difference / min; return (ratio < 0.0000001); } } public enum SerializationMechanism { POCO, DataContractAttribute, SerializableAttribute, } #endregion }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using System.Collections.Generic; using NPOI.OpenXmlFormats.Wordprocessing; using System.Xml; public class XWPFFootnote : IEnumerator<XWPFParagraph>, IBody { private List<XWPFParagraph> paragraphs = new List<XWPFParagraph>(); private List<XWPFTable> tables = new List<XWPFTable>(); private List<XWPFPictureData> pictures = new List<XWPFPictureData>(); private List<IBodyElement> bodyElements = new List<IBodyElement>(); private CT_FtnEdn ctFtnEdn; private XWPFFootnotes footnotes; public XWPFFootnote(CT_FtnEdn note, XWPFFootnotes xFootnotes) { footnotes = xFootnotes; ctFtnEdn = note; foreach (CT_P p in ctFtnEdn.GetPList()) { paragraphs.Add(new XWPFParagraph(p, this)); } } public XWPFFootnote(XWPFDocument document, CT_FtnEdn body) { if (null != body) { foreach (CT_P p in body.GetPList()) { paragraphs.Add(new XWPFParagraph(p, document)); } } } public IList<XWPFParagraph> Paragraphs { get { return paragraphs; } } public IEnumerator<XWPFParagraph> GetEnumerator() { return paragraphs.GetEnumerator(); } public IList<XWPFTable> Tables { get { return tables; } } public IList<XWPFPictureData> Pictures { get { return pictures; } } public IList<IBodyElement> BodyElements { get { return bodyElements; } } public CT_FtnEdn GetCTFtnEdn() { return ctFtnEdn; } public void SetCTFtnEdn(CT_FtnEdn footnote) { ctFtnEdn = footnote; } /// <summary> /// /// </summary> /// <param name="pos">position in table array</param> /// <returns>The table at position pos</returns> public XWPFTable GetTableArray(int pos) { if (pos > 0 && pos < tables.Count) { return tables[(pos)]; } return null; } /// <summary> /// inserts an existing XWPFTable to the arrays bodyElements and tables /// </summary> /// <param name="pos"></param> /// <param name="table"></param> public void InsertTable(int pos, XWPFTable table) { bodyElements.Insert(pos, table); int i; for (i = 0; i < ctFtnEdn.GetTblList().Count; i++) { CT_Tbl tbl = ctFtnEdn.GetTblArray(i); if(tbl == table.GetCTTbl()){ break; } } tables.Insert(i, table); } /** * if there is a corresponding {@link XWPFTable} of the parameter ctTable in the tableList of this header * the method will return this table * if there is no corresponding {@link XWPFTable} the method will return null * @param ctTable * @see NPOI.XWPF.UserModel.IBody#getTable(CTTbl ctTable) */ public XWPFTable GetTable(CT_Tbl ctTable) { foreach (XWPFTable table in tables) { if(table==null) return null; if(table.GetCTTbl().Equals(ctTable)) return table; } return null; } /** * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this header or footer * the method will return this paragraph * if there is no corresponding {@link XWPFParagraph} the method will return null * @param p is instance of CTP and is searching for an XWPFParagraph * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this header or footer * XWPFParagraph with the correspondig CTP p * @see NPOI.XWPF.UserModel.IBody#getParagraph(CTP p) */ public XWPFParagraph GetParagraph(CT_P p) { foreach (XWPFParagraph paragraph in paragraphs) { if(paragraph.GetCTP().Equals(p)) return paragraph; } return null; } /// <summary> /// Returns the paragraph that holds the text of the header or footer. /// </summary> /// <param name="pos"></param> /// <returns></returns> public XWPFParagraph GetParagraphArray(int pos) { return paragraphs[pos]; } /// <summary> /// Get the TableCell which belongs to the TableCell /// </summary> /// <param name="cell"></param> /// <returns></returns> public XWPFTableCell GetTableCell(CT_Tc cell) { object obj = cell.Parent; if (!(obj is CT_Row)) return null; CT_Row row = (CT_Row)obj; if (!(row.Parent is CT_Tbl)) return null; CT_Tbl tbl = (CT_Tbl)row.Parent; XWPFTable table = GetTable(tbl); if(table == null){ return null; } XWPFTableRow tableRow = table.GetRow(row); if(row == null){ return null; } return tableRow.GetTableCell(cell); } /** * verifies that cursor is on the right position * @param cursor */ private bool IsCursorInFtn(/*XmlCursor*/XmlDocument cursor) { /*XmlCursor verify = cursor.NewCursor(); verify.ToParent(); if(verify.Object == this.ctFtnEdn){ return true; } return false;*/ throw new NotImplementedException(); } public POIXMLDocumentPart Owner { get { return footnotes; } } /** * * @param cursor * @return the inserted table * @see NPOI.XWPF.UserModel.IBody#insertNewTbl(XmlCursor cursor) */ public XWPFTable InsertNewTbl(/*XmlCursor*/XmlDocument cursor) { /*if(isCursorInFtn(cursor)){ String uri = CTTbl.type.Name.NamespaceURI; String localPart = "tbl"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTTbl t = (CTTbl)cursor.Object; XWPFTable newT = new XWPFTable(t, this); cursor.RemoveXmlContents(); XmlObject o = null; while(!(o is CTTbl)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if(!(o is CTTbl)){ tables.Add(0, newT); } else{ int pos = tables.IndexOf(getTable((CTTbl)o))+1; tables.Add(pos,newT); } int i=0; cursor = t.NewCursor(); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newT); cursor = t.NewCursor(); cursor.ToEndToken(); return newT; } return null;*/ throw new NotImplementedException(); } /** * add a new paragraph at position of the cursor * @param cursor * @return the inserted paragraph * @see NPOI.XWPF.UserModel.IBody#insertNewParagraph(XmlCursor cursor) */ public XWPFParagraph InsertNewParagraph(/*XmlCursor*/XmlDocument cursor) { /*if(isCursorInFtn(cursor)){ String uri = CTP.type.Name.NamespaceURI; String localPart = "p"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTP p = (CTP)cursor.Object; XWPFParagraph newP = new XWPFParagraph(p, this); XmlObject o = null; while(!(o is CTP)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if((!(o is CTP)) || (CTP)o == p){ paragraphs.Add(0, newP); } else{ int pos = paragraphs.IndexOf(getParagraph((CTP)o))+1; paragraphs.Add(pos,newP); } int i=0; cursor.ToCursor(p.NewCursor()); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newP); cursor.ToCursor(p.NewCursor()); cursor.ToEndToken(); return newP; } return null;*/ throw new NotImplementedException(); } /** * add a new table to the end of the footnote * @param table * @return the Added XWPFTable */ public XWPFTable AddNewTbl(CT_Tbl table) { CT_Tbl newTable = ctFtnEdn.AddNewTbl(); newTable.Set(table); XWPFTable xTable = new XWPFTable(newTable, this); tables.Add(xTable); return xTable; } /** * add a new paragraph to the end of the footnote * @param paragraph * @return the Added XWPFParagraph */ public XWPFParagraph AddNewParagraph(CT_P paragraph) { CT_P newPara = ctFtnEdn.AddNewP(paragraph); //newPara.Set(paragraph); XWPFParagraph xPara = new XWPFParagraph(newPara, this); paragraphs.Add(xPara); return xPara; } /** * @see NPOI.XWPF.UserModel.IBody#getXWPFDocument() */ public XWPFDocument GetXWPFDocument() { return footnotes.GetXWPFDocument(); } /** * returns the Part, to which the body belongs, which you need for Adding relationship to other parts * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart GetPart() { return footnotes; } /** * Get the PartType of the body * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return BodyType.FOOTNOTE; } } public XWPFParagraph Current { get { throw new NotImplementedException(); } } public void Dispose() { throw new NotImplementedException(); } object System.Collections.IEnumerator.Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.Format { using System; using System.Text; using System.Collections.Generic; using System.Text.RegularExpressions; /** * This class : printing out an elapsed time format. * * @author Ken Arnold, Industrious Media LLC */ public class CellElapsedFormatter : CellFormatter { private List<TimeSpec> specs; private TimeSpec topmost; private String printfFmt; private static readonly Regex PERCENTS = new Regex("%"); private const double HOUR__FACTOR = 1.0 / 24.0; private const double MIN__FACTOR = HOUR__FACTOR / 60.0; private const double SEC__FACTOR = MIN__FACTOR / 60.0; private class TimeSpec { internal char type; internal int pos; internal int len; internal double factor; internal double modBy; public TimeSpec(char type, int pos, int len, double factor) { this.type = type; this.pos = pos; this.len = len; this.factor = factor; modBy = 0; } public long ValueFor(double elapsed) { double val; if (modBy == 0) val = elapsed / factor; else val = elapsed / factor % modBy; if (type == '0') return (long)Math.Round(val); else return (long)val; } } private class ElapsedPartHandler : CellFormatPart.IPartHandler { public ElapsedPartHandler(CellElapsedFormatter formatter) { this._formatter = formatter; } // This is the one class that's directly using printf, so it can't use // the default handling for quoted strings and special characters. The // only special character for this is '%', so we have to handle all the // quoting in this method ourselves. private CellElapsedFormatter _formatter; public String HandlePart(Match m, String part, CellFormatType type, StringBuilder desc) { int pos = desc.Length; char firstCh = part[0]; switch (firstCh) { case '[': if (part.Length < 3) break; if (_formatter.topmost != null) throw new ArgumentException( "Duplicate '[' times in format"); part = part.ToLower(); int specLen = part.Length - 2; _formatter.topmost = _formatter.AssignSpec(part[1], pos, specLen); return part.Substring(1, specLen); case 'h': case 'm': case 's': case '0': part = part.ToLower(); _formatter.AssignSpec(part[0], pos, part.Length); return part; case '\n': return "%n"; case '\"': part = part.Substring(1, part.Length - 2); break; case '\\': part = part.Substring(1); break; case '*': if (part.Length > 1) part = CellFormatPart.ExpandChar(part); break; // An escape we can let it handle because it can't have a '%' case '_': return null; } // Replace ever "%" with a "%%" so we can use printf //return PERCENTS.Matcher(part).ReplaceAll("%%"); //return PERCENTS.Replace(part, "%%"); return part; } } /** * Creates a elapsed time formatter. * * @param pattern The pattern to Parse. */ public CellElapsedFormatter(String pattern) : base(pattern) { specs = new List<TimeSpec>(); StringBuilder desc = CellFormatPart.ParseFormat(pattern, CellFormatType.ELAPSED, new ElapsedPartHandler(this)); //ListIterator<TimeSpec> it = specs.ListIterator(specs.Count); //while (it.HasPrevious()) for(int i=specs.Count-1;i>=0;i--) { //TimeSpec spec = it.Previous(); TimeSpec spec = specs[i]; //desc.Replace(spec.pos, spec.pos + spec.len, "%0" + spec.len + "d"); desc.Remove(spec.pos, spec.len); desc.Insert(spec.pos, "D" + spec.len); if (spec.type != topmost.type) { spec.modBy = modFor(spec.type, spec.len); } } printfFmt = desc.ToString(); } private TimeSpec AssignSpec(char type, int pos, int len) { TimeSpec spec = new TimeSpec(type, pos, len, factorFor(type, len)); specs.Add(spec); return spec; } private static double factorFor(char type, int len) { switch (type) { case 'h': return HOUR__FACTOR; case 'm': return MIN__FACTOR; case 's': return SEC__FACTOR; case '0': return SEC__FACTOR / Math.Pow(10, len); default: throw new ArgumentException( "Uknown elapsed time spec: " + type); } } private static double modFor(char type, int len) { switch (type) { case 'h': return 24; case 'm': return 60; case 's': return 60; case '0': return Math.Pow(10, len); default: throw new ArgumentException( "Uknown elapsed time spec: " + type); } } /** {@inheritDoc} */ public override void FormatValue(StringBuilder toAppendTo, Object value) { double elapsed = ((double)value); if (elapsed < 0) { toAppendTo.Append('-'); elapsed = -elapsed; } long[] parts = new long[specs.Count]; for (int i = 0; i < specs.Count; i++) { parts[i] = specs[(i)].ValueFor(elapsed); } //Formatter formatter = new Formatter(toAppendTo); //formatter.Format(printfFmt, parts); string[] fmtPart = printfFmt.Split(":. []".ToCharArray()); string split = string.Empty; int pos = 0; int index = 0; Regex regFmt = new Regex("D\\d+"); foreach (string fmt in fmtPart) { pos += fmt.Length; if (pos < printfFmt.Length) { split = printfFmt[pos].ToString(); pos++; } else split = string.Empty; if (regFmt.IsMatch(fmt)) { toAppendTo.Append(parts[index].ToString(fmt)).Append(split); index++; } else { toAppendTo.Append(fmt).Append(split); } } //throw new NotImplementedException(); } /** * {@inheritDoc} * <p/> * For a date, this is <tt>"mm/d/y"</tt>. */ public override void SimpleValue(StringBuilder toAppendTo, Object value) { FormatValue(toAppendTo, 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; using System.Xml; using System.Collections.Generic; using System.Globalization; namespace System.Runtime.Serialization { public sealed class ExtensionDataObject { private IList<ExtensionDataMember> _members; #if USE_REFEMIT || NET_NATIVE public ExtensionDataObject() #else internal ExtensionDataObject() #endif { } #if USE_REFEMIT || NET_NATIVE public IList<ExtensionDataMember> Members #else internal IList<ExtensionDataMember> Members #endif { get { return _members; } set { _members = value; } } } #if USE_REFEMIT || NET_NATIVE public class ExtensionDataMember #else internal class ExtensionDataMember #endif { private string _name; private string _ns; private IDataNode _value; private int _memberIndex; public string Name { get { return _name; } set { _name = value; } } public string Namespace { get { return _ns; } set { _ns = value; } } public IDataNode Value { get { return _value; } set { _value = value; } } public int MemberIndex { get { return _memberIndex; } set { _memberIndex = value; } } } #if USE_REFEMIT || NET_NATIVE public interface IDataNode #else internal interface IDataNode #endif { Type DataType { get; } object Value { get; set; } // boxes for primitives string DataContractName { get; set; } string DataContractNamespace { get; set; } string ClrTypeName { get; set; } string ClrAssemblyName { get; set; } string Id { get; set; } bool PreservesReferences { get; } // NOTE: consider moving below APIs to DataNode<T> if IDataNode API is made public void GetData(ElementData element); bool IsFinalValue { get; set; } void Clear(); } internal class DataNode<T> : IDataNode { protected Type dataType; private T _value; private string _dataContractName; private string _dataContractNamespace; private string _clrTypeName; private string _clrAssemblyName; private string _id = Globals.NewObjectId; private bool _isFinalValue; internal DataNode() { this.dataType = typeof(T); _isFinalValue = true; } internal DataNode(T value) : this() { _value = value; } public Type DataType { get { return dataType; } } public object Value { get { return _value; } set { _value = (T)value; } } bool IDataNode.IsFinalValue { get { return _isFinalValue; } set { _isFinalValue = value; } } public T GetValue() { return _value; } #if NotUsed public void SetValue(T value) { this.value = value; } #endif public string DataContractName { get { return _dataContractName; } set { _dataContractName = value; } } public string DataContractNamespace { get { return _dataContractNamespace; } set { _dataContractNamespace = value; } } public string ClrTypeName { get { return _clrTypeName; } set { _clrTypeName = value; } } public string ClrAssemblyName { get { return _clrAssemblyName; } set { _clrAssemblyName = value; } } public bool PreservesReferences { get { return (Id != Globals.NewObjectId); } } public string Id { get { return _id; } set { _id = value; } } public virtual void GetData(ElementData element) { element.dataNode = this; element.attributeCount = 0; element.childElementIndex = 0; if (DataContractName != null) AddQualifiedNameAttribute(element, Globals.XsiPrefix, Globals.XsiTypeLocalName, Globals.SchemaInstanceNamespace, DataContractName, DataContractNamespace); if (ClrTypeName != null) element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrTypeLocalName, ClrTypeName); if (ClrAssemblyName != null) element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ClrAssemblyLocalName, ClrAssemblyName); } public virtual void Clear() { // dataContractName not cleared because it is used when re-serializing from unknown data _clrTypeName = _clrAssemblyName = null; } internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs) { string prefix = ExtensionDataReader.GetPrefix(valueNs); element.AddAttribute(elementPrefix, elementNs, elementName, String.Format(CultureInfo.InvariantCulture, "{0}:{1}", prefix, valueName)); bool prefixDeclaredOnElement = false; if (element.attributes != null) { for (int i = 0; i < element.attributes.Length; i++) { AttributeData attribute = element.attributes[i]; if (attribute != null && attribute.prefix == Globals.XmlnsPrefix && attribute.localName == prefix) { prefixDeclaredOnElement = true; break; } } } if (!prefixDeclaredOnElement) element.AddAttribute(Globals.XmlnsPrefix, Globals.XmlnsNamespace, prefix, valueNs); } } internal class ClassDataNode : DataNode<object> { private IList<ExtensionDataMember> _members; internal ClassDataNode() { dataType = Globals.TypeOfClassDataNode; } internal IList<ExtensionDataMember> Members { get { return _members; } set { _members = value; } } public override void Clear() { base.Clear(); _members = null; } } internal class XmlDataNode : DataNode<object> { private IList<XmlAttribute> _xmlAttributes; private IList<XmlNode> _xmlChildNodes; private XmlDocument _ownerDocument; internal XmlDataNode() { dataType = Globals.TypeOfXmlDataNode; } internal IList<XmlAttribute> XmlAttributes { get { return _xmlAttributes; } set { _xmlAttributes = value; } } internal IList<XmlNode> XmlChildNodes { get { return _xmlChildNodes; } set { _xmlChildNodes = value; } } internal XmlDocument OwnerDocument { get { return _ownerDocument; } set { _ownerDocument = value; } } public override void Clear() { base.Clear(); _xmlAttributes = null; _xmlChildNodes = null; _ownerDocument = null; } } internal class CollectionDataNode : DataNode<Array> { private IList<IDataNode> _items; private string _itemName; private string _itemNamespace; private int _size = -1; internal CollectionDataNode() { dataType = Globals.TypeOfCollectionDataNode; } internal IList<IDataNode> Items { get { return _items; } set { _items = value; } } internal string ItemName { get { return _itemName; } set { _itemName = value; } } internal string ItemNamespace { get { return _itemNamespace; } set { _itemNamespace = value; } } internal int Size { get { return _size; } set { _size = value; } } public override void GetData(ElementData element) { base.GetData(element); element.AddAttribute(Globals.SerPrefix, Globals.SerializationNamespace, Globals.ArraySizeLocalName, Size.ToString(NumberFormatInfo.InvariantInfo)); } public override void Clear() { base.Clear(); _items = null; _size = -1; } } internal class ISerializableDataNode : DataNode<object> { private string _factoryTypeName; private string _factoryTypeNamespace; private IList<ISerializableDataMember> _members; internal ISerializableDataNode() { dataType = Globals.TypeOfISerializableDataNode; } internal string FactoryTypeName { get { return _factoryTypeName; } set { _factoryTypeName = value; } } internal string FactoryTypeNamespace { get { return _factoryTypeNamespace; } set { _factoryTypeNamespace = value; } } internal IList<ISerializableDataMember> Members { get { return _members; } set { _members = value; } } public override void GetData(ElementData element) { base.GetData(element); if (FactoryTypeName != null) AddQualifiedNameAttribute(element, Globals.SerPrefix, Globals.ISerializableFactoryTypeLocalName, Globals.SerializationNamespace, FactoryTypeName, FactoryTypeNamespace); } public override void Clear() { base.Clear(); _members = null; _factoryTypeName = _factoryTypeNamespace = null; } } internal class ISerializableDataMember { private string _name; private IDataNode _value; internal string Name { get { return _name; } set { _name = value; } } internal IDataNode Value { get { return _value; } set { _value = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SPL3D { class Octtree<T> where T : Cube { private int level; private Cube bounds; private List<T> objects; private Octtree<T>[] nodes; private readonly int MAX_OBJECTS = 10; private readonly int MAX_LEVELS = 10; public Octtree(int level,Cube bounds) { this.level = level; this.bounds = bounds; objects = new List<T>(); nodes = new Octtree<T>[8]; } public void Clear() { objects.Clear(); for (int i = 0; i < 4; ++i) { if (nodes[i] != null) { nodes[i].Clear(); nodes[i] = null; } } } private void Split() { int subWidth = (bounds.Width / 4); int subHeight = (bounds.Height / 4); int subDepth = (bounds.Depth / 4); int x = bounds.X; int y = bounds.Y; int z = bounds.Z; //Forward Top Left nodes[0] = new Octtree<T>(level + 1, new Cube(x - subWidth, y + subHeight, z+subDepth, subWidth, subHeight, subDepth)); //Forward Top Right nodes[1] = new Octtree<T>(level + 1, new Cube(x + subWidth, y + subHeight, z+subDepth, subWidth, subHeight, subDepth)); //Forward Bottom Left nodes[2] = new Octtree<T>(level + 1, new Cube(x - subWidth, y - subHeight, z+subDepth, subWidth, subHeight, subDepth)); //Forward Bottom Right nodes[3] = new Octtree<T>(level + 1, new Cube(x + subWidth, y - subHeight, z+subDepth, subWidth, subHeight, subDepth)); //Back Top Left nodes[4] = new Octtree<T>(level + 1, new Cube(x - subWidth, y + subHeight, z-subDepth, subWidth, subHeight, subDepth)); //Back Top Right nodes[5] = new Octtree<T>(level + 1, new Cube(x + subWidth, y + subHeight, z-subDepth, subWidth, subHeight, subDepth)); //Back Bottom Left nodes[6] = new Octtree<T>(level + 1, new Cube(x - subWidth, y - subHeight, z-subDepth, subWidth, subHeight, subDepth)); //Back Bottom Right nodes[7] = new Octtree<T>(level + 1, new Cube(x + subWidth, y - subHeight, z-subDepth, subWidth, subHeight, subDepth)); } /* * Determine which node the object belongs to. -1 means * object cannot completely fit within a child node and is part * of the parent node */ private int GetIndex(T obj) { int index = -1; double verticalMidpoint = bounds.Y; double horizontalMidpoint = bounds.X; double depthicalMidpoint = bounds.Z; int subWidth = (obj.Width / 2); int subHeight = (obj.Height / 2); int subDepth = (obj.Depth / 2); //Object is above z=0 bool forwardOctrant = (obj.Z - subDepth > depthicalMidpoint) && (obj.Z + subDepth > depthicalMidpoint); //Object in below z=0 bool backOctrant = (obj.Z - subDepth < depthicalMidpoint) && (obj.Z + subDepth < depthicalMidpoint); //Object is above y=0 bool topQuadrant = (obj.Y - subHeight > verticalMidpoint) && (obj.Y + subHeight > verticalMidpoint); //Object is below y=0 bool bottomQuadrant = (obj.Y + subHeight < verticalMidpoint) && (obj.Y - subHeight < verticalMidpoint); //Object is below x=0 bool leftQuadrant = (obj.X - subWidth < horizontalMidpoint) && (obj.X + subWidth < horizontalMidpoint); //Object is above x=0 bool rightQuadrant = (obj.X - subWidth > horizontalMidpoint) && (obj.X + subWidth > horizontalMidpoint); if (backOctrant) { if (topQuadrant) { if (leftQuadrant) { index = 0; } else if (rightQuadrant) { index = 1; } } else if (bottomQuadrant) { if (leftQuadrant) { index = 2; } else if (rightQuadrant) { index = 3; } } } else if(forwardOctrant) { if (topQuadrant) { if (leftQuadrant) { index = 4; } else if (rightQuadrant) { index = 5; } } else if (bottomQuadrant) { if (leftQuadrant) { index = 6; } else if (rightQuadrant) { index = 7; } } } return index; } /* * Insert the object into the quadtree. If the node * exceeds the capacity, it will split and add all * objects to their corresponding nodes. */ public void Insert(T obj) { if (nodes[0] != null) { int index = GetIndex(obj); if (index != -1) { nodes[index].Insert(obj); return; } } objects.Add(obj); if (objects.Count > MAX_OBJECTS && level<MAX_LEVELS) { if (nodes[0] == null) { Split(); } int i = 0; while (i < objects.Count) { int index = GetIndex(objects[i]); if (index != -1) { nodes[index].Insert(objects[i]); objects.Remove(objects[i]); } else { i++; } } } } /* * Return all objects that could collide with the given object */ public List<T> Retrieve(List<T> returnObjects,T obj) { int index = GetIndex(obj); if (index != -1 && nodes[0] != null) { nodes[index].Retrieve(returnObjects, obj); } foreach(T o in objects) { returnObjects.Add(o); } return returnObjects; } public override string ToString() { String result = "\n"; for (int i = 0; i < level; ++i) { result += "\t"; } result += "level: " + level; result += " x: " + bounds.X + " y: " + bounds.Y; foreach(T obj in objects) { result += "\n"; for (int i = 0; i < level; ++i) { result += "\t"; } result += obj.ToString(); } if (nodes[0] != null) { for (int i = 0; i < 4; ++i) { result+=nodes[i].ToString(); } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using ServiceStack.Caching; using ServiceStack.Data; using ServiceStack.MicrosoftGraph.ServiceModel; using ServiceStack.MicrosoftGraph.ServiceModel.Entities; using ServiceStack.MicrosoftGraph.ServiceModel.Interfaces; using ServiceStack.OrmLite; namespace ServiceStack.Azure.Auth { public class OrmLiteMultiTenantApplicationRegistryService : IApplicationRegistryService { #region Constants and Variables public class DirectoryRegistrationLookup { public long RegistryId { get; set; } public string Upn { get; set; } } public class ClientIdRegistrationLookup { public long RegistryId { get; set; } public string ClientId { get; set; } } private readonly IDbConnectionFactory _connectionFactory; private readonly ICacheClient _cacheClient; #endregion #region Constructors public OrmLiteMultiTenantApplicationRegistryService(IDbConnectionFactory connectionFactory, ICacheClient cacheClient) { _connectionFactory = connectionFactory; _cacheClient = cacheClient; } #endregion #region IApplicationRegistryService Members public bool ApplicationIsRegistered(string directoryName) { using (var db = _connectionFactory.OpenDbConnection()) { var loweredDomain = directoryName.ToLower(); var q = db.From<DirectoryUpn>() .Where(x => x.Suffix == loweredDomain); return db.Exists<DirectoryUpn>(q); } } public ApplicationRegistration GetApplicationByDirectoryName(string domain) { if (string.IsNullOrWhiteSpace(domain)) return null; var loweredDomain = domain.ToLower(); var dirLookup = _cacheClient.GetOrCreate(UrnId.Create(typeof(DirectoryRegistrationLookup), loweredDomain), () => { using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From<ApplicationRegistration>() .Join<ApplicationRegistration, DirectoryUpn>( (registration, upn) => registration.Id == upn.ApplicationRegistrationId) .Where<DirectoryUpn>(x => x.Suffix == loweredDomain) .Select<ApplicationRegistration>(x => x.Id); var id = db.Column<long>(q).FirstOrDefault(); return new DirectoryRegistrationLookup { RegistryId = id, Upn = loweredDomain }; } }); return ApplicationById(dirLookup.RegistryId); } private ApplicationRegistration ApplicationById(long id) { var reg = _cacheClient.GetOrCreate(UrnId.Create(typeof(ApplicationRegistration), id.ToString()), () => { using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From<ApplicationRegistration>() .Where(x => x.Id == id); return db.LoadSelect(q).FirstOrDefault(); } }); return reg; } public ApplicationRegistration GetApplicationById(string applicationId) { if (string.IsNullOrWhiteSpace(applicationId)) return null; // ClientIdRegistrationLookup var dirLookup = _cacheClient.GetOrCreate(UrnId.Create(typeof(ClientIdRegistrationLookup), applicationId), () => { using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From<ApplicationRegistration>() .Where(x => x.ClientId == applicationId) .Select<ApplicationRegistration>(x => x.Id); var id = db.Column<long>(q).FirstOrDefault(); return new ClientIdRegistrationLookup { RegistryId = id, ClientId = applicationId }; } }); return ApplicationById(dirLookup.RegistryId); } public ApplicationRegistration RegisterUpns(ApplicationRegistration registration, IEnumerable<string> upns) { if (registration == null) throw new ArgumentException($"Cannot update null or empty {nameof(ApplicationRegistration)}."); var utcNow = DateTimeOffset.UtcNow; var existing = registration.Upns?.Select(x => x.Suffix.ToLower()); var unique = upns.Where(x => !string.IsNullOrWhiteSpace(x) && !existing.Contains(x)) .Select(x => new DirectoryUpn { ApplicationRegistrationId = registration.Id, DateCreatedUtc = utcNow, Suffix = x.ToLower() }); using (var db = _connectionFactory.OpenDbConnection()) { db.InsertAll(unique); _cacheClient.RemoveAll(existing.Select(x => UrnId.Create(typeof(DirectoryRegistrationLookup), x))); _cacheClient.Remove(UrnId.Create(typeof(ApplicationRegistration), registration.Id.ToString())); // Return uncached version to avoid possible race returning invalid cached data. var q = db.From<ApplicationRegistration>() .Where(x => x.Id == registration.Id); return db.LoadSelect(q).FirstOrDefault(); } } public ApplicationRegistration RegisterApplication(ApplicationRegistration registration) { if (registration == null) throw new ArgumentException($"Cannot register null or empty {nameof(ApplicationRegistration)}."); if (string.IsNullOrWhiteSpace(registration.ClientId)) throw new ArgumentException("Parameter cannot be empty.", nameof(registration.ClientId)); if (string.IsNullOrWhiteSpace(registration.ClientSecret)) throw new ArgumentException("Parameter cannot be empty.", nameof(registration.ClientSecret)); if (registration.Upns?.Any() == false) { throw new ArgumentException("At least one upn must be specified to register an application."); } var duplicates = new List<string>(); registration.Upns.Each(upn => { upn.Suffix = upn.Suffix.ToLower(); upn.DateCreatedUtc = registration.DateCreatedUtc; duplicates.Add(upn.Suffix); }); long id; using (var db = _connectionFactory.OpenDbConnection()) { var existing = db.Select<DirectoryUpn>(x => duplicates.Contains(x.Suffix)); if (existing.Any()) { throw new InvalidOperationException($"Specified suffix(es) already registered: {string.Join(",", existing)}"); } db.Save(registration, true); id = registration.Id; } _cacheClient.RemoveAll(registration.Upns.Where(x => !string.IsNullOrWhiteSpace(x.Suffix)) .Select(x => x.Suffix.ToLower())); return ApplicationById(id); } // public ApplicationRegistration RegisterApplication(string applicationId, string publicKey, string directoryName, // long? refId, string refIdStr) // { // if (string.IsNullOrWhiteSpace(applicationId)) // throw new ArgumentException("Parameter cannot be empty.", nameof(applicationId)); // // if (string.IsNullOrWhiteSpace(publicKey)) // throw new ArgumentException("Parameter cannot be empty.", nameof(publicKey)); // // if (string.IsNullOrWhiteSpace(directoryName)) // throw new ArgumentException("Parameter cannot be empty.", nameof(directoryName)); // // // // using (var db = _connectionFactory.OpenDbConnection()) // { // var loweredDomain = directoryName.ToLower(); // if (db.Exists<ApplicationRegistration>(d => d.DirectoryName == loweredDomain)) // throw new InvalidOperationException($"Aad domain {directoryName} is already registered"); // var dir = new ApplicationRegistration // { // ClientId = applicationId, // ClientSecret = publicKey, // DirectoryName = directoryName, // RefId = refId, // RefIdStr = refIdStr, // AppTenantId = SequentialGuid.Create() // }; // db.Save(dir, true); // // return db.Single<ApplicationRegistration>(d => d.Id == dir.Id); // } // } public int GrantAdminConsent(string directoryName, string username) { if (string.IsNullOrWhiteSpace(directoryName)) throw new ArgumentException("Parameter cannot be empty.", nameof(directoryName)); if (string.IsNullOrWhiteSpace(username)) throw new ArgumentException("Parameter cannot be empty.", nameof(username)); var loweredDomain = directoryName.ToLower(); using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From<ApplicationRegistration>() .Join<ApplicationRegistration, DirectoryUpn>((registration, upn) => registration.Id == upn.ApplicationRegistrationId) .Where<DirectoryUpn>(x => x.Suffix == loweredDomain); var ar = db.Single<ApplicationRegistration>(q); ar.ConsentGrantedBy = username; ar.ConstentDateUtc = DateTimeOffset.UtcNow; var result = db.Update(ar); _cacheClient.Remove(UrnId.Create(typeof(ClientIdRegistrationLookup), ar.Id.ToString())); return result; } } public void InitSchema() { using (var db = _connectionFactory.OpenDbConnection()) { db.CreateTableIfNotExists<ApplicationRegistration>(); } } #endregion } }
using System; using System.Linq; using System.Reflection; using Xunit; using Should; namespace MicroMapper.UnitTests.Tests { public abstract class using_generic_configuration : AutoMapperSpecBase { protected override void Establish_context() { Mapper.CreateMap<Source, Destination>() .ForMember(d => d.Ignored, o => o.Ignore()) .ForMember(d => d.RenamedField, o => o.MapFrom(s => s.NamedProperty)) .ForMember(d => d.IntField, o => o.ResolveUsing<FakeResolver>().FromMember(s => s.StringField)) .ForMember("IntProperty", o => o.ResolveUsing<FakeResolver>().FromMember("AnotherStringField")) .ForMember(d => d.IntProperty3, o => o.ResolveUsing(typeof (FakeResolver)).FromMember(s => s.StringField3)) .ForMember(d => d.IntField4, o => o.ResolveUsing(new FakeResolver()).FromMember("StringField4")); } protected class Source { public int PropertyWithMatchingName { get; set; } public NestedSource NestedSource { get; set; } public int NamedProperty { get; set; } public string StringField; public string AnotherStringField; public string StringField3; public string StringField4; } protected class NestedSource { public int SomeField; } protected class Destination { public int PropertyWithMatchingName { get; set; } public string NestedSourceSomeField; public string Ignored { get; set; } public string RenamedField; public int IntField; public int IntProperty { get; set; } public int IntProperty3 { get; set; } public int IntField4; } class FakeResolver : ValueResolver<string, int> { protected override int ResolveCore(string source) { return default(int); } } } public class when_members_have_matching_names : using_generic_configuration { const string memberName = "PropertyWithMatchingName"; static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == memberName) .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_matching_member_of_the_source_type_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetProperty(memberName)); } } public class when_the_destination_member_is_flattened : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "NestedSourceSomeField") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_member_of_the_nested_source_type_as_value() { sourceMember.ShouldBeSameAs(typeof (NestedSource).GetField("SomeField")); } } public class when_the_destination_member_is_ignored : using_generic_configuration { static Exception exception; static MemberInfo sourceMember; protected override void Because_of() { try { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "Ignored") .SourceMember; } catch (Exception ex) { exception = ex; } } [Fact] public void should_not_throw_an_exception() { exception.ShouldBeNull(); } [Fact] public void should_be_null() { sourceMember.ShouldBeNull(); } } public class when_the_destination_member_is_projected : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "RenamedField") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_projected_member_of_the_source_type_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty")); } } public class when_the_destination_member_is_resolved_from_a_source_member : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "IntField") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField")); } } public class when_the_destination_property_is_resolved_from_a_source_member_using_the_Magic_String_overload : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "IntProperty") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetField("AnotherStringField")); } } public class when_the_destination_property_is_resolved_from_a_source_member_using_the_non_generic_resolve_method : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "IntProperty3") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField3")); } } public class when_the_destination_property_is_resolved_from_a_source_member_using_non_the_generic_resolve_method_and_the_Magic_String_overload : using_generic_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "IntField4") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_member_of_the_source_type_it_is_resolved_from_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetField("StringField4")); } } public abstract class using_nongeneric_configuration : AutoMapperSpecBase { protected override void Establish_context() { Mapper.CreateMap(typeof (Source), typeof (Destination)) .ForMember("RenamedProperty", o => o.MapFrom("NamedProperty")); } protected class Source { public int NamedProperty { get; set; } } protected class Destination { public string RenamedProperty { get; set; } } } public class when_the_destination_property_is_projected : using_nongeneric_configuration { static MemberInfo sourceMember; protected override void Because_of() { sourceMember = Mapper.FindTypeMapFor<Source, Destination>() .GetPropertyMaps() .Single(pm => pm.DestinationProperty.Name == "RenamedProperty") .SourceMember; } [Fact] public void should_not_be_null() { sourceMember.ShouldNotBeNull(); } [Fact] public void should_have_the_projected_member_of_the_source_type_as_value() { sourceMember.ShouldBeSameAs(typeof (Source).GetProperty("NamedProperty")); } } }
#if (UNITY_IPHONE || UNITY_ANDROID || UNITY_WP8) #define TOUCH_SCREEN_KEYBOARD #endif using UnityEngine; using System.Collections; /// <summary> /// TextInput control /// </summary> [ExecuteInEditMode] [AddComponentMenu("2D Toolkit/UI/tk2dUITextInput")] public class tk2dUITextInput : MonoBehaviour { /// <summary> /// UItem that will make cause TextInput to become selected on click /// </summary> public tk2dUIItem selectionBtn; /// <summary> /// TextMesh while text input will be displayed /// </summary> public tk2dTextMesh inputLabel; /// <summary> /// TextMesh that will be displayed if nothing in inputLabel and is not selected /// </summary> public tk2dTextMesh emptyDisplayLabel; /// <summary> /// State to be active if text input is not selected /// </summary> public GameObject unSelectedStateGO; /// <summary> /// Stated to be active if text input is selected /// </summary> public GameObject selectedStateGO; /// <summary> /// Text cursor to be displayed at next of text input on selection /// </summary> public GameObject cursor; /// <summary> /// How long the field is (visible) /// </summary> public float fieldLength = 1; /// <summary> /// Maximum number of characters allowed for input /// </summary> public int maxCharacterLength = 30; /// <summary> /// Text to be displayed when no text is entered and text input is not selected /// </summary> public string emptyDisplayText; /// <summary> /// If set to true (is a password field), then all characters will be replaced with password char /// </summary> public bool isPasswordField = false; /// <summary> /// Each character in the password field is replaced with the first character of this string /// Default: * if string is empty. /// </summary> public string passwordChar = "*"; [SerializeField] [HideInInspector] private tk2dUILayout layoutItem = null; public tk2dUILayout LayoutItem { get { return layoutItem; } set { if (layoutItem != value) { if (layoutItem != null) { layoutItem.OnReshape -= LayoutReshaped; } layoutItem = value; if (layoutItem != null) { layoutItem.OnReshape += LayoutReshaped; } } } } private bool isSelected = false; private bool wasStartedCalled = false; private bool wasOnAnyPressEventAttached = false; #if TOUCH_SCREEN_KEYBOARD private TouchScreenKeyboard keyboard = null; #endif private bool listenForKeyboardText = false; private bool isDisplayTextShown =false; public System.Action<tk2dUITextInput> OnTextChange; public string SendMessageOnTextChangeMethodName = ""; public GameObject SendMessageTarget { get { if (selectionBtn != null) { return selectionBtn.sendMessageTarget; } else return null; } set { if (selectionBtn != null && selectionBtn.sendMessageTarget != value) { selectionBtn.sendMessageTarget = value; #if UNITY_EDITOR tk2dUtil.SetDirty(selectionBtn); #endif } } } public bool IsFocus { get { return isSelected; } } private string text = ""; /// <summary> /// Update the input text /// </summary> public string Text { get { return text; } set { if (text != value) { text = value; if (text.Length > maxCharacterLength) { text = text.Substring(0, maxCharacterLength); } FormatTextForDisplay(text); if (isSelected) { SetCursorPosition(); } } } } void Awake() { SetState(); ShowDisplayText(); } void Start() { wasStartedCalled = true; if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress += AnyPress; } wasOnAnyPressEventAttached = true; } void OnEnable() { if (wasStartedCalled && !wasOnAnyPressEventAttached) { if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress += AnyPress; } } if (layoutItem != null) { layoutItem.OnReshape += LayoutReshaped; } selectionBtn.OnClick += InputSelected; } void OnDisable() { if (tk2dUIManager.Instance__NoCreate != null) { tk2dUIManager.Instance.OnAnyPress -= AnyPress; if (listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate -= ListenForKeyboardTextUpdate; } } wasOnAnyPressEventAttached = false; selectionBtn.OnClick -= InputSelected; listenForKeyboardText = false; if (layoutItem != null) { layoutItem.OnReshape -= LayoutReshaped; } } public void SetFocus() { SetFocus(true); } /// <summary> /// Sets or removes focus from the text input /// Currently you will need to manually need to remove focus and set focus on the new /// textinput if you wish to do this from a textInput callback, eg. auto advance when /// enter is pressed. /// </summary> public void SetFocus(bool focus) { if (!IsFocus && focus) { InputSelected(); } else if (IsFocus && !focus) { InputDeselected(); } } private void FormatTextForDisplay(string modifiedText) { if (isPasswordField) { int charLength = modifiedText.Length; char passwordReplaceChar = ( passwordChar.Length > 0 ) ? passwordChar[0] : '*'; modifiedText = ""; modifiedText=modifiedText.PadRight(charLength, passwordReplaceChar); } inputLabel.text = modifiedText; inputLabel.Commit(); float actualLabelWidth = inputLabel.GetComponent<Renderer>().bounds.size.x / inputLabel.transform.lossyScale.x; while (actualLabelWidth > fieldLength) { modifiedText=modifiedText.Substring(1, modifiedText.Length - 1); inputLabel.text = modifiedText; inputLabel.Commit(); actualLabelWidth = inputLabel.GetComponent<Renderer>().bounds.size.x / inputLabel.transform.lossyScale.x; } if (modifiedText.Length==0 && !listenForKeyboardText) { ShowDisplayText(); } else { HideDisplayText(); } } private void ListenForKeyboardTextUpdate() { bool change = false; string newText = text; //http://docs.unity3d.com/Documentation/ScriptReference/Input-inputString.html string inputStr = Input.inputString; char c; for (int i=0; i<inputStr.Length; i++) { c = inputStr[i]; if (c == "\b"[0]) { if (text.Length != 0) { newText = text.Substring(0, text.Length - 1); change = true; } } else if (c == "\n"[0] || c == "\r"[0]) { } else if ((int)c!=9 && (int)c!=27) //deal with a Mac only Unity bug where it returns a char for escape and tab { newText += c; change = true; } } #if UNITY_IOS && !UNITY_EDITOR inputStr = keyboard.text; if(!inputStr.Equals(text)) { newText = inputStr; change = true; } #endif if (change) { Text = newText; if (OnTextChange != null) { OnTextChange(this); } if (SendMessageTarget != null && SendMessageOnTextChangeMethodName.Length > 0) { SendMessageTarget.SendMessage( SendMessageOnTextChangeMethodName, this, SendMessageOptions.RequireReceiver ); } } } private void InputSelected() { if (text.Length == 0) { HideDisplayText(); } isSelected = true; if (!listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate += ListenForKeyboardTextUpdate; } listenForKeyboardText = true; SetState(); SetCursorPosition(); #if TOUCH_SCREEN_KEYBOARD if (Application.platform != RuntimePlatform.WindowsEditor && Application.platform != RuntimePlatform.OSXEditor) { #if UNITY_ANDROID //due to a delete key bug in Unity Android TouchScreenKeyboard.hideInput = false; #else TouchScreenKeyboard.hideInput = true; #endif keyboard = TouchScreenKeyboard.Open(text, TouchScreenKeyboardType.Default, false, false, isPasswordField, false); StartCoroutine(TouchScreenKeyboardLoop()); } #endif } #if TOUCH_SCREEN_KEYBOARD private IEnumerator TouchScreenKeyboardLoop() { while (keyboard != null && !keyboard.done && keyboard.active) { Text = keyboard.text; yield return null; } if (keyboard != null) { Text = keyboard.text; } if (isSelected) { InputDeselected(); } } #endif private void InputDeselected() { if (text.Length == 0) { ShowDisplayText(); } isSelected = false; if (listenForKeyboardText) { tk2dUIManager.Instance.OnInputUpdate -= ListenForKeyboardTextUpdate; } listenForKeyboardText = false; SetState(); #if TOUCH_SCREEN_KEYBOARD if (keyboard!=null && !keyboard.done) { keyboard.active = false; } keyboard = null; #endif } private void AnyPress() { if (isSelected && tk2dUIManager.Instance.PressedUIItem != selectionBtn) { InputDeselected(); } } private void SetState() { tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(unSelectedStateGO, !isSelected); tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(selectedStateGO, isSelected); tk2dUIBaseItemControl.ChangeGameObjectActiveState(cursor, isSelected); } private void SetCursorPosition() { float multiplier = 1; float cursorOffset = 0.002f; if (inputLabel.anchor == TextAnchor.MiddleLeft || inputLabel.anchor == TextAnchor.LowerLeft || inputLabel.anchor == TextAnchor.UpperLeft) { multiplier = 2; } else if (inputLabel.anchor == TextAnchor.MiddleRight || inputLabel.anchor == TextAnchor.LowerRight || inputLabel.anchor == TextAnchor.UpperRight) { multiplier = -2; cursorOffset = 0.012f; } if (text.EndsWith(" ")) { tk2dFontChar chr; if (inputLabel.font.inst.useDictionary) { chr = inputLabel.font.inst.charDict[' ']; } else { chr = inputLabel.font.inst.chars[' ']; } cursorOffset += chr.advance * inputLabel.scale.x/2; } float renderBoundsRight = inputLabel.GetComponent<Renderer>().bounds.extents.x / gameObject.transform.lossyScale.x; cursor.transform.localPosition = new Vector3(inputLabel.transform.localPosition.x + (renderBoundsRight + cursorOffset) * multiplier, cursor.transform.localPosition.y, cursor.transform.localPosition.z); } private void ShowDisplayText() { if (!isDisplayTextShown) { isDisplayTextShown = true; if (emptyDisplayLabel != null) { emptyDisplayLabel.text = emptyDisplayText; emptyDisplayLabel.Commit(); tk2dUIBaseItemControl.ChangeGameObjectActiveState(emptyDisplayLabel.gameObject, true); } tk2dUIBaseItemControl.ChangeGameObjectActiveState(inputLabel.gameObject, false); } } private void HideDisplayText() { if (isDisplayTextShown) { isDisplayTextShown = false; tk2dUIBaseItemControl.ChangeGameObjectActiveStateWithNullCheck(emptyDisplayLabel.gameObject, false); tk2dUIBaseItemControl.ChangeGameObjectActiveState(inputLabel.gameObject, true); } } private void LayoutReshaped(Vector3 dMin, Vector3 dMax) { fieldLength += (dMax.x - dMin.x); // No way to trigger re-format yet string tmpText = this.text; text = ""; Text = tmpText; } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ namespace System.Management.Automation.Internal { using System; using System.Threading; using System.Runtime.InteropServices; using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; using System.Management.Automation; /// <summary> /// A PipelineReader for an ObjectStream /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal abstract class ObjectReaderBase<T> : PipelineReader<T>, IDisposable { /// <summary> /// Construct with an existing ObjectStream /// </summary> /// <param name="stream">the stream to read</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null</exception> public ObjectReaderBase([In, Out] ObjectStreamBase stream) { if (stream == null) { throw new ArgumentNullException("stream", "stream may not be null"); } _stream = stream; } #region Events /// <summary> /// Event fired when objects are added to the underlying stream /// </summary> public override event EventHandler DataReady { add { lock (_monitorObject) { bool firstRegistrant = (null == InternalDataReady); InternalDataReady += value; if (firstRegistrant) { _stream.DataReady += new EventHandler(this.OnDataReady); } } } remove { lock (_monitorObject) { InternalDataReady -= value; if (null == InternalDataReady) { _stream.DataReady -= new EventHandler(this.OnDataReady); } } } } public event EventHandler InternalDataReady = null; #endregion Events #region Public Properties /// <summary> /// Waitable handle for caller's to block until data is ready to read from the underlying stream /// </summary> public override WaitHandle WaitHandle { get { return _stream.ReadHandle; } } /// <summary> /// Check if the stream is closed and contains no data. /// </summary> /// <value>True if the stream is closed and contains no data, otherwise; false.</value> /// <remarks> /// Attempting to read from the underlying stream if EndOfPipeline is true returns /// zero objects. /// </remarks> public override bool EndOfPipeline { get { return _stream.EndOfPipeline; } } /// <summary> /// Check if the stream is open for further writes. /// </summary> /// <value>true if the underlying stream is open, otherwise; false.</value> /// <remarks> /// The underlying stream may be readable after it is closed if data remains in the /// internal buffer. Check <see cref="EndOfPipeline"/> to determine if /// the underlying stream is closed and contains no data. /// </remarks> public override bool IsOpen { get { return _stream.IsOpen; } } /// <summary> /// Returns the number of objects in the underlying stream /// </summary> public override int Count { get { return _stream.Count; } } /// <summary> /// Get the capacity of the stream /// </summary> /// <value> /// The capacity of the stream. /// </value> /// <remarks> /// The capacity is the number of objects that stream may contain at one time. Once this /// limit is reached, attempts to write into the stream block until buffer space /// becomes available. /// </remarks> public override int MaxCapacity { get { return _stream.MaxCapacity; } } #endregion Public Properties #region Public Methods /// <summary> /// Close the stream /// </summary> /// <remarks> /// Causes subsequent calls to IsOpen to return false and calls to /// a write operation to throw an ObjectDisposedException. /// All calls to Close() after the first call are silently ignored. /// </remarks> /// <exception cref="ObjectDisposedException"> /// The stream is already disposed /// </exception> public override void Close() { // 2003/09/02-JonN added call to close underlying stream _stream.Close(); } #endregion Public Methods #region Private Methods /// <summary> /// Handle DataReady events from the underlying stream /// </summary> /// <param name="sender">The stream raising the event</param> /// <param name="args">standard event args.</param> private void OnDataReady(object sender, EventArgs args) { // call any event handlers on this, replacing the // ObjectStream sender with 'this' since receivers // are expecting a PipelineReader<object> InternalDataReady.SafeInvoke(this, args); } #endregion Private Methods #region Private fields /// <summary> /// The underlying stream /// </summary> /// <remarks>Can never be null</remarks> protected ObjectStreamBase _stream; /// <summary> /// This object is used to acquire an exclusive lock /// on event handler registration. /// </summary> /// <remarks> /// Note that we lock _monitorObject rather than "this" so that /// we are protected from outside code interfering in our /// critical section. Thanks to Wintellect for the hint. /// </remarks> private object _monitorObject = new Object(); #endregion Private fields #region IDisposable /// <summary> /// public method for dispose /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected abstract void Dispose(bool disposing); #endregion IDisposable } // ObjectReaderBase /// <summary> /// A PipelineReader reading objects from an ObjectStream /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal class ObjectReader : ObjectReaderBase<object> { #region ctor /// <summary> /// Construct with an existing ObjectStream /// </summary> /// <param name="stream">the stream to read</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null</exception> public ObjectReader([In, Out] ObjectStream stream) : base(stream) { } #endregion ctor /// <summary> /// Read at most <paramref name="count"/> objects /// </summary> /// <param name="count">The maximum number of objects to read</param> /// <returns>The objects read</returns> /// <remarks> /// This method blocks if the number of objects in the stream is less than <paramref name="count"/> /// and the stream is not closed. /// </remarks> public override Collection<object> Read(int count) { return _stream.Read(count); } /// <summary> /// Read a single object from the stream /// </summary> /// <returns>the next object in the stream</returns> /// <remarks>This method blocks if the stream is empty</remarks> public override object Read() { return _stream.Read(); } /// <summary> /// Blocks until the pipeline closes and reads all objects. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// If the stream is empty, an empty collection is returned. /// </remarks> public override Collection<object> ReadToEnd() { return _stream.ReadToEnd(); } /// <summary> /// Reads all objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of all objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> public override Collection<object> NonBlockingRead() { return _stream.NonBlockingRead(Int32.MaxValue); } /// <summary> /// Reads objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<object> NonBlockingRead(int maxRequested) { return _stream.NonBlockingRead(maxRequested); } /// <summary> /// Peek the next object /// </summary> /// <returns>The next object in the stream or ObjectStream.EmptyObject if the stream is empty</returns> public override object Peek() { return _stream.Peek(); } /// <summary> /// release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } } // ObjectReader /// <summary> /// A PipelineReader reading PSObjects from an ObjectStream /// </summary> /// <remarks> /// This class is not safe for multi-threaded operations. /// </remarks> internal class PSObjectReader : ObjectReaderBase<PSObject> { #region ctor /// <summary> /// Construct with an existing ObjectStream /// </summary> /// <param name="stream">the stream to read</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null</exception> public PSObjectReader([In, Out] ObjectStream stream) : base(stream) { } #endregion ctor /// <summary> /// Read at most <paramref name="count"/> objects /// </summary> /// <param name="count">The maximum number of objects to read</param> /// <returns>The objects read</returns> /// <remarks> /// This method blocks if the number of objects in the stream is less than <paramref name="count"/> /// and the stream is not closed. /// </remarks> public override Collection<PSObject> Read(int count) { return MakePSObjectCollection(_stream.Read(count)); } /// <summary> /// Read a single PSObject from the stream /// </summary> /// <returns>the next PSObject in the stream</returns> /// <remarks>This method blocks if the stream is empty</remarks> public override PSObject Read() { return MakePSObject(_stream.Read()); } /// <summary> /// Blocks until the pipeline closes and reads all objects. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// If the stream is empty, an empty collection is returned. /// </remarks> public override Collection<PSObject> ReadToEnd() { return MakePSObjectCollection(_stream.ReadToEnd()); } /// <summary> /// Reads all objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of all objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> public override Collection<PSObject> NonBlockingRead() { return MakePSObjectCollection(_stream.NonBlockingRead(Int32.MaxValue)); } /// <summary> /// Reads objects currently in the stream, but does not block. /// </summary> /// <returns>A collection of zero or more objects.</returns> /// <remarks> /// This method performs a read of objects currently in the /// stream. The method will block until exclusive access to the /// stream is acquired. If there are no objects in the stream, /// an empty collection is returned. /// </remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<PSObject> NonBlockingRead(int maxRequested) { return MakePSObjectCollection(_stream.NonBlockingRead(maxRequested)); } /// <summary> /// Peek the next PSObject /// </summary> /// <returns>The next PSObject in the stream or ObjectStream.EmptyObject if the stream is empty</returns> public override PSObject Peek() { return MakePSObject(_stream.Peek()); } /// <summary> /// release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } #region Private private static PSObject MakePSObject(object o) { if (null == o) return null; return PSObject.AsPSObject(o); } // It might ultimately be more efficient to // make ObjectStream generic and convert the objects to PSObject // before inserting them into the initial Collection, so that we // don't have to convert the collection later. private static Collection<PSObject> MakePSObjectCollection( Collection<object> coll) { if (null == coll) return null; Collection<PSObject> retval = new Collection<PSObject>(); foreach (object o in coll) { retval.Add(MakePSObject(o)); } return retval; } #endregion Private } // PSObjectReader /// <summary> /// A ObjectReader for a PSDataCollection ObjectStream /// </summary> /// <remarks> /// PSDataCollection is introduced after 1.0. PSDataCollection is /// used to store data which can be used with different /// commands concurrently. /// Only Read() operation is supported currently. /// </remarks> internal class PSDataCollectionReader<DataStoreType, ReturnType> : ObjectReaderBase<ReturnType> { #region Private Data private PSDataCollectionEnumerator<DataStoreType> _enumerator; #endregion #region ctor /// <summary> /// Construct with an existing ObjectStream /// </summary> /// <param name="stream">the stream to read</param> /// <exception cref="ArgumentNullException">Thrown if the specified stream is null</exception> public PSDataCollectionReader(PSDataCollectionStream<DataStoreType> stream) : base(stream) { System.Management.Automation.Diagnostics.Assert(null != stream.ObjectStore, "Stream should have a valid data store"); _enumerator = (PSDataCollectionEnumerator<DataStoreType>)stream.ObjectStore.GetEnumerator(); } #endregion ctor /// <summary> /// This method is not supported. /// </summary> /// <param name="count">The maximum number of objects to read</param> /// <returns>The objects read</returns> public override Collection<ReturnType> Read(int count) { throw new NotSupportedException(); } /// <summary> /// Read a single object from the stream. /// </summary> /// <returns> /// The next object in the buffer or AutomationNull if buffer is closed /// and data is not available. /// </returns> /// <remarks> /// This method blocks if the buffer is empty. /// </remarks> public override ReturnType Read() { object result = AutomationNull.Value; if (_enumerator.MoveNext()) { result = _enumerator.Current; } return ConvertToReturnType(result); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> ReadToEnd() { throw new NotSupportedException(); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> NonBlockingRead() { return NonBlockingRead(Int32.MaxValue); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return new Collection<ReturnType>(); } Collection<ReturnType> results = new Collection<ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_enumerator.MoveNext(false)) { results.Add(ConvertToReturnType(_enumerator.Current)); continue; } break; } return results; } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> public override ReturnType Peek() { throw new NotSupportedException(); } /// <summary> /// release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected override void Dispose(bool disposing) { if (disposing) { _stream.Close(); } } private ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) { ReturnType result; LanguagePrimitives.TryConvertTo(inputObject, out result); return result; } System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); } } /// <summary> /// A ObjectReader for a PSDataCollection ObjectStream /// </summary> /// <remarks> /// PSDataCollection is introduced after 1.0. PSDataCollection is /// used to store data which can be used with different /// commands concurrently. /// Only Read() operation is supported currently. /// </remarks> internal class PSDataCollectionPipelineReader<DataStoreType, ReturnType> : ObjectReaderBase<ReturnType> { #region Private Data private PSDataCollection<DataStoreType> _datastore; #endregion Private Data #region ctor /// <summary> /// Construct with an existing ObjectStream /// </summary> /// <param name="stream">the stream to read</param> /// <param name="computerName"></param> /// <param name="runspaceId"></param> internal PSDataCollectionPipelineReader(PSDataCollectionStream<DataStoreType> stream, String computerName, Guid runspaceId) : base(stream) { System.Management.Automation.Diagnostics.Assert(null != stream.ObjectStore, "Stream should have a valid data store"); _datastore = stream.ObjectStore; ComputerName = computerName; RunspaceId = runspaceId; } #endregion ctor /// <summary> /// Computer name passed in by the pipeline which /// created this reader /// </summary> internal String ComputerName { get; } /// <summary> /// Runspace Id passed in by the pipeline which /// created this reader /// </summary> internal Guid RunspaceId { get; } /// <summary> /// This method is not supported. /// </summary> /// <param name="count">The maximum number of objects to read</param> /// <returns>The objects read</returns> public override Collection<ReturnType> Read(int count) { throw new NotSupportedException(); } /// <summary> /// Read a single object from the stream. /// </summary> /// <returns> /// The next object in the buffer or AutomationNull if buffer is closed /// and data is not available. /// </returns> /// <remarks> /// This method blocks if the buffer is empty. /// </remarks> public override ReturnType Read() { object result = AutomationNull.Value; if (_datastore.Count > 0) { Collection<DataStoreType> resultCollection = _datastore.ReadAndRemove(1); // ReadAndRemove returns a Collection<DataStoreType> type but we // just want the single object contained in the collection. if (resultCollection.Count == 1) { result = resultCollection[0]; } } return ConvertToReturnType(result); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> ReadToEnd() { throw new NotSupportedException(); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> public override Collection<ReturnType> NonBlockingRead() { return NonBlockingRead(Int32.MaxValue); } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> /// <remarks></remarks> /// <param name="maxRequested"> /// Return no more than maxRequested objects. /// </param> public override Collection<ReturnType> NonBlockingRead(int maxRequested) { if (maxRequested < 0) { throw PSTraceSource.NewArgumentOutOfRangeException("maxRequested", maxRequested); } if (maxRequested == 0) { return new Collection<ReturnType>(); } Collection<ReturnType> results = new Collection<ReturnType>(); int readCount = maxRequested; while (readCount > 0) { if (_datastore.Count > 0) { results.Add(ConvertToReturnType((_datastore.ReadAndRemove(1))[0])); readCount--; continue; } break; } return results; } /// <summary> /// This method is not supported. /// </summary> /// <returns></returns> public override ReturnType Peek() { throw new NotSupportedException(); } /// <summary> /// Converts to the return type based on language primitives /// </summary> /// <param name="inputObject">input object to convert</param> /// <returns>input object converted to the specified return type</returns> private ReturnType ConvertToReturnType(object inputObject) { Type resultType = typeof(ReturnType); if (typeof(PSObject) == resultType || typeof(object) == resultType) { ReturnType result; LanguagePrimitives.TryConvertTo(inputObject, out result); return result; } System.Management.Automation.Diagnostics.Assert(false, "ReturnType should be either object or PSObject only"); throw PSTraceSource.NewNotSupportedException(); } #region IDisposable /// <summary> /// release all resources /// </summary> /// <param name="disposing">if true, release all managed resources</param> protected override void Dispose(bool disposing) { if (disposing) { _datastore.Dispose(); } } #endregion IDisposable } }
using System; using System.Collections.Generic; using System.Linq; using Sandbox.ModAPI; using VRage.Game; using VRage.Game.Entity; using VRage.ModAPI; using VRageMath; //using Ingame = VRage.Game.ModAPI.Ingame; using Ingame = Sandbox.ModAPI.Ingame; using VRage.Game.ModAPI; using VRage.ObjectBuilders; using VRage.Utils; using Sandbox.Game.Entities; using Sandbox.Game; using Sandbox.Definitions; using VRage; using NaniteConstructionSystem.Extensions; namespace NaniteConstructionSystem.Entities.Tools { public class NaniteToolBaseOld { private IMySlimBlock m_targetBlock = null; public IMySlimBlock TargetBlock { get { return m_targetBlock; } } private int m_startTime = 0; public int StartTime { get { return m_startTime; } } private int m_waitTime = 0; public int WaitTime { get { return m_waitTime; } } private IMyFunctionalBlock m_tool = null; public IMyFunctionalBlock ToolBlock { get { return m_tool; } } private IMyEntity m_toolEntity; private NaniteConstructionBlock m_constructionBlock; private bool m_started = false; private int m_lastToolUse = 0; private int m_lastEnabled = 0; private bool m_completed = false; private bool m_performanceFriendly; private int m_completeTime; private Dictionary<string, int> m_missingComponents; private Dictionary<string, MyTuple<MyFixedPoint, MyObjectBuilder_PhysicalObject>> m_inventory = new Dictionary<string, MyTuple<MyFixedPoint, MyObjectBuilder_PhysicalObject>>(); private bool m_isGrinder; private long m_cubeEntityId; private Vector3I m_position; private bool m_removed; public NaniteToolBaseOld(NaniteConstructionBlock constructionBlock, IMySlimBlock block, int waitTime, string toolBuilderText, bool performanceFriendly, bool isGrinder) { if (block == null) { Logging.Instance.WriteLine("Block is null!"); return; } m_targetBlock = block; Vector3D position = Vector3D.Zero; if (block.FatBlock == null) { position = Vector3D.Transform(block.Position * (block.CubeGrid.GridSizeEnum == MyCubeSize.Small ? 0.5f : 2.5f), block.CubeGrid.WorldMatrix); } else { position = block.FatBlock.GetPosition(); } m_startTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; m_waitTime = waitTime; m_constructionBlock = constructionBlock; m_performanceFriendly = performanceFriendly; m_isGrinder = isGrinder; m_missingComponents = new Dictionary<string, int>(); m_inventory = new Dictionary<string, MyTuple<MyFixedPoint, MyObjectBuilder_PhysicalObject>>(); m_removed = false; if (!performanceFriendly) CreateTool(block.CubeGrid.GridSizeEnum, toolBuilderText); else CreatePerformanceTool(); //Logging.Instance.WriteLine("Init"); } public virtual void Close() { //Logging.Instance.WriteLine(string.Format("Close")); int pos = 0; try { if(m_performanceFriendly) { if (Sync.IsClient) NaniteConstructionManager.ParticleManager.RemoveParticle(m_cubeEntityId, m_position); else m_constructionBlock.SendRemoveParticleEffect(m_cubeEntityId, m_position); if (m_isGrinder && m_removed) { TransferRemainingComponents(); Logging.Instance.WriteLine(string.Format("GRINDING completed. Target block: {0} - (EntityID: {1} Elapsed: {2})", m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.EntityId : 0, m_completeTime + m_waitTime)); } m_completed = true; return; } if(m_constructionBlock != null && m_constructionBlock.ConstructionBlock != null) { var toolInventory = ((MyEntity)m_tool).GetInventory(0); // Since grinding in creative gives no components. Insert hack. if(MyAPIGateway.Session.CreativeMode && m_tool is Sandbox.ModAPI.Ingame.IMyShipGrinder) { MyObjectBuilder_CubeBlock block = (MyObjectBuilder_CubeBlock)m_targetBlock.GetObjectBuilder(); MyCubeBlockDefinition blockDefinition; if(MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition)) { foreach(var item in blockDefinition.Components) { var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id); toolInventory.AddItems(item.Count, inventoryItem); } } } if (toolInventory.GetItemsCount() > 0) { TransferFromTarget((MyCubeBlock)m_tool); } } m_completed = true; if (m_tool != null) { m_tool.Enabled = false; } if (!m_toolEntity.Closed) m_toolEntity.Close(); } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("Close() {1}: {0}", ex.ToString(), pos)); } } private void TransferRemainingComponents() { MyObjectBuilder_CubeBlock block; try { if (m_targetBlock.FatBlock == null) block = m_targetBlock.GetObjectBuilder(); else block = m_targetBlock.FatBlock.GetObjectBuilderCubeBlock(); } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("ERROR getting cubeblock object builder (1): {0} {1} - {2}", m_targetBlock.IsDestroyed, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, ex.ToString())); return; } MyCubeBlockDefinition blockDefinition; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition)) { Dictionary<string, MyTuple<int, MyPhysicalItemDefinition>> components = new Dictionary<string, MyTuple<int, MyPhysicalItemDefinition>>(); foreach (var item in blockDefinition.Components) { var inventoryItem = (MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.DeconstructItem.Id); if (!components.ContainsKey(item.DeconstructItem.Id.SubtypeName)) components.Add(item.DeconstructItem.Id.SubtypeName, new MyTuple<int, MyPhysicalItemDefinition>(item.Count, item.DeconstructItem)); else components[item.DeconstructItem.Id.SubtypeName] = new MyTuple<int, MyPhysicalItemDefinition>(components[item.DeconstructItem.Id.SubtypeName].Item1 + item.Count, item.DeconstructItem); } foreach (var item in m_missingComponents) { if (components.ContainsKey(item.Key)) { components[item.Key] = new MyTuple<int, MyPhysicalItemDefinition>(components[item.Key].Item1 - item.Value, components[item.Key].Item2); } if (components[item.Key].Item1 <= 0) components.Remove(item.Key); } foreach (var item in components) { TransferFromItem((MyObjectBuilder_PhysicalObject)MyObjectBuilderSerializer.CreateNewObject(item.Value.Item2.Id), item.Value.Item1); } } foreach(var item in m_inventory) { MyFloatingObjects.Spawn(new MyPhysicalInventoryItem(item.Value.Item1, item.Value.Item2), Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize, m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up); } } private void TransferFromItem(MyObjectBuilder_PhysicalObject item, int count) { MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory(); if(targetInventory.CanItemsBeAdded(count, item.GetId())) { targetInventory.AddItems(count, item); return; } if (!GridHelper.FindFreeCargo((MyCubeBlock)m_constructionBlock.ConstructionBlock, item, count)) return; var inventoryItem = new MyPhysicalInventoryItem(count, item); MyFloatingObjects.Spawn(inventoryItem, Vector3D.Transform(m_targetBlock.Position * m_targetBlock.CubeGrid.GridSize, m_targetBlock.CubeGrid.WorldMatrix), m_targetBlock.CubeGrid.WorldMatrix.Forward, m_targetBlock.CubeGrid.WorldMatrix.Up); } private void TransferFromTarget(MyCubeBlock target) { MyInventory targetInventory = ((MyCubeBlock)m_constructionBlock.ConstructionBlock).GetInventory(); MyInventory sourceInventory = target.GetInventory(); foreach(var item in sourceInventory.GetItems().ToList()) { if(targetInventory.ItemsCanBeAdded(item.Amount, item)) { targetInventory.TransferItemsFrom(sourceInventory, item, item.Amount); } else { int amountFits = (int)targetInventory.ComputeAmountThatFits(new MyDefinitionId(item.Content.TypeId, item.Content.SubtypeId)); if(amountFits > 0f) { targetInventory.TransferItemsFrom(sourceInventory, item, amountFits); } } } if (sourceInventory.GetItems().Count < 1) return; if (GridHelper.FindFreeCargo(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock)) return; // We have left over inventory, drop it foreach(var item in sourceInventory.GetItems().ToList()) { sourceInventory.RemoveItems(item.ItemId, item.Amount, spawn: true); } } public virtual void Update() { if (m_performanceFriendly) { if (!m_started && MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_startTime > m_waitTime) { m_started = true; m_cubeEntityId = m_targetBlock.CubeGrid.EntityId; m_position = m_targetBlock.Position; if (Sync.IsClient) NaniteConstructionManager.ParticleManager.AddParticle(m_cubeEntityId, m_position, 27); else m_constructionBlock.SendStartParticleEffect(m_cubeEntityId, m_position, 27); } if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_startTime > m_waitTime + m_completeTime) { Complete(!m_isGrinder); } return; } if (m_targetBlock.IsDestroyed) { if (m_tool != null && !m_tool.Closed && m_tool.Enabled) m_tool.Enabled = false; return; } if (m_toolEntity.Closed) return; // This moves the tool to the position of the target even if the parent cube moves. Vector3D targetBlockPosition; if (m_targetBlock.FatBlock != null) targetBlockPosition = m_targetBlock.FatBlock.PositionComp.GetPosition(); else targetBlockPosition = Vector3D.Transform(m_targetBlock.Position * (m_targetBlock.CubeGrid.GridSizeEnum == MyCubeSize.Small ? 0.5f : 2.5f), m_targetBlock.CubeGrid.WorldMatrix); if (m_toolEntity != null && !m_toolEntity.Closed && m_toolEntity.PositionComp.GetPosition() != targetBlockPosition) { m_toolEntity.SetPosition(targetBlockPosition); } if (m_completed) return; if (m_started) //(int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_lastToolUse > 30 && m_started) { m_lastToolUse = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; ToggleToolStatus(); } if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_startTime > m_waitTime) { if (m_started) return; m_started = true; } } private void ToggleToolStatus() { if (m_tool.Closed) return; var efficiency = NaniteConstructionManager.Settings.ConstructionEfficiency; if (m_tool is Sandbox.ModAPI.Ingame.IMyShipGrinder) efficiency = NaniteConstructionManager.Settings.DeconstructionEfficiency; //Logging.Instance.WriteLine(string.Format("Efficiency: {0}", efficiency)); if(efficiency >= 1f || m_lastEnabled == 0) { m_lastEnabled = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; if (!m_tool.Enabled) { m_tool.Enabled = true; } return; } var onTime = (1f * efficiency) * 1000f + 250f; var offTime = (1f - (1f * efficiency)) * 1000f + 250f; //Logging.Instance.WriteLine(string.Format("OnTime: {0} OffTime: {1} Elapsed: {2}", onTime, offTime, MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_lastEnabled)); if(!m_tool.Enabled && MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_lastEnabled > offTime) { m_lastEnabled = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; m_tool.Enabled = true; } else if(m_tool.Enabled && MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_lastEnabled > onTime) { m_lastEnabled = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; m_tool.Enabled = false; } } private Vector3D GetTargetPosition() { Vector3D targetBlockPosition; if (m_targetBlock.FatBlock != null) targetBlockPosition = m_targetBlock.FatBlock.PositionComp.GetPosition(); else targetBlockPosition = Vector3D.Transform(m_targetBlock.Position * (m_targetBlock.CubeGrid.GridSizeEnum == MyCubeSize.Small ? 0.5f : 2.5f), m_targetBlock.CubeGrid.WorldMatrix); return targetBlockPosition; } private void CreateTool(MyCubeSize size, string toolBuilderText) { var toolObject = toolBuilderText; if (size == MyCubeSize.Large) toolObject = string.Format(toolObject, "Small"); else toolObject = string.Format(toolObject, "Tiny"); MyObjectBuilder_CubeGrid cubeGrid = MyAPIGateway.Utilities.SerializeFromXML<MyObjectBuilder_CubeGrid>(toolObject); foreach (var item in cubeGrid.CubeBlocks) item.Owner = m_constructionBlock.ConstructionBlock.OwnerId; m_toolEntity = MyAPIGateway.Entities.CreateFromObjectBuilder(cubeGrid); m_toolEntity.PositionComp.Scale = 0.001f; m_toolEntity.PositionComp.SetPosition(GetTargetPosition()); m_toolEntity.Physics.Enabled = false; m_toolEntity.Save = false; var toolGrid = (MyCubeGrid)m_toolEntity; toolGrid.IsSplit = true; toolGrid.IsPreview = true; List<IMySlimBlock> blocks = new List<IMySlimBlock>(); ((IMyCubeGrid)m_toolEntity).GetBlocks(blocks); foreach (var slimBlock in blocks) { if (slimBlock.FatBlock == null) continue; var block = slimBlock.FatBlock; if (block is Sandbox.ModAPI.Ingame.IMyShipWelder || block is Sandbox.ModAPI.Ingame.IMyShipGrinder) { MyCubeBlock toolBlock = (MyCubeBlock)block; toolBlock.IDModule.ShareMode = MyOwnershipShareModeEnum.Faction; IMyFunctionalBlock tool = (IMyFunctionalBlock)block; m_tool = tool; break; } } MyAPIGateway.Entities.AddEntity(m_toolEntity); //m_toolEntity.RemoveFromGamePruningStructure(); } private void CreatePerformanceTool() { MyObjectBuilder_CubeBlock block; try { if (m_targetBlock.FatBlock == null) block = m_targetBlock.GetObjectBuilder(); else block = m_targetBlock.FatBlock.GetObjectBuilderCubeBlock(); } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("ERROR getting cubeblock object builder (2): {0} {1} - {2}", m_targetBlock.IsDestroyed, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, ex.ToString())); return; } MyCubeBlockDefinition blockDefinition; if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition)) { m_completeTime = (int)(m_targetBlock.BuildIntegrity / blockDefinition.IntegrityPointsPerSec * 1000f / MyAPIGateway.Session.GrinderSpeedMultiplier / NaniteConstructionManager.Settings.DeconstructionEfficiency); } Logging.Instance.WriteLine(string.Format("GRINDING started. Target block: {0} - {1}ms", m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, m_completeTime)); } private void Complete(bool replace = false) { if (replace) { /* VRage.Game.ModAPI.Interfaces.IMyDestroyableObject obj = (VRage.Game.ModAPI.Interfaces.IMyDestroyableObject)m_targetBlock; var dmg = m_targetBlock.MaxIntegrity - m_targetBlock.BuildIntegrity; obj.DoDamage(-dmg, VRage.Utils.MyStringHash.GetOrCompute("NaniteRepair"), true); m_targetBlock.ApplyAccumulatedDamage(); MyCubeGrid grid = (MyCubeGrid)m_targetBlock.CubeGrid; grid.SendIntegrityChanged((Sandbox.Game.Entities.Cube.MySlimBlock)m_targetBlock, MyCubeGrid.MyIntegrityChangeEnum.Repair, 0); grid.OnIntegrityChanged((Sandbox.Game.Entities.Cube.MySlimBlock)m_targetBlock); m_targetBlock.UpdateVisual(); */ } else { if (m_targetBlock.IsDestroyed || m_targetBlock.CubeGrid.GetCubeBlock(m_targetBlock.Position) == null || (m_targetBlock.FatBlock != null && m_targetBlock.FatBlock.Closed)) return; if (m_targetBlock.CubeGrid.Closed) return; MyCubeGrid grid = (MyCubeGrid)m_targetBlock.CubeGrid; MyObjectBuilder_CubeBlock block; try { if (m_targetBlock.FatBlock == null) block = m_targetBlock.GetObjectBuilder(); else block = m_targetBlock.FatBlock.GetObjectBuilderCubeBlock(); } catch (Exception ex) { Logging.Instance.WriteLine(string.Format("ERROR getting cubeblock object builder (3): {0} {1} - {2}", m_targetBlock.IsDestroyed, m_targetBlock.FatBlock != null ? m_targetBlock.FatBlock.GetType().Name : m_targetBlock.GetType().Name, ex.ToString())); } // Target block contains inventory, spawn it if(m_targetBlock.FatBlock != null && ((MyEntity)m_targetBlock.FatBlock).HasInventory) { for(int r = 0; r < ((MyEntity)m_targetBlock.FatBlock).InventoryCount; r++) { var inventory = ((MyEntity)m_targetBlock.FatBlock).GetInventoryBase(r); if (inventory == null) continue; foreach(var item in inventory.GetItems()) { Logging.Instance.WriteLine(string.Format("INVENTORY found. Target block contains inventory: {0} {1}", item.Amount, item.Content.SubtypeId)); if(!m_inventory.ContainsKey(item.Content.SubtypeName)) m_inventory.Add(item.Content.SubtypeName, new MyTuple<MyFixedPoint, MyObjectBuilder_PhysicalObject>(item.Amount, item.Content)); else m_inventory[item.Content.SubtypeName] = new MyTuple<MyFixedPoint, MyObjectBuilder_PhysicalObject>(m_inventory[item.Content.SubtypeName].Item1 + item.Amount, m_inventory[item.Content.SubtypeName].Item2); } } } m_targetBlock.GetMissingComponents(m_missingComponents); //grid.RemoveBlock((Sandbox.Game.Entities.Cube.MySlimBlock)m_targetBlock, true); grid.RazeBlock(m_targetBlock.Position); m_removed = true; } } } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using ESRI.ArcGIS.Geodatabase; using Miner.ComCategories; using stdole; namespace Miner.Interop { /// <summary> /// Base class for QA/QC validation rules. /// </summary> [ComVisible(true)] public abstract class BaseValidationRule : IMMValidationRule, IMMExtObject, IDisposable { #region Fields /// <summary> /// Array of class or field model names used to enable the assignment of the validation rule within ArcCatalog. /// </summary> private readonly string[] _ModelNames; /// <summary> /// The name of the validation rule. This name will be displayed in ArcCatalog in the ArcFM Properties /// </summary> private readonly string _Name; private static readonly ILog Log = LogProvider.For<BaseValidationRule>(); /// <summary> /// D8List of the validation errors. Use the AddError method to add errors to this list. /// </summary> private ID8List _ErrorList; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BaseValidationRule" /> class. /// </summary> /// <param name="name">The name of the validation rule. This name will be displayed in ArcCatalog in the ArcFM Properties.</param> protected BaseValidationRule(string name) { _Name = name; } /// <summary> /// Initializes a new instance of the <see cref="BaseValidationRule" /> class. /// </summary> /// <param name="name">The name of the validation rule. This name will be displayed in ArcCatalog in the ArcFM Properties.</param> /// <param name="modelNames">The model names that must be present on the feature class to be enabled.</param> protected BaseValidationRule(string name, params string[] modelNames) { _Name = name; _ModelNames = modelNames; } #endregion #region Public Properties /// <summary> /// Gets the bitmap. /// </summary> /// <value>The bitmap.</value> public virtual IPictureDisp Bitmap { get { return null; } } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return _Name; } } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #region Public Methods /// <summary> /// Gets if this validation rule is enabled. /// </summary> /// <param name="pvarValues">The parameter values.</param> /// <returns><c>true</c> if the validation rule is enabled or visible within ArcCatalog; otherwise <c>false</c>.</returns> public virtual bool get_Enabled(ref object pvarValues) { try { return this.EnableByModelNames(pvarValues); } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Enabling Validation Rule " + _Name, e); else Log.Error(e); } return false; } /// <summary> /// Determines whether the specified row is valid. /// </summary> /// <param name="pRow">The row.</param> /// <returns>D8List of IMMValidationError items.</returns> public virtual ID8List IsValid(IRow pRow) { // Create a new D8List. _ErrorList = new D8ListClass(); try { this.InternalIsValid(pRow); } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Executing Validation Rule " + _Name, e); else Log.Error(e); } // Return the error list. return _ErrorList; } #endregion #region Internal Methods /// <summary> /// Registers the specified registry key. /// </summary> /// <param name="registryKey">The registry key.</param> [ComRegisterFunction] internal static void Register(string registryKey) { MMValidationRules.Register(registryKey); } /// <summary> /// Unregisters the specified registry key. /// </summary> /// <param name="registryKey">The registry key.</param> [ComUnregisterFunction] internal static void Unregister(string registryKey) { MMValidationRules.Unregister(registryKey); } #endregion #region Protected Methods /// <summary> /// Adds the error to the internal D8List. /// </summary> /// <param name="errorMessage">The error message to be added.</param> protected void AddError(string errorMessage) { if (_ErrorList == null) _ErrorList = new D8ListClass(); IMMValidationError error = new MMValidationErrorClass(); error.Severity = 8; error.BitmapID = 0; error.ErrorMessage = errorMessage; _ErrorList.Add((ID8ListItem) error); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only /// unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { if (_ErrorList != null) while (Marshal.ReleaseComObject(_ErrorList) > 0) { // Loop until reference counter zero. } } } /// <summary> /// Determines if the specified parameter is an object class that has been configured with a class model name /// identified /// in the _ModelNames array. /// </summary> /// <param name="param">The object class to validate.</param> /// <returns>Boolean indicating if the specified object class has any of the appropriate model name(s).</returns> protected virtual bool EnableByModelNames(object param) { if (_ModelNames == null) return true; // No configured model names. IObjectClass oclass = param as IObjectClass; if (oclass == null) return true; return (oclass.IsAssignedClassModelName(_ModelNames)); } /// <summary> /// Internal implementation of the IsValid method. This method is called within internal exception handling to report /// all errors to the event log and prompt the user. /// </summary> /// <param name="row">The row being validated.</param> protected abstract void InternalIsValid(IRow row); #endregion } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.ComponentModel; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SourceCode.Clay.Buffers { /* The xxHash32 implementation is based on the code published by Yann Collet: https://raw.githubusercontent.com/Cyan4973/xxHash/5c174cfa4e45a42f94082dc0d4539b39696afea1/xxhash.c xxHash - Fast Hash algorithm Copyright (C) 2012-2016, Yann Collet BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) 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. 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. You can contact the author at : - xxHash homepage: http://www.xxhash.com - xxHash source repository : https://github.com/Cyan4973/xxHash */ #pragma warning disable CA1815 #pragma warning disable CA1066 #pragma warning disable CA2231 #pragma warning disable 0809 #pragma warning disable CA1065 /// <summary> /// Calculates a HashCode of a sequence of bytes. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] internal struct ByteHashCode { #if !NETSTANDARD2_0 private static readonly uint s_seed = (uint)typeof(HashCode).GetField(nameof(s_seed), BindingFlags.NonPublic | BindingFlags.Static).GetValue(null); #else private const uint s_seed = 26_39_41429u; #endif public static readonly int Empty = Combine(Array.Empty<byte>()); private const uint Prime1 = 2654435761u; private const uint Prime2 = 2246822519u; private const uint Prime3 = 3266489917u; private const uint Prime4 = 668265263u; private const uint Prime5 = 374761393u; private uint _acc0, _acc1, _acc2, _acc3; private uint _queue0, _queue1, _queue2, _queue3; private ulong _length; public static int Combine(ReadOnlySpan<byte> values) { uint acc; var length = (uint)values.Length; ReadOnlySpan<uint> ints = MemoryMarshal.Cast<byte, uint>(values); if (values.Length < 16) { acc = s_seed + Prime5; } else { var acc0 = unchecked(s_seed + Prime1 + Prime2); var acc1 = unchecked(s_seed + Prime2); var acc2 = s_seed; var acc3 = unchecked(s_seed - Prime1); while (ints.Length > 3) { acc0 = Round(acc0, ints[0]); acc1 = Round(acc1, ints[1]); acc2 = Round(acc2, ints[2]); acc3 = Round(acc3, ints[3]); ints = ints.Slice(4); values = values.Slice(4 * sizeof(uint)); } acc = Rol(acc0, 1) + Rol(acc1, 7) + Rol(acc2, 12) + Rol(acc3, 18); } acc += length; while (ints.Length > 0) { acc = RemainderRound(acc, ints[0]); ints = ints.Slice(1); values = values.Slice(sizeof(uint)); } while (values.Length > 0) { acc = RemainderRound(acc, values[0]); values = values.Slice(1); } acc = MixFinal(acc); return (int)acc; } /// <summary> /// Adds the specified byte to the HashCode. /// </summary> /// <param name="value">The byte sequence to add</param> public void Add(byte value) { var index = _length++; var position = (byte)(index % 16); #if NETSTANDARD2_0 unsafe { fixed (uint* ptr = &_queue0) { Span<uint> span = new Span<uint>(ptr, 4); #else Span<uint> span = MemoryMarshal.CreateSpan(ref _queue0, 4); #endif Span<byte> octets = MemoryMarshal.Cast<uint, byte>(span); octets[position] = value; if (position == 15) { if (index == 15) { _acc0 = unchecked(s_seed + Prime1 + Prime2); _acc1 = unchecked(s_seed + Prime2); _acc2 = s_seed; _acc3 = unchecked(s_seed - Prime1); } _acc0 = Round(_acc0, _queue0); _acc1 = Round(_acc1, _queue1); _acc2 = Round(_acc2, _queue2); _acc3 = Round(_acc3, _queue3); _queue0 = _queue1 = _queue2 = _queue3 = 0; } #if NETSTANDARD2_0 } } #endif } public int ToHashCode() { var length = _length; var acc = length < 16 ? s_seed + Prime5 : Rol(_acc0, 1) + Rol(_acc1, 7) + Rol(_acc2, 12) + Rol(_acc3, 18); acc += (uint)length; #if NETSTANDARD2_0 unsafe { fixed (uint* ptr = &_queue0) { Span<uint> span = new Span<uint>(ptr, 4); #else Span<uint> span = MemoryMarshal.CreateSpan(ref _queue0, 4); #endif Span<byte> remainder = MemoryMarshal.Cast<uint, byte>(span) .Slice(0, (int)(length % 16)); Span<uint> ints = MemoryMarshal.Cast<byte, uint>(remainder); while (ints.Length > 0) { acc = RemainderRound(acc, ints[0]); ints = ints.Slice(1); remainder = remainder.Slice(sizeof(uint)); } while (remainder.Length > 0) { acc = RemainderRound(acc, remainder[0]); remainder = remainder.Slice(1); } acc = MixFinal(acc); return (int)acc; #if NETSTANDARD2_0 } } #endif } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Rol(uint value, int count) => (value << count) | (value >> (32 - count)); [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint Round(uint acc, uint lane) { acc += lane * Prime2; acc = Rol(acc, 13); acc *= Prime1; return acc; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint RemainderRound(uint acc, uint lane) { acc += lane * Prime3; acc = Rol(acc, 17) * Prime4; return acc; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint RemainderRound(uint acc, byte lane) { acc += lane * Prime5; acc = Rol(acc, 11) * Prime1; return acc; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static uint MixFinal(uint hash) { hash ^= hash >> 15; hash *= Prime2; hash ^= hash >> 13; hash *= Prime3; hash ^= hash >> 16; return hash; } [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => throw new NotSupportedException("HashCode is a mutable struct and should not be compared with other HashCodes. Use ToHashCode to retrieve the computed hash code."); [Obsolete("HashCode is a mutable struct and should not be compared with other HashCodes.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => throw new NotSupportedException("HashCode is a mutable struct and should not be compared with other HashCodes."); } #pragma warning restore CA1065 #pragma warning restore 0809 #pragma warning restore CA2231 #pragma warning restore CA1066 #pragma warning restore CA1815 // Override equals and operator equals on value types }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.RenderTree; using Microsoft.AspNetCore.Components.Test.Helpers; using Xunit; namespace Microsoft.AspNetCore.Components.Test { public class CascadingParameterTest { [Fact] public void PassesCascadingParametersToNestedComponents() { // Arrange var renderer = new TestRenderer(); var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", "Hello"); builder.AddAttribute(2, "ChildContent", new RenderFragment(childBuilder => { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.AddAttribute(1, "RegularParameter", "Goodbye"); childBuilder.CloseComponent(); })); builder.CloseComponent(); }); // Act/Assert var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var batch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(batch, out var nestedComponentId); var nestedComponentDiff = batch.DiffsByComponentId[nestedComponentId].Single(); // The nested component was rendered with the correct parameters Assert.Collection(nestedComponentDiff.Edits, edit => { Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type); AssertFrame.Text( batch.ReferenceFrames[edit.ReferenceFrameIndex], "CascadingParameter=Hello; RegularParameter=Goodbye"); }); Assert.Equal(1, nestedComponent.NumRenders); } [Fact] public void RetainsCascadingParametersWhenUpdatingDirectParameters() { // Arrange var renderer = new TestRenderer(); var regularParameterValue = "Initial value"; var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", "Hello"); builder.AddAttribute(2, "ChildContent", new RenderFragment(childBuilder => { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.AddAttribute(1, "RegularParameter", regularParameterValue); childBuilder.CloseComponent(); })); builder.CloseComponent(); }); // Act 1: Render in initial state var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); // Capture the nested component so we can verify the update later var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out var nestedComponentId); Assert.Equal(1, nestedComponent.NumRenders); // Act 2: Render again with updated regular parameter regularParameterValue = "Changed value"; component.TriggerRender(); // Assert Assert.Equal(2, renderer.Batches.Count); var secondBatch = renderer.Batches[1]; var nestedComponentDiff = secondBatch.DiffsByComponentId[nestedComponentId].Single(); // The nested component was rendered with the correct parameters Assert.Collection(nestedComponentDiff.Edits, edit => { Assert.Equal(RenderTreeEditType.UpdateText, edit.Type); Assert.Equal(0, edit.ReferenceFrameIndex); // This is the only change AssertFrame.Text(secondBatch.ReferenceFrames[0], "CascadingParameter=Hello; RegularParameter=Changed value"); }); Assert.Equal(2, nestedComponent.NumRenders); } [Fact] public void NotifiesDescendantsOfUpdatedCascadingParameterValuesAndPreservesDirectParameters() { // Arrange var providedValue = "Initial value"; var renderer = new TestRenderer(); var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", providedValue); builder.AddAttribute(2, "ChildContent", new RenderFragment(childBuilder => { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.AddAttribute(1, "RegularParameter", "Goodbye"); childBuilder.CloseComponent(); })); builder.CloseComponent(); }); // Act 1: Initial render; capture nested component ID var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out var nestedComponentId); Assert.Equal(1, nestedComponent.NumRenders); // Act 2: Re-render CascadingValue with new value providedValue = "Updated value"; component.TriggerRender(); // Assert: We re-rendered CascadingParameterConsumerComponent Assert.Equal(2, renderer.Batches.Count); var secondBatch = renderer.Batches[1]; var nestedComponentDiff = secondBatch.DiffsByComponentId[nestedComponentId].Single(); // The nested component was rendered with the correct parameters Assert.Collection(nestedComponentDiff.Edits, edit => { Assert.Equal(RenderTreeEditType.UpdateText, edit.Type); Assert.Equal(0, edit.ReferenceFrameIndex); // This is the only change AssertFrame.Text(secondBatch.ReferenceFrames[0], "CascadingParameter=Updated value; RegularParameter=Goodbye"); }); Assert.Equal(2, nestedComponent.NumRenders); } [Fact] public void DoesNotNotifyDescendantsIfCascadingParameterValuesAreImmutableAndUnchanged() { // Arrange var renderer = new TestRenderer(); var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", "Unchanging value"); builder.AddAttribute(2, "ChildContent", new RenderFragment(childBuilder => { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.AddAttribute(1, "RegularParameter", "Goodbye"); childBuilder.CloseComponent(); })); builder.CloseComponent(); }); // Act 1: Initial render var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out _); Assert.Equal(3, firstBatch.DiffsByComponentId.Count); // Root + CascadingValue + nested Assert.Equal(1, nestedComponent.NumRenders); // Act/Assert: Re-render the CascadingValue; observe nested component wasn't re-rendered component.TriggerRender(); // Assert: We did not re-render CascadingParameterConsumerComponent Assert.Equal(2, renderer.Batches.Count); var secondBatch = renderer.Batches[1]; Assert.Equal(2, secondBatch.DiffsByComponentId.Count); // Root + CascadingValue, but not nested one Assert.Equal(1, nestedComponent.NumRenders); } [Fact] public void StopsNotifyingDescendantsIfTheyAreRemoved() { // Arrange var providedValue = "Initial value"; var displayNestedComponent = true; var renderer = new TestRenderer(); var component = new TestComponent(builder => { // At the outer level, have an unrelated fixed cascading value to show we can deal with combining both types builder.OpenComponent<CascadingValue<int>>(0); builder.AddAttribute(1, "Value", 123); builder.AddAttribute(2, "IsFixed", true); builder.AddAttribute(3, "ChildContent", new RenderFragment(builder2 => { // Then also have a non-fixed cascading value so we can show that unsubscription works builder2.OpenComponent<CascadingValue<string>>(0); builder2.AddAttribute(1, "Value", providedValue); builder2.AddAttribute(2, "ChildContent", new RenderFragment(builder3 => { if (displayNestedComponent) { builder3.OpenComponent<SecondCascadingParameterConsumerComponent<string, int>>(0); builder3.AddAttribute(1, "RegularParameter", "Goodbye"); builder3.CloseComponent(); } })); builder2.CloseComponent(); })); builder.CloseComponent(); }); // Act 1: Initial render; capture nested component ID var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out var nestedComponentId); Assert.Equal(1, nestedComponent.NumSetParametersCalls); Assert.Equal(1, nestedComponent.NumRenders); // Act/Assert 2: Re-render the CascadingValue; observe nested component wasn't re-rendered providedValue = "Updated value"; displayNestedComponent = false; // Remove the nested component component.TriggerRender(); // Assert: We did not render the nested component now it's been removed Assert.Equal(2, renderer.Batches.Count); var secondBatch = renderer.Batches[1]; Assert.Equal(1, nestedComponent.NumRenders); Assert.Equal(3, secondBatch.DiffsByComponentId.Count); // Root + CascadingValue + CascadingValue, but not nested component // We *did* send updated params during the first render where it was removed, // because the params are sent before the disposal logic runs. We could avoid // this by moving the notifications into the OnAfterRender phase, but then we'd // often render descendants twice (once because they are descendants and some // direct parameter might have changed, then once because a cascading parameter // changed). We can't have it both ways, so optimize for the case when the // nested component *hasn't* just been removed. Assert.Equal(2, nestedComponent.NumSetParametersCalls); // Act 3: However, after disposal, the subscription is removed, so we won't send // updated params on subsequent CascadingValue renders. providedValue = "Updated value 2"; component.TriggerRender(); Assert.Equal(2, nestedComponent.NumSetParametersCalls); } [Fact] public void DoesNotNotifyDescendantsOfUpdatedCascadingParameterValuesWhenFixed() { // Arrange var providedValue = "Initial value"; var shouldIncludeChild = true; var renderer = new TestRenderer(); var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", providedValue); builder.AddAttribute(2, "IsFixed", true); builder.AddAttribute(3, "ChildContent", new RenderFragment(childBuilder => { if (shouldIncludeChild) { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.AddAttribute(1, "RegularParameter", "Goodbye"); childBuilder.CloseComponent(); } })); builder.CloseComponent(); }); // Act 1: Initial render; capture nested component ID var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out var nestedComponentId); Assert.Equal(1, nestedComponent.NumRenders); // Assert: Initial value is supplied to descendant var nestedComponentDiff = firstBatch.DiffsByComponentId[nestedComponentId].Single(); Assert.Collection(nestedComponentDiff.Edits, edit => { Assert.Equal(RenderTreeEditType.PrependFrame, edit.Type); AssertFrame.Text( firstBatch.ReferenceFrames[edit.ReferenceFrameIndex], "CascadingParameter=Initial value; RegularParameter=Goodbye"); }); // Act 2: Re-render CascadingValue with new value providedValue = "Updated value"; component.TriggerRender(); // Assert: We did not re-render the descendant Assert.Equal(2, renderer.Batches.Count); var secondBatch = renderer.Batches[1]; Assert.Equal(2, secondBatch.DiffsByComponentId.Count); // Root + CascadingValue, but not nested one Assert.Equal(1, nestedComponent.NumSetParametersCalls); Assert.Equal(1, nestedComponent.NumRenders); // Act 3: Dispose shouldIncludeChild = false; component.TriggerRender(); // Assert: Absence of an exception here implies we didn't cause a problem by // trying to remove a non-existent subscription } [Fact] public void CascadingValueThrowsIfFixedFlagChangesToTrue() { // Arrange var renderer = new TestRenderer(); var isFixed = false; var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<object>>(0); builder.AddAttribute(1, "IsFixed", isFixed); builder.AddAttribute(2, "Value", new object()); builder.CloseComponent(); }); renderer.AssignRootComponentId(component); component.TriggerRender(); // Act/Assert isFixed = true; var ex = Assert.Throws<InvalidOperationException>(() => component.TriggerRender()); Assert.Equal("The value of IsFixed cannot be changed dynamically.", ex.Message); } [Fact] public void CascadingValueThrowsIfFixedFlagChangesToFalse() { // Arrange var renderer = new TestRenderer(); var isFixed = true; var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<object>>(0); if (isFixed) // Showing also that "unset" is treated as "false" { builder.AddAttribute(1, "IsFixed", true); } builder.AddAttribute(2, "Value", new object()); builder.CloseComponent(); }); renderer.AssignRootComponentId(component); component.TriggerRender(); // Act/Assert isFixed = false; var ex = Assert.Throws<InvalidOperationException>(() => component.TriggerRender()); Assert.Equal("The value of IsFixed cannot be changed dynamically.", ex.Message); } [Fact] public void ParameterViewSuppliedWithCascadingParametersCannotBeUsedAfterSynchronousReturn() { // Arrange var providedValue = "Initial value"; var renderer = new TestRenderer(); var component = new TestComponent(builder => { builder.OpenComponent<CascadingValue<string>>(0); builder.AddAttribute(1, "Value", providedValue); builder.AddAttribute(2, "ChildContent", new RenderFragment(childBuilder => { childBuilder.OpenComponent<CascadingParameterConsumerComponent<string>>(0); childBuilder.CloseComponent(); })); builder.CloseComponent(); }); // Initial render; capture nested component var componentId = renderer.AssignRootComponentId(component); component.TriggerRender(); var firstBatch = renderer.Batches.Single(); var nestedComponent = FindComponent<CascadingParameterConsumerComponent<string>>(firstBatch, out var nestedComponentId); // Re-render CascadingValue with new value, so it gets a new ParameterView providedValue = "Updated value"; component.TriggerRender(); Assert.Equal(2, renderer.Batches.Count); // It's no longer able to access anything in the ParameterView it just received var ex = Assert.Throws<InvalidOperationException>(nestedComponent.AttemptIllegalAccessToLastParameterView); Assert.Equal($"The {nameof(ParameterView)} instance can no longer be read because it has expired. {nameof(ParameterView)} can only be read synchronously and must not be stored for later use.", ex.Message); } private static T FindComponent<T>(CapturedBatch batch, out int componentId) { var componentFrame = batch.ReferenceFrames.Single( frame => frame.FrameType == RenderTreeFrameType.Component && frame.Component is T); componentId = componentFrame.ComponentId; return (T)componentFrame.Component; } class TestComponent : AutoRenderComponent { private readonly RenderFragment _renderFragment; public TestComponent(RenderFragment renderFragment) { _renderFragment = renderFragment; } protected override void BuildRenderTree(RenderTreeBuilder builder) => _renderFragment(builder); } class CascadingParameterConsumerComponent<T> : AutoRenderComponent { private ParameterView lastParameterView; public int NumSetParametersCalls { get; private set; } public int NumRenders { get; private set; } [CascadingParameter] T CascadingParameter { get; set; } [Parameter] public string RegularParameter { get; set; } public override async Task SetParametersAsync(ParameterView parameters) { lastParameterView = parameters; NumSetParametersCalls++; await base.SetParametersAsync(parameters); } protected override void BuildRenderTree(RenderTreeBuilder builder) { NumRenders++; builder.AddContent(0, $"CascadingParameter={CascadingParameter}; RegularParameter={RegularParameter}"); } public void AttemptIllegalAccessToLastParameterView() { // You're not allowed to hold onto a ParameterView and access it later, // so this should throw lastParameterView.TryGetValue<object>("anything", out _); } } class SecondCascadingParameterConsumerComponent<T1, T2> : CascadingParameterConsumerComponent<T1> { [CascadingParameter] T2 SecondCascadingParameter { get; set; } } } }
using Bloom.Api; using Bloom.Book; using Bloom.Collection; using Bloom.MiscUI; using Bloom.web; using L10NSharp; using SIL.IO; using SIL.Xml; using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Security; using System.Windows.Forms; using System.Xml; namespace Bloom.Spreadsheet { public class SpreadsheetExporter { InternalSpreadsheet _spreadsheet = new InternalSpreadsheet(); private IWebSocketProgress _progress; private BloomWebSocketServer _webSocketServer; private string _outputFolder; // null if not exporting to folder (mainly some unit tests) private string _outputImageFolder; // null if not exporting to folder (mainly some unit tests) private ILanguageDisplayNameResolver LangDisplayNameResolver { get; set; } public delegate SpreadsheetExporter Factory(); /// <summary> /// Constructs a new Spreadsheet Exporter /// </summary> /// <param name="webSocketServer">The webSockerServer of the instance</param> /// <param name="langDisplayNameResolver">The object that will be used to retrieve the language display names</param> public SpreadsheetExporter(BloomWebSocketServer webSocketServer, ILanguageDisplayNameResolver langDisplayNameResolver) { _webSocketServer = webSocketServer; LangDisplayNameResolver = langDisplayNameResolver; } /// <summary> /// Constructs a new Spreadsheet Exporter /// </summary> /// <param name="webSocketServer">The webSockerServer of the instance</param> /// <param name="collectionSettings">The collectionSettings of the book that will be exported. This is used to retrieve the language display names</param> public SpreadsheetExporter(BloomWebSocketServer webSocketServer, CollectionSettings collectionSettings) : this(webSocketServer, new CollectionSettingsLanguageDisplayNameResolver(collectionSettings)) { } public SpreadsheetExporter(ILanguageDisplayNameResolver langDisplayNameResolver) { Debug.Assert(Bloom.Program.RunningUnitTests, "SpreadsheetExporter should be passed a webSocketProgress unless running unit tests that don't need it"); LangDisplayNameResolver = langDisplayNameResolver; } //a list of values which, if they occur in the data-book attribute of an element in the bloomDataDiv, //indicate that the element content should be treated as an image, even though the element doesn't //have a src attribute nor actually contain an img element public static List<string> DataDivImagesWithNoSrcAttributes = new List<string>() { "licenseImage" }; public void ExportToFolderWithProgress(HtmlDom dom, string imagesFolderPath, string outputFolder, Action<string> resultCallback) { var mainShell = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell); BrowserProgressDialog.DoWorkWithProgressDialog(_webSocketServer, "spreadsheet-export", () => new ReactDialog("progressDialogBundle", // props to send to the react component new { title = "Exporting Spreadsheet", titleIcon = "", // enhance: add icon if wanted titleColor = "white", titleBackgroundColor = Palette.kBloomBlueHex, webSocketContext = "spreadsheet-export", showReportButton = "if-error" }, "Export Spreadsheet") // winforms dialog properties { Width = 620, Height = 550 }, (progress, worker) => { var spreadsheet = ExportToFolder(dom, imagesFolderPath, outputFolder, out string outputFilePath, progress); resultCallback(outputFilePath); return progress.HaveProblemsBeenReported; }, null, mainShell); } public SpreadsheetExportParams Params = new SpreadsheetExportParams(); public InternalSpreadsheet Export(HtmlDom dom, string imagesFolderPath, IWebSocketProgress progress = null) { _progress = progress ?? new NullWebSocketProgress(); _spreadsheet.Params = Params; var pages = dom.GetPageElements(); //Get xmatter var dataDiv = GetDataDiv(dom); AddDataDivData(dataDiv, imagesFolderPath); var iContentPage = 0; foreach (var page in pages) { var pageNumber = page.Attributes["data-page-number"]?.Value ?? ""; // For now we will ignore all un-numbered pages, particularly xmatter, // which was handled above by exporting data div data. if (pageNumber == "") continue; //Each page alternates colors var colorForPage = iContentPage++ % 2 == 0 ? InternalSpreadsheet.AlternatingRowsColor1 : InternalSpreadsheet.AlternatingRowsColor2; AddContentRows(page, pageNumber, imagesFolderPath, colorForPage); } _spreadsheet.SortHiddenContentRowsToTheBottom(); return _spreadsheet; } private bool _reportedImageDescription; private void AddContentRows(XmlElement page, string pageNumber, string imagesFolderPath, Color colorForPage) { var imageContainers = GetImageContainers(page); var allGroups = TranslationGroupManager.SortedGroupsOnPage(page, true); var groups = allGroups.Where(x => !x.Attributes["class"].Value.Contains("bloom-imageDescription")).ToList(); if (!_reportedImageDescription && groups.Count < allGroups.Count) { _progress?.MessageWithoutLocalizing("Image descriptions are not currently supported by spreadsheet import/export. They will be ignored.", ProgressKind.Warning); _reportedImageDescription = true; } var pageContentTuples = imageContainers.MapUnevenPairs(groups, (imageContainer, group) => (imageContainer, group)); foreach (var pageContent in pageContentTuples) { var row = new ContentRow(_spreadsheet); row.SetCell(InternalSpreadsheet.RowTypeColumnLabel, InternalSpreadsheet.PageContentRowLabel); row.SetCell(InternalSpreadsheet.PageNumberColumnLabel, pageNumber); if (pageContent.imageContainer != null) { var image = (XmlElement)pageContent.imageContainer.SafeSelectNodes(".//img").Item(0); var imagePath = ImagePath(imagesFolderPath, image.GetAttribute("src")); var fileName = Path.GetFileName(imagePath); var outputPath = Path.Combine("images", fileName); if (fileName == "placeHolder.png") outputPath = InternalSpreadsheet.BlankContentIndicator; row.SetCell(InternalSpreadsheet.ImageSourceColumnLabel, outputPath); CopyImageFileToSpreadsheetFolder(imagePath); } if (pageContent.group != null) { foreach (var editable in pageContent.group.SafeSelectNodes("./*[contains(@class, 'bloom-editable')]").Cast<XmlElement>()) { var langCode = editable.Attributes["lang"]?.Value ?? ""; if (langCode == "z" || langCode == "") continue; var index = GetOrAddColumnForLang(langCode); var content = editable.InnerXml; // Don't just test content, it typically contains paragraph markup. if (String.IsNullOrWhiteSpace(editable.InnerText)) { content = InternalSpreadsheet.BlankContentIndicator; } row.SetCell(index, content); } } row.BackgroundColor = colorForPage; } } private XmlElement GetDataDiv(HtmlDom elementOrDom) { return elementOrDom.SafeSelectNodes(".//div[@id='bloomDataDiv']").Cast<XmlElement>().First(); } private XmlElement[] GetImageContainers(XmlElement elementOrDom) { return elementOrDom.SafeSelectNodes(".//*[contains(@class,'bloom-imageContainer')]").Cast<XmlElement>() .ToArray(); } private string ImagePath(string imagesFolderPath, string imageSrc) { return Path.Combine(imagesFolderPath, UrlPathString.CreateFromUrlEncodedString(imageSrc).NotEncoded); } /// <summary> /// Get the column for a language. If no column exists, one will be added /// </summary> /// <remarks>If the column does not exist it will be added. /// The friendly name used for the column will be the display name for that language according to {this.LangDisplayNameResolver}</remarks> /// If the column already exists, its index will be returned. The column, including the column friendly name, will not be modified /// <param name="langCode">The language code to look up, as specified in the header</param> /// <returns>The index of the column</returns> private int GetOrAddColumnForLang(string langCode) { // Check if a column already exists for this column var colIndex = _spreadsheet.GetOptionalColumnForLang(langCode); if (colIndex >= 0) { return colIndex; } // Doesn't exist yet. Let's add a column for it. var langFriendlyName = LangDisplayNameResolver.GetLanguageDisplayName(langCode); return _spreadsheet.AddColumnForLang(langCode, langFriendlyName); } private void AddDataDivData(XmlNode node, string imagesFolderPath) { var dataBookNodeList = node.SafeSelectNodes("./div[@data-book]").Cast<XmlElement>().ToList(); //Bring the ones with the same data-book value together so we can easily make a single row for each data-book value dataBookNodeList.Sort((a, b) => a.GetAttribute("data-book").CompareTo(b.GetAttribute("data-book"))); string prevDataBookLabel = null; SpreadsheetRow row = null; foreach (XmlElement dataBookElement in dataBookNodeList) { var langCode = dataBookElement.GetAttribute("lang"); if (langCode == "z") { continue; } var dataBookLabel = dataBookElement.GetAttribute("data-book"); // Don't export branding, these elements often contain complex content // beyond our current capabilities, but also, importing branding won't work // because these elements are determined by the current branding of the collection. // So there's no point in cluttering the export with them. if (dataBookLabel.Contains("branding")) continue; // No need to export this, Bloom has them all and chooses the right one // based on the licenseUrl. if (dataBookLabel == "licenseImage") continue; //The first time we see this tag: if (!dataBookLabel.Equals(prevDataBookLabel)) { row = new ContentRow(_spreadsheet); var label = "[" + dataBookLabel.Trim() + "]"; if (label != InternalSpreadsheet.BookTitleRowLabel && label != InternalSpreadsheet.CoverImageRowLabel) row.Hidden = true; row.SetCell(InternalSpreadsheet.RowTypeColumnLabel, label); var imageSrcAttribute = dataBookElement.GetAttribute("src").Trim(); if (IsDataDivImageElement(dataBookElement, dataBookLabel)) { if (imageSrcAttribute.Length > 0 && dataBookElement.InnerText.Trim().Length > 0 && !imageSrcAttribute.Equals(dataBookElement.InnerText.Trim())) { //Some data-book items redundantly store the src of the image which they capture in both their content and //src attribute. We haven't yet found any case in which they are different, so are only storing one in the //spreadsheet. This test is to make sure that we notice if we come across a case where it might be necessary //to save both. _progress.MessageWithParams("Spreadsheet.DataDivConflictWarning", "", "Export warning: Found differing 'src' attribute and element text for data-div element {0}. The 'src' attribute will be ignored.", ProgressKind.Warning, dataBookLabel); } string imageSource; string childSrc = ChildImgElementSrc(dataBookElement); if (childSrc.Length > 0) { // We've lost track of what was 'incomplete' about our handling of data-book elements // that have an image child and don't have branding in their key. But the message // was a nuisance. Keeping the code in case it reminds us of a problem at some point. //if (! dataBookElement.GetAttribute("data-book").Contains("branding")) //{ // var msg = LocalizationManager.GetString("Spreadsheet:DataDivNonBrandingImageElment", // "Export warning: Found a non-branding image in an <img> element for " + dataBookLabel // + ". This is not fully handled yet."); // NonFatalProblem.Report(ModalIf.All, PassiveIf.None, msg, showSendReport: true); //} // Don't think we ever have data-book elements with more than one image. But if we encounter one, // I think it's worth warning the user that we don't handle it. if (dataBookElement.ChildNodes .Cast<XmlNode>().Count(n => n.Name == "img" && string.IsNullOrEmpty(((XmlElement)n).GetAttribute("src"))) > 1) { _progress.MessageWithParams("Spreadsheet.MultipleImageChildren", "", "Export warning: Found multiple images in data-book element {0}. Only the first will be exported.", ProgressKind.Warning, dataBookLabel); } imageSource = childSrc; } else { //We determined that whether or not a data-book div has a src attribute, it is the innerText //of the item that is used to set the src of the image in the actual pages of the document. //So that's what we want to capture in the spreadsheet. imageSource = dataBookElement.InnerText.Trim(); } row.SetCell(InternalSpreadsheet.ImageSourceColumnLabel, Path.Combine("images", imageSource)); CopyImageFileToSpreadsheetFolder(ImagePath(imagesFolderPath, imageSource)); prevDataBookLabel = dataBookLabel; continue; } } if (IsDataDivImageElement(dataBookElement, dataBookLabel)) { _progress.MessageWithParams("Spreadsheet.DataDivImageMultiple", "", "Export warning: Found multiple elements for image element {0}. Only the first will be exported.", ProgressKind.Warning, dataBookLabel); continue; } var colIndex = GetOrAddColumnForLang(langCode); row.SetCell(colIndex, dataBookElement.InnerXml.Trim()); prevDataBookLabel = dataBookLabel; } } private void CopyImageFileToSpreadsheetFolder(string imageSourcePath) { if (_outputImageFolder != null) { if (Path.GetFileName(imageSourcePath) == "placeHolder.png") return; // don't need to copy this around. if (!RobustFile.Exists(imageSourcePath)) { _progress.MessageWithParams("Spreadsheet.MissingImage", "", "Export warning: did not find the image {0}. It will be missing from the export folder.", ProgressKind.Warning, imageSourcePath); return; } var destPath = Path.Combine(_outputImageFolder, Path.GetFileName(imageSourcePath)); RobustFile.Copy(imageSourcePath, destPath, true); } } private bool IsDataDivImageElement(XmlElement dataBookElement, string dataBookLabel) { var imageSrc = dataBookElement.GetAttribute("src").Trim(); //Unfortunately, in the current state of Bloom, we have at least three ways of representing in the bloomDataDiv things that are //images in the main document.Some can be identified by having a src attribute on the data-book element itself. Some actually contain //an img element. And some don't have any identifying mark at all, so to recognize them we just have to hard-code a list. return imageSrc.Length > 0 || ChildImgElementSrc(dataBookElement).Length > 0 || DataDivImagesWithNoSrcAttributes.Contains(dataBookLabel); } private string ChildImgElementSrc(XmlElement node) { foreach (XmlNode childNode in node.ChildNodes) { if (childNode.Name.Equals("img") && ((XmlElement)childNode).HasAttribute("src")) { return ((XmlElement)childNode).GetAttribute("src"); } } return ""; } /// <summary> /// Output the specified DOM to the specified outputFolder (after deleting any existing content, if /// permitted...depends on overwrite param and possibly user input). /// Returns the intermediate spreadsheet object created, and also outputs the path to the xlsx file created. /// Looks for images in the specified imagesFolderPath (typically the book folder) and copies them to an /// images subdirectory of the outputFolder. /// Currently the xlsx file created will have the same name as the outputFolder, typically copied from /// the input book folder. /// <returns>the internal spreadsheet, or null if not permitted to overwrite.</returns> /// </summary> public InternalSpreadsheet ExportToFolder(HtmlDom dom, string imagesFolderPath, string outputFolder, out string outputPath, IWebSocketProgress progress = null, OverwriteOptions overwrite = OverwriteOptions.Ask) { outputPath = Path.Combine(outputFolder, Path.Combine(outputFolder, Path.GetFileNameWithoutExtension(outputFolder) + ".xlsx")); _outputFolder = outputFolder; _outputImageFolder = Path.Combine(_outputFolder, "images"); try { if (Directory.Exists(outputFolder)) { if (overwrite == OverwriteOptions.Quit) { // I'm assuming someone working with a command-line can cope with English. // Don't think it's worth cluttering the XLF with this. Console.WriteLine($"Output folder ({_outputFolder}) exists. Use --overwrite to overwrite."); outputPath = null; return null; } var appearsToBeBloomBookFolder = Directory.EnumerateFiles(outputFolder, "*.htm").Any(); var msgTemplate = LocalizationManager.GetString("Spreadsheet.Overwrite", "You are about to replace the existing folder named {0}"); var msg = string.Format(msgTemplate, outputFolder); var messageBoxButtons = new[] { new MessageBoxButton() { Text = "Overwrite", Id = "overwrite" }, new MessageBoxButton() { Text = "Cancel", Id = "cancel", Default = true } }; if (appearsToBeBloomBookFolder) { if (overwrite == OverwriteOptions.Overwrite) { // Assume we can't UI in this mode. But we absolutely must not overwrite the book folder! // So quit anyway. Console.WriteLine( $"Output folder ({_outputFolder}) exists and appears to be a Bloom book, not a previous export. If you really mean to export there, you'll have to delete the folder first."); outputPath = null; return null; } msgTemplate = LocalizationManager.GetString("Spreadsheet.OverwriteBook", "The folder named {0} already exists and looks like it might be a Bloom book folder!"); msg = string.Format(msgTemplate, outputFolder); messageBoxButtons = new[] { messageBoxButtons[1] }; // only cancel } if (overwrite == OverwriteOptions.Ask) { var formToInvokeOn = Application.OpenForms.Cast<Form>().FirstOrDefault(f => f is Shell); string result = null; formToInvokeOn.Invoke((Action)(() => { result = BloomMessageBox.Show(formToInvokeOn, msg, messageBoxButtons, MessageBoxIcon.Warning); })); if (result != "overwrite") { outputPath = null; return null; } } // if it's not Ask, at this point it must be Overwrite, so go ahead. } // In case there's a previous export, get rid of it. SIL.IO.RobustIO.DeleteDirectoryAndContents(_outputFolder); Directory.CreateDirectory(_outputImageFolder); // also (re-)creates its parent, outputFolder var spreadsheet = Export(dom, imagesFolderPath, progress); spreadsheet.WriteToFile(outputPath, progress); return spreadsheet; } catch (Exception e) when (e is IOException || e is SecurityException || e is UnauthorizedAccessException) { progress.MessageWithParams("Spreadsheet.WriteFailed", "", "Bloom had problems writing files to that location ({0}). Check that you have permission to write there.", ProgressKind.Error, _outputFolder); } outputPath = null; return null; // some error occurred and was caught } } public enum OverwriteOptions { Overwrite, Quit, Ask } /// <summary> /// An interface for SpreadsheetExporter to be able to convert language ISO codes to their display names. /// This allows unit tests to use mocks to handle this functionality instead of figuring out how to construct a concrete resolver /// </summary> public interface ILanguageDisplayNameResolver { /// <summary> /// Given a language code, returns the friendly name of that language (according to the dictionary passed into the constructor) /// </summary> /// <param name="langCode"></param> /// <returns>Returns the friendly name if available. If not, returns the language code unchanged.</returns> string GetLanguageDisplayName(string langCode); } /// <summary> /// Resolves language codes to language display names based on the book's CollectionSettings /// </summary> class CollectionSettingsLanguageDisplayNameResolver : ILanguageDisplayNameResolver { private CollectionSettings CollectionSettings; public CollectionSettingsLanguageDisplayNameResolver(CollectionSettings collectionSettings) { this.CollectionSettings = collectionSettings; } public string GetLanguageDisplayName(string langCode) { return this.CollectionSettings.GetDisplayNameForLanguage(langCode); } } // Note: You can also resolve these from the book.BookInfo.MetaData.DisplayNames dictionary, but // that seems to have fewer entries than CollectionSetting's or BookData's GetDisplayNameForLanguage() function }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using Sensus.Anonymization; using Sensus.Anonymization.Anonymizers; using Sensus.Probes.User.Scripts.ProbeTriggerProperties; using Sensus.UI.Inputs; namespace Sensus.Probes.User.Scripts { /// <summary> /// The <see cref="Datum.Timestamp"/> field of a <see cref="ScriptDatum"/> indicates the time when the particular input (e.g., text box) was /// completed by the user. Compare this with <see cref="LocationTimestamp"/>, <see cref="RunTimestamp"/>, and <see cref="SubmissionTimestamp"/>. /// /// When a user submits a survey, a <see cref="ScriptDatum"/> object is submitted for each input in the survey (e.g., each text entry, /// multiple-choice item, etc.). However, if the user does not submit the survey, no such objects will be submitted. As a means of tracking /// the deployment and response/non-response of surveys, Sensus also submits an additional <see cref="ScriptRunDatum"/> object each time /// the survey is displayed to the user, regardless of whether the user ends up submitting their survey answers. /// /// </summary> public class ScriptDatum : Datum { private string _scriptId; private string _scriptName; private string _groupId; private string _inputId; private string _runId; private object _response; private string _triggerDatumId; private double? _latitude; private double? _longitude; private DateTimeOffset _runTimestamp; private DateTimeOffset? _locationTimestamp; private List<InputCompletionRecord> _completionRecords; private DateTimeOffset _submissionTimestamp; /// <summary> /// Identifier for a script. This does not change across invocations of the script. /// </summary> /// <value>The script identifier.</value> public string ScriptId { get { return _scriptId; } set { _scriptId = value; } } /// <summary> /// Descriptive name for a script. /// </summary> /// <value>The name of the script.</value> public string ScriptName { get { return _scriptName; } set { _scriptName = value; } } /// <summary> /// Identifier for a set of inputs within the script. This does not change across invocations of the script. /// </summary> /// <value>The group identifier.</value> public string GroupId { get { return _groupId; } set { _groupId = value; } } /// <summary> /// Identifier for an input within the script. This does not change across invocations of the script. /// </summary> /// <value>The input identifier.</value> public string InputId { get { return _inputId; } set { _inputId = value; } } /// <summary> /// Identifier for a particular invocation of a script. This changes for each new invocation of the script. /// </summary> /// <value>The run identifier.</value> public string RunId { get { return _runId; } set { _runId = value; } } /// <summary> /// User's response to an input within the script. /// </summary> /// <value>The response.</value> public object Response { get { return _response; } set { _response = value; } } /// <summary> /// If the script is triggered by a <see cref="Datum"/> from another probe, this is the <see cref="Datum.Id"/>. /// </summary> /// <value>The trigger datum identifier.</value> [Anonymizable("Triggering Datum ID:", typeof(StringHashAnonymizer), false)] public string TriggerDatumId { get { return _triggerDatumId; } set { _triggerDatumId = value; } } /// <summary> /// Latitude of GPS reading taken when user submitted the response (if enabled). /// </summary> /// <value>The latitude.</value> [DoubleProbeTriggerProperty] [Anonymizable(null, new Type[] { typeof(DoubleRoundingTenthsAnonymizer), typeof(DoubleRoundingHundredthsAnonymizer), typeof(DoubleRoundingThousandthsAnonymizer) }, -1)] public double? Latitude { get { return _latitude; } set { _latitude = value; } } /// <summary> /// Longitude of GPS reading taken when user submitted the response (if enabled). /// </summary> /// <value>The longitude.</value> [DoubleProbeTriggerProperty] [Anonymizable(null, new Type[] { typeof(DoubleRoundingTenthsAnonymizer), typeof(DoubleRoundingHundredthsAnonymizer), typeof(DoubleRoundingThousandthsAnonymizer) }, -1)] public double? Longitude { get { return _longitude; } set { _longitude = value; } } /// <summary> /// Timestamp of when a script survey was made available to the user for completion. /// </summary> /// <value>The run timestamp.</value> public DateTimeOffset RunTimestamp { get { return _runTimestamp; } set { _runTimestamp = value; } } /// <summary> /// Timestamp of GPS reading (if enabled). /// </summary> /// <value>The location timestamp.</value> public DateTimeOffset? LocationTimestamp { get { return _locationTimestamp; } set { _locationTimestamp = value; } } /// <summary> /// A trace of activity for the input. /// </summary> /// <value>The completion records.</value> public List<InputCompletionRecord> CompletionRecords { get { return _completionRecords; } // need setter in order for anonymizer to pick up the property (only includes writable properties) set { _completionRecords = value; } } /// <summary> /// Timestamp of when the user tapped the Submit button on the survey form. /// </summary> /// <value>The submission timestamp.</value> public DateTimeOffset SubmissionTimestamp { get { return _submissionTimestamp; } set { _submissionTimestamp = value; } } public override string DisplayDetail { get { if (_response == null) { return "No response."; } else { if (_response is IList) { IList responseList = _response as IList; return responseList.Count + " response" + (responseList.Count == 1 ? "" : "s") + "."; } else { return _response.ToString(); } } } } /// <summary> /// Gets the string placeholder value, which is the user's response. /// </summary> /// <value>The string placeholder value.</value> public override object StringPlaceholderValue { get { return _response; } } /// <summary> /// For JSON deserialization. /// </summary> private ScriptDatum() { _completionRecords = new List<InputCompletionRecord>(); } public ScriptDatum(DateTimeOffset timestamp, string scriptId, string scriptName, string groupId, string inputId, string runId, object response, string triggerDatumId, double? latitude, double? longitude, DateTimeOffset? locationTimestamp, DateTimeOffset runTimestamp, List<InputCompletionRecord> completionRecords, DateTimeOffset submissionTimestamp) : base(timestamp) { _scriptId = scriptId; _scriptName = scriptName; _groupId = groupId; _inputId = inputId; _runId = runId; _response = response; _triggerDatumId = triggerDatumId == null ? "" : triggerDatumId; _latitude = latitude; _longitude = longitude; _locationTimestamp = locationTimestamp; _runTimestamp = runTimestamp; _completionRecords = completionRecords; _submissionTimestamp = submissionTimestamp; } public override string ToString() { return base.ToString() + Environment.NewLine + "Script: " + _scriptId + Environment.NewLine + "Group: " + _groupId + Environment.NewLine + "Input: " + _inputId + Environment.NewLine + "Run: " + _runId + Environment.NewLine + "Response: " + _response + Environment.NewLine + "Latitude: " + _latitude + Environment.NewLine + "Longitude: " + _longitude + Environment.NewLine + "Location Timestamp: " + _locationTimestamp + Environment.NewLine + "Run Timestamp: " + _runTimestamp + Environment.NewLine + "Submission Timestamp: " + _submissionTimestamp; } } }
/* * 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 ParquetSharp.Bytes { using System; using ParquetSharp.External; /** * Based on DataOutputStream but in little endian and without the String/char methods * * @author Julien Le Dem * */ public class LittleEndianDataOutputStream : OutputStream { private readonly OutputStream @out; /** * Creates a new data output stream to write data to the specified * underlying output stream. The counter <code>written</code> is * set to zero. * * @param out the underlying output stream, to be saved for later * use. * @see java.io.FilterOutputStream#out */ public LittleEndianDataOutputStream(OutputStream @out) { this.@out = @out; } /** * Writes the specified byte (the low eight bits of the argument * <code>b</code>) to the underlying output stream. If no exception * is thrown, the counter <code>written</code> is incremented by * <code>1</code>. * <p> * Implements the <code>write</code> method of <code>OutputStream</code>. * * @param b the <code>byte</code> to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public override void WriteByte(byte b) { @out.WriteByte(b); } /** * Writes <code>len</code> bytes from the specified byte array * starting at offset <code>off</code> to the underlying output stream. * If no exception is thrown, the counter <code>written</code> is * incremented by <code>len</code>. * * @param b the data. * @param off the start offset in the data. * @param len the number of bytes to write. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public override void Write(byte[] b, int off, int len) { @out.Write(b, off, len); } /** * Flushes this data output stream. This forces any buffered output * bytes to be written out to the stream. * <p> * The <code>flush</code> method of <code>DataOutputStream</code> * calls the <code>flush</code> method of its underlying output stream. * * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out * @see java.io.OutputStream#flush() */ public override void Flush() { @out.Flush(); } /** * Writes a <code>boolean</code> to the underlying output stream as * a 1-byte value. The value <code>true</code> is written out as the * value <code>(byte)1</code>; the value <code>false</code> is * written out as the value <code>(byte)0</code>. If no exception is * thrown, the counter <code>written</code> is incremented by * <code>1</code>. * * @param v a <code>boolean</code> value to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeBoolean(bool v) { @out.WriteByte(v ? (byte)1 : (byte)0); } /** * Writes out a <code>byte</code> to the underlying output stream as * a 1-byte value. If no exception is thrown, the counter * <code>written</code> is incremented by <code>1</code>. * * @param v a <code>byte</code> value to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeByte(int v) { @out.WriteByte((byte)v); } /** * Writes a <code>short</code> to the underlying output stream as two * bytes, low byte first. If no exception is thrown, the counter * <code>written</code> is incremented by <code>2</code>. * * @param v a <code>short</code> to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeShort(int v) { @out.WriteByte((byte)((uint)v >> 0)); @out.WriteByte((byte)((uint)v >> 8)); } /** * Writes an <code>int</code> to the underlying output stream as four * bytes, low byte first. If no exception is thrown, the counter * <code>written</code> is incremented by <code>4</code>. * * @param v an <code>int</code> to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeInt(int v) { // TODO: see note in LittleEndianDataInputStream: maybe faster // to use Integer.reverseBytes() and then writeInt, or a ByteBuffer // approach @out.WriteByte((byte)((uint)v >> 0)); @out.WriteByte((byte)((uint)v >> 8)); @out.WriteByte((byte)((uint)v >> 16)); @out.WriteByte((byte)((uint)v >> 24)); } private byte[] writeBuffer = new byte[8]; public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /** * Writes a <code>long</code> to the underlying output stream as eight * bytes, low byte first. In no exception is thrown, the counter * <code>written</code> is incremented by <code>8</code>. * * @param v a <code>long</code> to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out */ public void writeLong(long v) { writeBuffer[7] = (byte)((ulong)v >> 56); writeBuffer[6] = (byte)((ulong)v >> 48); writeBuffer[5] = (byte)((ulong)v >> 40); writeBuffer[4] = (byte)((ulong)v >> 32); writeBuffer[3] = (byte)((ulong)v >> 24); writeBuffer[2] = (byte)((ulong)v >> 16); writeBuffer[1] = (byte)((ulong)v >> 8); writeBuffer[0] = (byte)((ulong)v >> 0); @out.Write(writeBuffer, 0, 8); } /** * Converts the float argument to an <code>int</code> using the * <code>floatToIntBits</code> method in class <code>Float</code>, * and then writes that <code>int</code> value to the underlying * output stream as a 4-byte quantity, low byte first. If no * exception is thrown, the counter <code>written</code> is * incremented by <code>4</code>. * * @param v a <code>float</code> value to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out * @see java.lang.Float#floatToIntBits(float) */ public void writeFloat(float v) { writeInt(Float.floatToIntBits(v)); } /** * Converts the double argument to a <code>long</code> using the * <code>doubleToLongBits</code> method in class <code>Double</code>, * and then writes that <code>long</code> value to the underlying * output stream as an 8-byte quantity, low byte first. If no * exception is thrown, the counter <code>written</code> is * incremented by <code>8</code>. * * @param v a <code>double</code> value to be written. * @exception IOException if an I/O error occurs. * @see java.io.FilterOutputStream#out * @see java.lang.Double#doubleToLongBits(double) */ public void writeDouble(double v) { writeLong(BitConverter.DoubleToInt64Bits(v)); } protected override void Dispose(bool disposing) { base.Dispose(disposing); IOExceptionUtils.closeQuietly(@out); } } }
// 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. // In order to convert some functionality to Visual C#, the Java Language Conversion Assistant // creates "support classes" that duplicate the original functionality. // // Support classes replicate the functionality of the original code, but in some cases they are // substantially different architecturally. Although every effort is made to preserve the // original architecture of the application in the converted project, the user should be aware that // the primary goal of these support classes is to replicate functionality, and that at times // the architecture of the resulting solution may differ somewhat. // using System; using System.IO; using System.Collections; using System.Collections.Specialized; using Alachisoft.NGroups; using Alachisoft.NGroups.Util; using Alachisoft.NGroups.Blocks; using Alachisoft.NGroups.Protocols; using Alachisoft.NGroups.Protocols.pbcast; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Serialization; using Alachisoft.NCache.Serialization.Formatters; using Alachisoft.NCache.Common; using Alachisoft.NCache.Common.DataStructures; /// <summary> /// Contains conversion support elements such as classes, interfaces and static methods. /// </summary> public class Global { static public void RegisterCompactTypes() { CompactFormatterServices.RegisterCompactType(typeof(List),81); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NCache.Common.ProductVersion), 302); CompactFormatterServices.RegisterCompactType(typeof(ViewId),82); CompactFormatterServices.RegisterCompactType(typeof(View),83); CompactFormatterServices.RegisterCompactType(typeof(PingRsp),85); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NGroups.Protocols.pbcast.Digest),87); CompactFormatterServices.RegisterCompactType(typeof(Message),89); CompactFormatterServices.RegisterCompactType(typeof(MergeView),90); CompactFormatterServices.RegisterCompactType(typeof(MergeData),91); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NGroups.Protocols.pbcast.JoinRsp), 92); CompactFormatterServices.RegisterCompactType(typeof(RequestCorrelator.HDR),93); CompactFormatterServices.RegisterCompactType(typeof(TOTAL.HDR),94); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NGroups.Protocols.pbcast.GMS.HDR),98); CompactFormatterServices.RegisterCompactType(typeof(PingHeader),103); CompactFormatterServices.RegisterCompactType(typeof(TcpHeader),104); CompactFormatterServices.RegisterCompactType(typeof(ConnectionTable.Connection.ConnectionHeader), 108); CompactFormatterServices.RegisterCompactType(typeof(HashMapBucket), 114); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NCache.Common.Net.Address), 110); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NGroups.Protocols.TCP.HearBeat), 115); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NCache.Common.Stats.HPTimeStats), 126); CompactFormatterServices.RegisterCompactType(typeof(Alachisoft.NCache.Common.Stats.HPTime), 127); CompactFormatterServices.RegisterCompactType(typeof(MessageTrace), 128); CompactFormatterServices.RegisterCompactType(typeof(ConnectInfo), 137); } /*******************************/ //Provides access to a static System.Random class instance static public System.Random Random = new System.Random(); /*******************************/ /// <summary> /// This class provides functionality not found in .NET collection-related interfaces. /// </summary> internal class ICollectionSupport { /// <summary> /// Removes all the elements from the specified collection that are contained in the target collection. /// </summary> /// <param name="target">Collection where the elements will be removed.</param> /// <param name="c">Elements to remove from the target collection.</param> /// <returns>true</returns> public static bool RemoveAll(ArrayList target, ArrayList c) { try { for (int i=0; i<c.Count; i++) { target.Remove(c[i]); } } catch (System.Exception ex) { throw ex; } return true; } /// <summary> /// Retains the elements in the target collection that are contained in the specified collection /// </summary> /// <param name="target">Collection where the elements will be removed.</param> /// <param name="c">Elements to be retained in the target collection.</param> /// <returns>true</returns> public static bool RetainAll(ArrayList target, ArrayList c) { try { for (int i = target.Count - 1; i>=0; i--) { if(!c.Contains(target[i])) target.RemoveAt(i); } } catch (System.Exception ex) { throw ex; } return true; } } /*******************************/ /// <summary> /// The class performs token processing in strings /// </summary> /// <summary> /// This class breaks a string into set of tokens and returns them one by one /// </summary> /// Hasan Khan: Originally this class was written by someone else which highly /// relied upon use of exceptions for its functionality and since it is used /// in many places in the code it could affect the performance of NCache. /// I have been asked to fix this performance bottleneck so I will rewrite this class. /// /// Design of this class is totally useless but I'm going to follow the old design /// for the sake of compatibility of rest of the code. /// /// Design flaws: /// ------------- /// 1) HasMoreTokens() works same as MoveNext /// 2) MoveNext() internally calls HasMoreTokens /// 3) Current calls NextToken /// 4) NextToken() gives the current token /// 5) Count gives the number of remaining tokens //internal class Tokenizer : IEnumerator public class Tokenizer : IEnumerator { string text; char[] delims; string[] tokens; int index; public Tokenizer(string text, string delimiters) { this.text = text; delims = delimiters.ToCharArray(); /// We do not need this function in 1x so contional compiling it /// reason: StringSplitOptions.RemoveEmptyEntries is not defined in system assembly of .net 1x tokens = text.Split(delims, StringSplitOptions.RemoveEmptyEntries); index = -1; // First call of MoveNext will put the pointer on right position. } public string NextToken() { return tokens[index]; //Hasan: this is absurd } /// <summary> /// Remaining tokens count /// </summary> public int Count //Hasan: bad design { get { if (index < tokens.Length) return tokens.Length - index - 1; else return 0; } } /// <summary> /// Determines if there are more tokens to return from text. /// Also moves the pointer to next token /// </summary> /// <returns>True if there are more tokens otherwise, false</returns> public bool HasMoreTokens() //Hasan: bad design { if (index < tokens.Length - 1) { index++; return true; } else return false; } #region IEnumerator Members /// <summary> /// Performs the same action as NextToken /// </summary> public object Current { get { return NextToken(); } } /// <summary> /// Performs the same function as HasMoreTokens /// </summary> /// <returns>True if there are more tokens otherwise, false</returns> public bool MoveNext() { return HasMoreTokens(); //Hasan: this is absurd } public void Reset() { index = -1; } #endregion } /// <summary> /// Converts an array of bytes to an array of chars /// </summary> /// <param name="byteArray">The array of bytes to convert</param> /// <returns>The new array of chars</returns> public static char[] ToCharArray(byte[] byteArray) { return System.Text.UTF8Encoding.UTF8.GetChars(byteArray); } /*******************************/ /// <summary> /// Converts the specified collection to its string representation. /// </summary> /// <param name="c">The collection to convert to string.</param> /// <returns>A string representation of the specified collection.</returns> public static string CollectionToString(ICollection c) { System.Text.StringBuilder s = new System.Text.StringBuilder(); if (c != null) { ArrayList l = new ArrayList(c); bool isDictionary = (c is BitArray || c is Hashtable || c is IDictionary || c is NameValueCollection || (l.Count > 0 && l[0] is DictionaryEntry)); for (int index = 0; index < l.Count; index++) { if (l[index] == null) s.Append("null"); else if (!isDictionary) s.Append(l[index]); else { isDictionary = true; if (c is NameValueCollection) s.Append(((NameValueCollection)c).GetKey (index)); else s.Append(((DictionaryEntry) l[index]).Key); s.Append("="); if (c is NameValueCollection) s.Append(((NameValueCollection)c).GetValues(index)[0]); else s.Append(((DictionaryEntry) l[index]).Value); } if (index < l.Count - 1) s.Append(", "); } if(isDictionary) { if(c is ArrayList) isDictionary = false; } if (isDictionary) { s.Insert(0, "{"); s.Append("}"); } else { s.Insert(0, "["); s.Append("]"); } } else s.Insert(0, "null"); return s.ToString(); } /// <summary> /// Tests if the specified object is a collection and converts it to its string representation. /// </summary> /// <param name="obj">The object to convert to string</param> /// <returns>A string representation of the specified object.</returns> public static string CollectionToString(object obj) { string result = ""; if (obj != null) { if (obj is ICollection) result = CollectionToString((ICollection)obj); else result = obj.ToString(); } else result = "null"; return result; } public static string ArrayListToString(ArrayList list) { System.Text.StringBuilder s = new System.Text.StringBuilder(); if (list != null) { s.Append("[ "); foreach (object item in list) { s.Append(item.ToString() + ","); } s.Remove(s.Length, 1); s.Append(" ]"); } else { s.Append("<null>"); } return s.ToString(); } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Text; using WmcSoft.Interop; using DWORD = System.UInt32; using VoidPtr = System.IntPtr; using HRESULT = System.Int32; using INT = System.Int32; using UINT = System.UInt32; using LONG = System.Int32; using WPARAM = System.UInt32; using LPARAM = System.IntPtr; using LRESULT = System.IntPtr; using LONG_PTR = System.IntPtr; using BOOL = System.Int32; using HDC = System.IntPtr; using HRGN = System.IntPtr; using HBITMAP = System.IntPtr; using HIMC = System.IntPtr; using HCURSOR = System.IntPtr; using RECT = WmcSoft.Interop.RECTL; using COLORREF = System.UInt32; namespace WmcSoft.Interop.TextObjectModel { [StructLayout(LayoutKind.Sequential, Pack = 4)] public class CHARFORMATW { public int cbSize; public int dwMask; public int dwEffects; public int yHeight; public int yOffset; public int crTextColor; public byte bCharSet; public byte bPitchAndFamily; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x40)] public byte[] szFaceName; public CHARFORMATW() { this.cbSize = Marshal.SizeOf(typeof(CHARFORMATW)); this.szFaceName = new byte[0x40]; } } [StructLayout(LayoutKind.Sequential)] public class PARAFORMAT { public int cbSize; public int dwMask; public short wNumbering; public short wReserved; public int dxStartIndent; public int dxRightIndent; public int dxOffset; public short wAlignment; public short cTabCount; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x20)] public int[] rgxTabs; public PARAFORMAT() { this.cbSize = Marshal.SizeOf(typeof(PARAFORMAT)); } } /// <summary> /// Defines different background styles control. /// </summary> public enum BackStyle { /// <summary> /// background should show through. /// </summary> Transparent = 0, /// <summary> /// erase background /// </summary> Opaque = 1, } /// <summary> /// Defines different hitresults /// </summary> public enum HitResult { /// <summary> /// no hit /// </summary> NoHit = 0, /// <summary> /// point is within the text's rectangle, but in a /// transparent region /// </summary> Transparent = 1, /// <summary> /// point is close to the text /// </summary> Close = 2, /// <summary> /// dead-on hit /// </summary> Hit = 3, } /// <summary> /// useful values for TxGetNaturalSize. /// </summary> public enum NaturalSize { /// <summary> /// Get a size that fits the content /// </summary> FitToContent = 1, /// <summary> /// Round to the nearest whole line. /// </summary> RoundToLine = 2 } /// <summary> /// useful values for TxDraw lViewId parameter /// </summary> public enum View { Active = 0, Inactive = -1 } /// <summary> /// used for CHANGENOTIFY.dwChangeType; indicates what happened /// for a particular change. /// </summary> public enum ChangeType { /// <summary> /// Nothing special happened /// </summary> Generic = 0, /// <summary> /// the text changed /// </summary> TextChanged = 1, /// <summary> /// A new undo action was added /// </summary> NewUndo = 2, /// <summary> /// A new redo action was added /// </summary> NewRedo = 4 } /// <summary> /// The TxGetPropertyBits and OnTxPropertyBitsChange methods can pass the following bits: /// </summary> /// <remarks>Do NOT rely on the ordering of these bits yet; the are subject to change.</remarks> [Flags] public enum PropertyBits { /// <summary> /// rich-text control /// </summary> RichText = 0x1, /// <summary> /// single vs multi-line control /// </summary> MultiLine = 2, /// <summary> /// read only text /// </summary> ReadOnly = 4, /// <summary> /// underline accelerator character /// </summary> ShowAccelerator = 8, /// <summary> /// use password char to display text /// </summary> UsePassword = 0x10, /// <summary> /// show selection when inactive /// </summary> HideSelection = 0x20, /// <summary> /// remember selection when inactive /// </summary> SaveSelection = 0x40, /// <summary> /// auto-word selection /// </summary> AutoWordSel = 0x80, /// <summary> /// vertical /// </summary> Vertical = 0x100, /// <summary> /// notification that the selection bar width has changed. /// </summary> /// <remarks>FUTURE: move this bit to the end to maintain /// the division between properties and notifications.</remarks> SelBarChange = 0x200, /// <summary> /// if set, then multi-line controls should wrap words to fit the available display /// </summary> WordWrap = 0x400, /// <summary> /// enable/disable beeping /// </summary> AllowBeep = 0x800, /// <summary> /// disable/enable dragging /// </summary> DisableDrag = 0x1000, /// <summary> /// the inset changed /// </summary> ViewInsetChange = 0x2000, /// <summary> /// /// </summary> BackStyleChange = 0x4000, /// <summary> /// /// </summary> MaxLengthChange = 0x8000, /// <summary> /// /// </summary> ScrollBarChange = 0x10000, /// <summary> /// /// </summary> CharFormatChange = 0x20000, /// <summary> /// /// </summary> ParaFormatChange = 0x40000, /// <summary> /// /// </summary> ExtentChange = 0x80000, /// <summary> /// the client rectangle changed /// </summary> ClientRectChange = 0x100000, /// <summary> /// tells the renderer to use the current background color rather than the system default for an entire line /// </summary> UseCurrentBkg = 0x200000, } /// <summary> /// passed during an EN_CHANGE notification; contains information about /// what actually happened for a change. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ChangeNotify { /// <summary> /// TEXT changed, etc /// </summary> public DWORD dwChangeType; /// <summary> /// cookie for the undo action /// </summary> public VoidPtr pvCookieData; } public delegate bool TxDrawDelegate(DWORD dw); /// <summary> /// An interface extending Microsoft's Text Object Model to provide /// extra functionality for windowless operation. In conjunction /// with ITextHost, ITextServices provides the means by which the /// the RichEdit control can be used *without* creating a window. /// </summary> [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("8d33f740-cf58-11ce-a89d-00aa006cadc5")] public interface ITextServices { /// <summary> /// Generic Send Message interface /// </summary> /// <param name="msg"></param> /// <param name="wparam"></param> /// <param name="lparam"></param> /// <param name="plresult"></param> /// <returns></returns> [PreserveSig] HRESULT TxSendMessage(UINT msg, WPARAM wparam, LPARAM lparam, IntPtr plresult); /// <summary> /// Rendering /// </summary> /// <param name="dwDrawAspect"></param> /// <param name="lindex"></param> /// <param name="pvAspect"></param> /// <param name="ptd"></param> /// <param name="hdcDraw"></param> /// <param name="hicTargetDev"></param> /// <param name="lprcBounds"></param> /// <param name="lprcWBounds"></param> /// <param name="lprcUpdate"></param> /// <param name="callback"></param> /// <param name="dwContinue"></param> /// <param name="lViewId"></param> /// <returns></returns> [PreserveSig] HRESULT TxDraw( DWORD dwDrawAspect, LONG lindex, VoidPtr pvAspect, [In, MarshalAs(UnmanagedType.Struct)] DVTARGETDEVICE ptd, HDC hdcDraw, HDC hicTargetDev, [In, MarshalAs(UnmanagedType.Struct)] RECTL lprcBounds, [In, MarshalAs(UnmanagedType.Struct)] RECTL lprcWBounds, [In, MarshalAs(UnmanagedType.Struct)] RECT lprcUpdate, [MarshalAs(UnmanagedType.FunctionPtr)] TxDrawDelegate callback, DWORD dwContinue, LONG lViewId); /// <summary> /// Horizontal scrollbar support /// </summary> /// <param name="plMin"></param> /// <param name="plMax"></param> /// <param name="plPos"></param> /// <param name="plPage"></param> /// <param name="pfEnabled"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetHScroll(out LONG plMin, out LONG plMax, out LONG plPos, out LONG plPage, out BOOL pfEnabled); /// <summary> /// Vertical scrollbar support /// </summary> /// <param name="plMin"></param> /// <param name="plMax"></param> /// <param name="plPos"></param> /// <param name="plPage"></param> /// <param name="pfEnabled"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetVScroll(out LONG plMin, out LONG plMax, out LONG plPos, out LONG plPage, out BOOL pfEnabled); /// <summary> /// Setcursor /// </summary> /// <param name="dwDrawAspect"></param> /// <param name="lindex"></param> /// <param name="pvAspect"></param> /// <param name="ptd"></param> /// <param name="hdcDraw"></param> /// <param name="hicTargetDev"></param> /// <param name="lprcClient"></param> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> [PreserveSig] HRESULT OnTxSetCursor( DWORD dwDrawAspect, LONG lindex, VoidPtr pvAspect, [In, MarshalAs(UnmanagedType.Struct)] DVTARGETDEVICE ptd, HDC hdcDraw, HDC hicTargetDev, [In, MarshalAs(UnmanagedType.Struct)] RECT lprcClient, INT x, INT y); /// <summary> /// Hit-test /// </summary> /// <param name="dwDrawAspect"></param> /// <param name="lindex"></param> /// <param name="pvAspect"></param> /// <param name="ptd"></param> /// <param name="hdcDraw"></param> /// <param name="hicTargetDev"></param> /// <param name="lprcClient"></param> /// <param name="x"></param> /// <param name="y"></param> /// <param name="pHitResult"></param> /// <returns></returns> [PreserveSig] HRESULT TxQueryHitPoint( DWORD dwDrawAspect, LONG lindex, VoidPtr pvAspect, [In, MarshalAs(UnmanagedType.Struct)] DVTARGETDEVICE ptd, HDC hdcDraw, HDC hicTargetDev, [In, MarshalAs(UnmanagedType.Struct)] RECT lprcClient, INT x, INT y, [Out, MarshalAs(UnmanagedType.U4)] HitResult pHitResult); /// <summary> /// Inplace activate notification /// </summary> /// <param name="lprcClient"></param> /// <returns></returns> [PreserveSig] HRESULT OnTxInPlaceActivate([In, MarshalAs(UnmanagedType.Struct)] RECT lprcClient); /// <summary> /// Inplace deactivate notification /// </summary> void OnTxInPlaceDeactivate(); /// <summary> /// UI activate notification /// </summary> /// <returns></returns> void OnTxUIActivate(); /// <summary> /// UI deactivate notification /// </summary> void OnTxUIDeactivate(); /// <summary> /// Get text in control /// </summary> /// <param name="pbstrText"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetText([MarshalAs(UnmanagedType.BStr)] out string pbstrText); /// <summary> /// Set text in control /// </summary> /// <param name="pszText"></param> /// <returns></returns> [PreserveSig] HRESULT TxSetText(StringBuilder pszText); /// <summary> /// Get x position of /// </summary> /// <param name="retVal"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetCurTargetX(out LONG retVal); /// <summary> /// Get baseline position /// </summary> /// <param name="retVal"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetBaseLinePos(out LONG retVal); /// <summary> /// Get Size to fit / Natural size /// </summary> /// <param name="dwAspect"></param> /// <param name="hdcDraw"></param> /// <param name="hicTargetDev"></param> /// <param name="ptd"></param> /// <param name="dwMode"></param> /// <param name="psizelExtent"></param> /// <param name="pwidth"></param> /// <param name="pheight"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetNaturalSize( DWORD dwAspect, HDC hdcDraw, HDC hicTargetDev, [In, MarshalAs(UnmanagedType.Struct)] DVTARGETDEVICE ptd, DWORD dwMode, [In, MarshalAs(UnmanagedType.Struct)] SIZEL psizelExtent, [In, Out] LONG pwidth, [In, Out] LONG pheight); /// <summary> /// Drag & drop /// </summary> /// <param name="ppDropTarget"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetDropTarget([Out, MarshalAs(UnmanagedType.Interface)] IDropTarget ppDropTarget); /// <summary> /// Bulk bit property change notifications /// </summary> /// <param name="dwMask"></param> /// <param name="dwBits"></param> /// <returns></returns> [PreserveSig] HRESULT OnTxPropertyBitsChange(DWORD dwMask, DWORD dwBits); /// <summary> /// Fetch the cached drawing size /// </summary> /// <param name="pdwWidth"></param> /// <param name="pdwHeight"></param> /// <returns></returns> [PreserveSig] HRESULT TxGetCachedSize(out DWORD pdwWidth, out DWORD pdwHeight); } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("c5bdd8d0-d26e-11ce-a89e-00aa006cadc5")] public interface ITextHost { /// <summary> /// Get the DC for the host /// </summary> /// <returns></returns> [PreserveSig] HDC TxGetDC(); /// <summary> /// /// </summary> /// <param name="hdc"></param> /// <returns></returns> [PreserveSig] INT TxReleaseDC(HDC hdc); /// <summary> /// Show the scroll bar /// </summary> /// <param name="fnBar"></param> /// <param name="fShow"></param> /// <returns></returns> [PreserveSig] BOOL TxShowScrollBar(INT fnBar, BOOL fShow); //@cmember Enable the scroll bar [PreserveSig] BOOL TxEnableScrollBar(INT fuSBFlags, INT fuArrowflags); //@cmember Set the scroll range [PreserveSig] BOOL TxSetScrollRange( INT fnBar, LONG nMinPos, INT nMaxPos, BOOL fRedraw); //@cmember Set the scroll position [PreserveSig] BOOL TxSetScrollPos(INT fnBar, INT nPos, BOOL fRedraw); //@cmember InvalidateRect [PreserveSig] void TxInvalidateRect([In] RECT prc, BOOL fMode); //@cmember Send a WM_PAINT to the window [PreserveSig] void TxViewChange(BOOL fUpdate); //@cmember Create the caret [PreserveSig] BOOL TxCreateCaret(HBITMAP hbmp, INT xWidth, INT yHeight); //@cmember Show the caret [PreserveSig] BOOL TxShowCaret(BOOL fShow); //@cmember Set the caret position [PreserveSig] BOOL TxSetCaretPos(INT x, INT y); //@cmember Create a timer with the specified timeout [PreserveSig] BOOL TxSetTimer(UINT idTimer, UINT uTimeout); //@cmember Destroy a timer [PreserveSig] void TxKillTimer(UINT idTimer); //@cmember Scroll the content of the specified window's client area [PreserveSig] void TxScrollWindowEx( INT dx, INT dy, [In] RECT lprcScroll, [In] RECT lprcClip, HRGN hrgnUpdate, [In, Out] ref RECT lprcUpdate, UINT fuScroll); //@cmember Get mouse capture [PreserveSig] void TxSetCapture(BOOL fCapture); //@cmember Set the focus to the text window [PreserveSig] void TxSetFocus(); //@cmember Establish a new cursor shape [PreserveSig] void TxSetCursor(HCURSOR hcur, BOOL fText); //@cmember Converts screen coordinates of a specified point to the client coordinates [PreserveSig] BOOL TxScreenToClient([In, Out] POINTL lppt); //@cmember Converts the client coordinates of a specified point to screen coordinates [PreserveSig] BOOL TxClientToScreen([In, Out] POINTL lppt); //@cmember Request host to activate text services [PreserveSig] HRESULT TxActivate([Out] IntPtr plOldState); //@cmember Request host to deactivate text services [PreserveSig] HRESULT TxDeactivate(LONG lNewState); //@cmember Retrieves the coordinates of a window's client area [PreserveSig] HRESULT TxGetClientRect([In, Out] RECT prc); //@cmember Get the view rectangle relative to the inset [PreserveSig] HRESULT TxGetViewInset([In, Out] RECT prc); //@cmember Get the default character format for the text [PreserveSig] HRESULT TxGetCharFormat([Out] out CHARFORMATW ppCF); //@cmember Get the default paragraph format for the text [PreserveSig] HRESULT TxGetParaFormat([Out] out PARAFORMAT ppPF); //@cmember Get the background color for the window [PreserveSig] COLORREF TxGetSysColor(int nIndex); //@cmember Get the background (either opaque or transparent) [PreserveSig] HRESULT TxGetBackStyle(IntPtr pstyle); //@cmember Get the maximum length for the text [PreserveSig] HRESULT TxGetMaxLength(IntPtr plength); //@cmember Get the bits representing requested scroll bars for the window [PreserveSig] HRESULT TxGetScrollBars(IntPtr pdwScrollBar); //@cmember Get the character to display for password input [PreserveSig] HRESULT TxGetPasswordChar(IntPtr pch); //@cmember Get the accelerator character [PreserveSig] HRESULT TxGetAcceleratorPos(IntPtr pcp); //@cmember Get the native size [PreserveSig] HRESULT TxGetExtent([In] ref SIZEL lpExtent); //@cmember Notify host that default character format has changed [PreserveSig] HRESULT OnTxCharFormatChange([In] ref CHARFORMATW pcf); //@cmember Notify host that default paragraph format has changed [PreserveSig] HRESULT OnTxParaFormatChange([In] ref PARAFORMAT ppf); //@cmember Bulk access to bit properties [PreserveSig] HRESULT TxGetPropertyBits(DWORD dwMask, IntPtr pdwBits); //@cmember Notify host of events [PreserveSig] HRESULT TxNotify(DWORD iNotify, [MarshalAs(UnmanagedType.AsAny)] object pv); // Far East Methods for getting the Input Context [PreserveSig] HIMC TxImmGetContext(); [PreserveSig] void TxImmReleaseContext(HIMC himc); //@cmember Returns HIMETRIC size of the control bar. [PreserveSig] HRESULT TxGetSelectionBarWidth(IntPtr lSelBarWidth); } [ComVisible(true)] [ComDefaultInterface(typeof(ITextHost))] public class TextServiceHost : ITextHost, System.IServiceProvider { #region Interop [DllImport("riched20.dll", CallingConvention = CallingConvention.StdCall, PreserveSig = true)] [return: MarshalAs(UnmanagedType.Error)] static extern int CreateTextServices( [In, MarshalAs(UnmanagedType.IUnknown)] object punkOuter, [In, MarshalAs(UnmanagedType.Interface)] ITextHost pITextHost, [MarshalAs(UnmanagedType.IUnknown)] out object ppUnk); #endregion #region Lifecycle public TextServiceHost() { dwBits = (int)(PropertyBits.RichText | PropertyBits.MultiLine | PropertyBits.WordWrap | PropertyBits.UseCurrentBkg); } #endregion #region IServiceProvider Members private object services; public object GetService(Type serviceType) { if (services == null) { object none = null; ITextHost host = (ITextHost)this; int errorCode = CreateTextServices(none, host, out services); Marshal.ThrowExceptionForHR(errorCode); } if (services != null && serviceType.IsAssignableFrom(services.GetType())) { return services; } return null; } public T GetService<T>() where T : class { return this.GetService(typeof(T)) as T; } #endregion #region ITextHost Members IntPtr ITextHost.TxGetDC() { return IntPtr.Zero; } int ITextHost.TxReleaseDC(IntPtr hdc) { return 1; } int ITextHost.TxShowScrollBar(int fnBar, int fShow) { return 0; } int ITextHost.TxEnableScrollBar(int fuSBFlags, int fuArrowflags) { return 0; } int ITextHost.TxSetScrollRange(int fnBar, int nMinPos, int nMaxPos, int fRedraw) { return 0; } int ITextHost.TxSetScrollPos(int fnBar, int nPos, int fRedraw) { return 0; } void ITextHost.TxInvalidateRect(RECTL prc, int fMode) { } void ITextHost.TxViewChange(int fUpdate) { } int ITextHost.TxCreateCaret(IntPtr hbmp, int xWidth, int yHeight) { return 0; } int ITextHost.TxShowCaret(int fShow) { return 0; } int ITextHost.TxSetCaretPos(int x, int y) { return 0; } int ITextHost.TxSetTimer(uint idTimer, uint uTimeout) { return 0; } void ITextHost.TxKillTimer(uint idTimer) { } void ITextHost.TxScrollWindowEx(int dx, int dy, RECTL lprcScroll, RECTL lprcClip, IntPtr hrgnUpdate, ref RECTL lprcUpdate, uint fuScroll) { } void ITextHost.TxSetCapture(int fCapture) { } void ITextHost.TxSetFocus() { } void ITextHost.TxSetCursor(IntPtr hcur, int fText) { } int ITextHost.TxScreenToClient(POINTL lppt) { return 0; } int ITextHost.TxClientToScreen(POINTL lppt) { return 0; } int ITextHost.TxActivate(IntPtr plOldState) { if (plOldState != IntPtr.Zero) { Marshal.WriteInt32(plOldState, 0); } return 0; } int ITextHost.TxDeactivate(int lNewState) { return 0; } int ITextHost.TxGetClientRect(RECTL prc) { rcClient = prc; return 0; } RECTL rcClient; int ITextHost.TxGetViewInset(RECTL prc) { rcViewInset = prc; return 0; } RECTL rcViewInset; int ITextHost.TxGetCharFormat(out CHARFORMATW ppCF) { ppCF = charFormat; System.Diagnostics.Debugger.Break(); return 0; } CHARFORMATW charFormat = new CHARFORMATW(); int ITextHost.TxGetParaFormat(out PARAFORMAT ppPF) { ppPF = paraFormat; return 0; } PARAFORMAT paraFormat = new PARAFORMAT(); uint ITextHost.TxGetSysColor(int nIndex) { return (uint)System.Drawing.SystemColors.Window.ToArgb(); } int ITextHost.TxGetBackStyle(IntPtr pstyle) { return HResult.E_NOTIMPL; } int ITextHost.TxGetMaxLength(IntPtr plength) { return HResult.E_NOTIMPL; } int ITextHost.TxGetScrollBars(IntPtr pdwScrollBar) { return HResult.E_NOTIMPL; } int ITextHost.TxGetPasswordChar(IntPtr pch) { Marshal.WriteInt16(pch, '*'); return 0; } int ITextHost.TxGetAcceleratorPos(IntPtr pcp) { return HResult.E_NOTIMPL; } int ITextHost.TxGetExtent(ref SIZEL lpExtent) { return HResult.E_NOTIMPL; } int ITextHost.OnTxCharFormatChange(ref CHARFORMATW pcf) { return HResult.E_NOTIMPL; } int ITextHost.OnTxParaFormatChange(ref PARAFORMAT ppf) { return HResult.E_NOTIMPL; } int ITextHost.TxGetPropertyBits(uint dwMask, IntPtr pdwBits) { Marshal.WriteInt32(pdwBits, dwBits); return 0; } int dwBits; int ITextHost.TxNotify(uint iNotify, object pv) { return 0; } IntPtr ITextHost.TxImmGetContext() { return IntPtr.Zero; } void ITextHost.TxImmReleaseContext(IntPtr himc) { } int ITextHost.TxGetSelectionBarWidth(IntPtr lSelBarWidth) { Marshal.WriteInt64(lSelBarWidth, 100); return 0; } #endregion } } #if C //+----------------------------------------------------------------------- // Factories //------------------------------------------------------------------------ // Text Services factory STDAPI CreateTextServices( IUnknown *punkOuter, ITextHost *pITextHost, IUnknown **ppUnk); typedef HRESULT (STDAPICALLTYPE * PCreateTextServices)( IUnknown *punkOuter, ITextHost *pITextHost, IUnknown **ppUnk); #endif
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Client.Datastream { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Cache; using Apache.Ignite.Core.Client.Datastream; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.Impl.Client.Datastream; using NUnit.Framework; /// <summary> /// Tests for <see cref="IDataStreamerClient{TK,TV}"/>. /// </summary> public class DataStreamerClientTest : ClientTestBase { /** */ private const int GridCount = 3; /// <summary> /// Initializes a new instance of <see cref="DataStreamerClientTest"/>. /// </summary> public DataStreamerClientTest() : this(false) { // No-op. } /// <summary> /// Initializes a new instance of <see cref="DataStreamerClientTest"/>. /// </summary> public DataStreamerClientTest(bool enablePartitionAwareness) : base(GridCount, enableSsl: false, enablePartitionAwareness: enablePartitionAwareness) { // No-op. } /// <summary> /// Tests basic streaming with default options. /// </summary> [Test] public void TestBasicStreaming() { var cache = GetClientCache<string>(); using (var streamer = Client.GetDataStreamer<int, string>(cache.Name)) { Assert.AreEqual(cache.Name, streamer.CacheName); streamer.Add(1, "1"); streamer.Add(2, "2"); } Assert.AreEqual("1", cache[1]); Assert.AreEqual("2", cache[2]); } /// <summary> /// Tests add and remove operations combined. /// </summary> [Test] public void TestAddRemoveOverwrite() { var cache = GetClientCache<int>(); cache.PutAll(Enumerable.Range(1, 10).ToDictionary(x => x, x => x + 1)); var options = new DataStreamerClientOptions {AllowOverwrite = true}; using (var streamer = Client.GetDataStreamer<int, object>(cache.Name, options)) { streamer.Add(1, 11); streamer.Add(20, 20); foreach (var key in new[] {2, 4, 6, 7, 8, 9}) { streamer.Remove(key); } // Remove with null streamer.Add(10, null); } var resKeys = cache.GetAll(Enumerable.Range(1, 30)) .Select(x => x.Key) .OrderBy(x => x) .ToArray(); Assert.AreEqual(11, cache.Get(1)); Assert.AreEqual(20, cache.Get(20)); Assert.AreEqual(4, cache.GetSize()); Assert.AreEqual(new[] {1, 3, 5, 20}, resKeys); } /// <summary> /// Tests automatic flush when buffer gets full. /// </summary> [Test] public void TestAutoFlushOnFullBuffer() { var cache = GetClientCache<string>(); var keys = TestUtils.GetPrimaryKeys(GetIgnite(), cache.Name).Take(10).ToArray(); // Set server buffers to 1 so that server always flushes the data. var options = new DataStreamerClientOptions<int, int> { PerNodeBufferSize = 3 }; using (var streamer = Client.GetDataStreamer( cache.Name, options)) { streamer.Add(keys[1], 1); Assert.AreEqual(0, cache.GetSize()); streamer.Add(keys[2], 2); Assert.AreEqual(0, cache.GetSize()); streamer.Add(keys[3], 3); TestUtils.WaitForTrueCondition(() => cache.GetSize() == 3); } } /// <summary> /// Tests manual (explicit) flush. /// </summary> [Test] public void TestManualFlush() { var cache = GetClientCache<int>(); using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { streamer.Add(1, 1); streamer.Add(2, 2); streamer.Flush(); streamer.Add(3, 3); Assert.AreEqual(2, cache.GetSize()); Assert.AreEqual(1, cache[1]); Assert.AreEqual(2, cache[2]); streamer.Flush(); Assert.AreEqual(3, cache.GetSize()); Assert.AreEqual(3, cache[3]); } } /// <summary> /// Tests that <see cref="IDataStreamerClient{TK,TV}.Remove"/> throws an exception when /// <see cref="DataStreamerClientOptions.AllowOverwrite"/> is not enabled. /// </summary> [Test] public void TestRemoveNoAllowOverwriteThrows() { var cache = GetClientCache<string>(); using (var streamer = Client.GetDataStreamer<int, string>(cache.Name)) { var ex = Assert.Throws<IgniteClientException>(() => streamer.Remove(1)); Assert.AreEqual("DataStreamer can't remove data when AllowOverwrite is false.", ex.Message); } } /// <summary> /// Tests streaming of relatively long list of entries to verify multiple buffer flush correctness. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestStreamLongList() { var cache = GetClientCache<int>(); const int count = 50000; using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { for (var k = 0; k < count; k++) { streamer.Add(k, -k); } } Assert.AreEqual(count, cache.GetSize()); Assert.AreEqual(-2, cache[2]); Assert.AreEqual(-200, cache[200]); } /// <summary> /// Tests streamer usage from multiple threads. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestStreamMultithreaded() { var cache = GetClientCache<int>(); const int count = 250000; int id = 0; using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { TestUtils.RunMultiThreaded(() => { while (true) { var key = Interlocked.Increment(ref id); if (key > count) { break; } // ReSharper disable once AccessToDisposedClosure streamer.Add(key, key + 2); } }, 8); } Assert.AreEqual(count, cache.GetSize()); Assert.AreEqual(4, cache[2]); Assert.AreEqual(22, cache[20]); } /// <summary> /// Tests streamer usage with Parallel.For, which dynamically allocates threads to perform work. /// This test verifies backpressure behavior quite well. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestStreamParallelFor() { var cache = GetClientCache<int>(); const int count = 250000; using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { // ReSharper disable once AccessToDisposedClosure Parallel.For(0, count, i => streamer.Add(i, i + 2)); streamer.Flush(); CheckArrayPoolLeak(streamer); } Assert.AreEqual(count, cache.GetSize()); Assert.AreEqual(4, cache[2]); Assert.AreEqual(22, cache[20]); } /// <summary> /// Tests that disposing the streamer without adding any data does nothing. /// </summary> [Test] public void TestDisposeWithNoDataAdded() { var cache = GetClientCache<int>(); using (Client.GetDataStreamer<int, int>(cache.Name)) { // No-op. } Assert.AreEqual(0, cache.GetSize()); } /// <summary> /// Tests that closing the streamer without adding any data does nothing. /// </summary> [Test] public void TestCloseWithNoDataAdded([Values(true, false)] bool cancel) { var cache = GetClientCache<int>(); using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { streamer.Close(cancel); } Assert.AreEqual(0, cache.GetSize()); } /// <summary> /// Tests that enabling <see cref="DataStreamerClientOptions.SkipStore"/> causes cache store to be skipped /// during streaming. /// </summary> [Test] public void TestSkipStoreDoesNotInvokeCacheStore([Values(true, false)] bool allowOverwrite) { var serverCache = Ignition.GetIgnite().CreateCache<int, int>(new CacheConfiguration { Name = TestUtils.TestName, CacheStoreFactory = new BlockingCacheStore(), WriteThrough = true }); var options = new DataStreamerClientOptions { SkipStore = true, AllowOverwrite = allowOverwrite }; BlockingCacheStore.Block(); using (var streamer = Client.GetDataStreamer<int, int>(serverCache.Name, options)) { foreach (var x in Enumerable.Range(1, 300)) { streamer.Add(x, -x); } } Assert.AreEqual(300, serverCache.GetSize()); Assert.AreEqual(-100, serverCache[100]); } /// <summary> /// Tests that add method gets blocked when the number of active flush operations for a node /// exceeds <see cref="DataStreamerClientOptions.PerNodeParallelOperations"/>. /// </summary> [Test] public void TestExceedingPerNodeParallelOperationsBlocksAddMethod() { var serverCache = Ignition.GetIgnite().CreateCache<int, int>(new CacheConfiguration { Name = TestUtils.TestName, CacheStoreFactory = new BlockingCacheStore(), WriteThrough = true }); var options = new DataStreamerClientOptions { PerNodeParallelOperations = 2, PerNodeBufferSize = 1, AllowOverwrite = true // Required for cache store to be invoked. }; // Get primary keys for one of the nodes. var keys = TestUtils.GetPrimaryKeys(Ignition.GetIgnite(), serverCache.Name).Take(5).ToArray(); using (var streamer = Client.GetDataStreamer<int, int>(serverCache.Name, options)) { // Block writes and add data. BlockingCacheStore.Block(); streamer.Add(keys[1], 1); streamer.Add(keys[2], 2); // ReSharper disable once AccessToDisposedClosure var task = Task.Factory.StartNew(() => streamer.Add(keys[3], 3)); // Task is blocked because two streamer operations are already in progress. Assert.IsFalse(TestUtils.WaitForCondition(() => task.IsCompleted, 500)); BlockingCacheStore.Unblock(); TestUtils.WaitForTrueCondition(() => task.IsCompleted, 500); } Assert.AreEqual(3, serverCache.GetSize()); } /// <summary> /// Tests that <see cref="DataStreamerClientOptions{TK,TV}"/> have correct default values. /// </summary> [Test] public void TestOptionsHaveCorrectDefaults() { using (var streamer = Client.GetDataStreamer<int, int>(CacheName)) { var opts = streamer.Options; Assert.AreEqual(DataStreamerClientOptions.DefaultPerNodeBufferSize, opts.PerNodeBufferSize); Assert.AreEqual(DataStreamerClientOptions.DefaultPerNodeParallelOperations, opts.PerNodeParallelOperations); Assert.AreEqual(Environment.ProcessorCount * 4, opts.PerNodeParallelOperations); Assert.AreEqual(TimeSpan.Zero, opts.AutoFlushInterval); Assert.IsNull(opts.Receiver); Assert.IsFalse(opts.AllowOverwrite); Assert.IsFalse(opts.SkipStore); Assert.IsFalse(opts.ReceiverKeepBinary); } } /// <summary> /// Tests that option values are validated on set. /// </summary> [Test] public void TestInvalidOptionValuesCauseArgumentException() { var opts = new DataStreamerClientOptions(); Assert.Throws<ArgumentException>(() => opts.PerNodeBufferSize = -1); Assert.Throws<ArgumentException>(() => opts.PerNodeParallelOperations = -1); } /// <summary> /// Tests that flush throws correct exception when cache does not exist. /// </summary> [Test] public void TestFlushThrowsWhenCacheDoesNotExist() { var streamer = Client.GetDataStreamer<int, int>("bad-cache-name"); streamer.Add(1, 1); var ex = Assert.Throws<AggregateException>(() => streamer.Flush()); StringAssert.StartsWith("Cache does not exist", ex.GetBaseException().Message); // Streamer is closed because of the flush failure. Assert.IsTrue(streamer.IsClosed); } /// <summary> /// Tests that dispose throws correct exception when cache does not exist. /// </summary> [Test] public void TestDisposeThrowsWhenCacheDoesNotExist() { var streamer = Client.GetDataStreamer<int, int>("bad-cache-name"); streamer.Add(1, 1); Assert.IsFalse(streamer.IsClosed); var ex = Assert.Throws<AggregateException>(() => streamer.Dispose()); StringAssert.StartsWith("Cache does not exist", ex.GetBaseException().Message); Assert.IsTrue(streamer.IsClosed); } #if NETCOREAPP // TODO: IGNITE-15710 /// <summary> /// Tests that flush throws when exception happens in cache store. /// </summary> [Test] public void TestFlushThrowsOnCacheStoreException() { var serverCache = Ignition.GetIgnite().CreateCache<int, int>(new CacheConfiguration { Name = TestUtils.TestName, CacheStoreFactory = new BlockingCacheStore(), WriteThrough = true }); var options = new DataStreamerClientOptions { AllowOverwrite = true // Required for cache store to be invoked. }; var streamer = Client.GetDataStreamer<int, int>(serverCache.Name, options); streamer.Remove(1); var ex = Assert.Throws<AggregateException>(() => streamer.Flush()); StringAssert.Contains("Failed to finish operation (too many remaps)", ex.GetBaseException().Message); // Streamer is closed because of the flush failure. Assert.IsTrue(streamer.IsClosed); } #endif /// <summary> /// Tests that all add/remove operations throw <see cref="ObjectDisposedException"/> when streamer is closed. /// </summary> [Test] public void TestAllOperationsThrowWhenStreamerIsClosed() { var options = new DataStreamerClientOptions { AllowOverwrite = true }; var streamer = Client.GetDataStreamer<int, int>(CacheName, options); streamer.Close(true); Assert.Throws<ObjectDisposedException>(() => streamer.Add(1, 1)); Assert.Throws<ObjectDisposedException>(() => streamer.Remove(1)); Assert.Throws<ObjectDisposedException>(() => streamer.Flush()); Assert.Throws<ObjectDisposedException>(() => streamer.FlushAsync()); } /// <summary> /// Tests that Dispose and Close methods can be called multiple times. /// </summary> [Test] public void TestMultipleCloseAndDisposeCallsAreAllowed() { using (var streamer = Client.GetDataStreamer<int, int>(CacheName)) { streamer.Add(1, 2); streamer.Close(cancel: false); streamer.Dispose(); streamer.Close(true); streamer.Close(false); streamer.CloseAsync(true).Wait(); streamer.CloseAsync(false).Wait(); } Assert.AreEqual(2, GetCache<int>()[1]); } /// <summary> /// Tests that cancelled streamer discards buffered data. /// </summary> [Test] public void TestCloseCancelDiscardsBufferedData() { using (var streamer = Client.GetDataStreamer<int, int>(CacheName)) { streamer.Add(1, 1); streamer.Add(2, 2); streamer.Close(cancel: true); } Assert.AreEqual(0, GetCache<int>().GetSize()); } /// <summary> /// Tests that async continuation does not happen on socket receiver system thread. /// </summary> [Test] public void TestFlushAsyncContinuationDoesNotRunOnSocketReceiverThread() { var cache = GetClientCache<int>(); using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { streamer.Add(1, 1); streamer.FlushAsync().ContinueWith(t => { var trace = new StackTrace().ToString(); StringAssert.DoesNotContain("ClientSocket", trace); }, TaskContinuationOptions.ExecuteSynchronously).Wait(); } } /// <summary> /// Tests data streamer with a receiver. /// </summary> [Test] public void TestStreamReceiver() { var cache = GetClientCache<int>(); var options = new DataStreamerClientOptions<int, int> { Receiver = new StreamReceiverAddOne() }; using (var streamer = Client.GetDataStreamer(cache.Name, options)) { streamer.Add(1, 1); } Assert.AreEqual(2, cache[1]); } /// <summary> /// Tests stream receiver in binary mode. /// </summary> [Test] public void TestStreamReceiverKeepBinary() { var cache = GetClientCache<Test>().WithKeepBinary<int, IBinaryObject>(); var options = new DataStreamerClientOptions<int, IBinaryObject> { Receiver = new StreamReceiverAddTwoKeepBinary(), ReceiverKeepBinary = true }; using (var streamer = Client.GetDataStreamer(cache.Name, options)) { streamer.Add(1, Client.GetBinary().ToBinary<IBinaryObject>(new Test {Val = 3})); } Assert.AreEqual(5, cache[1].Deserialize<Test>().Val); } /// <summary> /// Tests that flush throws when exception happens in stream receiver. /// </summary> [Test] public void TestFlushThrowsOnExceptionInStreamReceiver() { var options = new DataStreamerClientOptions<int, int> { Receiver = new StreamReceiverThrowException() }; var streamer = Client.GetDataStreamer(CacheName, options); streamer.Add(1, 1); var ex = Assert.Throws<AggregateException>(() => streamer.Flush()); var clientEx = (IgniteClientException) ex.GetBaseException(); StringAssert.Contains("Failed to finish operation (too many remaps)", clientEx.Message); } /// <summary> /// Tests that flush throws when exception happens during stream receiver deserialization. /// </summary> [Test] public void TestFlushThrowsOnExceptionInStreamReceiverReadBinary() { var options = new DataStreamerClientOptions<int, int> { Receiver = new StreamReceiverReadBinaryThrowException() }; var streamer = Client.GetDataStreamer(CacheName, options); streamer.Add(1, 1); var ex = Assert.Throws<AggregateException>(() => streamer.Flush()); var clientEx = (IgniteClientException) ex.GetBaseException(); StringAssert.Contains("Failed to finish operation (too many remaps)", clientEx.Message); } /// <summary> /// Tests that streamer flushes data periodically when <see cref="DataStreamerClientOptions.AutoFlushInterval"/> /// is set to non-zero value. /// </summary> [Test] public void TestAutoFlushInterval() { var cache = GetClientCache<int>(); var options = new DataStreamerClientOptions { AutoFlushInterval = TimeSpan.FromSeconds(0.1) }; using (var streamer = Client.GetDataStreamer<int, int>(cache.Name, options)) { streamer.Add(1, 1); TestUtils.WaitForTrueCondition(() => cache.ContainsKey(1)); streamer.Add(2, 2); TestUtils.WaitForTrueCondition(() => cache.ContainsKey(2)); } } /// <summary> /// Tests that streamer gets closed when automatic flush encounters a fatal error (cache does not exist). /// </summary> [Test] public void TestAutoFlushClosesStreamerWhenCacheDoesNotExist() { var options = new DataStreamerClientOptions { AutoFlushInterval = TimeSpan.FromSeconds(0.2) }; var streamer = Client.GetDataStreamer<int, int>("bad-cache-name", options); streamer.Add(1, 1); Assert.IsFalse(streamer.IsClosed); TestUtils.WaitForTrueCondition(() => streamer.IsClosed); var ex = Assert.Throws<IgniteClientException>(() => streamer.Flush()); Assert.AreEqual("Streamer is closed with error, check inner exception for details.", ex.Message); Assert.IsNotNull(ex.InnerException); var inner = ((AggregateException)ex.InnerException).GetBaseException(); StringAssert.StartsWith("Cache does not exist", inner.Message); } /// <summary> /// Tests that streaming binary objects with a thin client results in those objects being /// available through SQL in the cache's table. /// </summary> [Test] public void TestBinaryStreamerCreatesSqlRecord() { var cacheCfg = new CacheClientConfiguration { Name = "TestBinaryStreamerCreatesSqlRecord", SqlSchema = "persons", QueryEntities = new[] { new QueryEntity { KeyTypeName = "PersonKey", ValueTypeName = "Person", Fields = new List<QueryField> { new QueryField { Name = "Id", FieldType = typeof(int), IsKeyField = true }, new QueryField { Name = "Name", FieldType = typeof(string), }, new QueryField { Name = "Age", FieldType = typeof(int) } } } } }; var cacheClientBinary = Client.GetOrCreateCache<int, IBinaryObject>(cacheCfg) .WithKeepBinary<int, IBinaryObject>(); // Prepare a binary object. var personKey = Client.GetBinary().GetBuilder("PersonKey") .SetIntField("Id", 111) .Build(); var person = Client.GetBinary().GetBuilder("Person") .SetStringField("Name", "Jane") .SetIntField("Age", 43) .Build(); // Stream the binary object to the server. using (var streamer = Client.GetDataStreamer<IBinaryObject, IBinaryObject>(cacheCfg.Name)) { streamer.Add(personKey, person); streamer.Flush(); } // Check that SQL works. var query = new SqlFieldsQuery("SELECT Id, Name, Age FROM \"PERSONS\".PERSON"); var fullResultAfterClientStreamer = cacheClientBinary.Query(query).GetAll(); Assert.IsNotNull(fullResultAfterClientStreamer); Assert.AreEqual(1, fullResultAfterClientStreamer.Count); Assert.AreEqual(111, fullResultAfterClientStreamer[0][0]); Assert.AreEqual("Jane", fullResultAfterClientStreamer[0][1]); Assert.AreEqual(43, fullResultAfterClientStreamer[0][2]); } #if NETCOREAPP /// <summary> /// Tests streaming with async/await. /// </summary> [Test] public async Task TestStreamingAsyncAwait() { var cache = GetClientCache<int>(); using (var streamer = Client.GetDataStreamer<int, int>(cache.Name)) { streamer.Add(1, 1); await streamer.FlushAsync(); Assert.AreEqual(1, await cache.GetAsync(1)); streamer.Add(2, 2); await streamer.FlushAsync(); Assert.AreEqual(2, await cache.GetAsync(2)); streamer.Add(3, 3); await streamer.CloseAsync(false); } Assert.AreEqual(3, await cache.GetSizeAsync()); Assert.AreEqual(3, await cache.GetAsync(3)); } #endif internal static void CheckArrayPoolLeak<TK, TV>(IDataStreamerClient<TK, TV> streamer) { var streamerImpl = (DataStreamerClient<TK, TV>) streamer; TestUtils.WaitForCondition(() => streamerImpl.ArraysAllocated == streamerImpl.ArraysPooled, 1000); Assert.AreEqual(streamerImpl.ArraysAllocated, streamerImpl.ArraysPooled, "Pooled arrays should not leak."); Console.WriteLine("Array pool size: " + streamerImpl.ArraysPooled); } protected override IgniteConfiguration GetIgniteConfiguration() { return new IgniteConfiguration(base.GetIgniteConfiguration()) { Logger = new TestUtils.TestContextLogger() }; } private class StreamReceiverAddOne : IStreamReceiver<int, int> { public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries) { cache.PutAll(entries.ToDictionary(x => x.Key, x => x.Value + 1)); } } private class StreamReceiverThrowException : IStreamReceiver<int, int> { public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries) { throw new ArithmeticException("Foo"); } } private class StreamReceiverReadBinaryThrowException : IStreamReceiver<int, int>, IBinarizable { public void Receive(ICache<int, int> cache, ICollection<ICacheEntry<int, int>> entries) { // No-op. } public void WriteBinary(IBinaryWriter writer) { // No-op. } public void ReadBinary(IBinaryReader reader) { throw new InvalidOperationException("Bar"); } } private class StreamReceiverAddTwoKeepBinary : IStreamReceiver<int, IBinaryObject> { /** <inheritdoc /> */ public void Receive(ICache<int, IBinaryObject> cache, ICollection<ICacheEntry<int, IBinaryObject>> entries) { var binary = cache.Ignite.GetBinary(); cache.PutAll(entries.ToDictionary(x => x.Key, x => binary.ToBinary<IBinaryObject>(new Test { Val = x.Value.Deserialize<Test>().Val + 2 }))); } } private class Test { public int Val { get; set; } } private class BlockingCacheStore : CacheStoreAdapter<int, int>, IFactory<ICacheStore> { private static readonly ManualResetEventSlim Gate = new ManualResetEventSlim(false); public static void Block() { Gate.Reset(); } public static void Unblock() { Gate.Set(); } public override int Load(int key) { throw new IgniteException("Error in Store"); } public override void Write(int key, int val) { Gate.Wait(); } public override void Delete(int key) { throw new IgniteException("Error in Store"); } public ICacheStore CreateInstance() { return new BlockingCacheStore(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace System.Reflection.Metadata.Ecma335 { sealed class MetadataAggregator { // For each heap handle and each delta contains aggregate heap lengths. // heapSizes[heap kind][reader index] == Sum { 0..index | reader[i].XxxHeapLength } private readonly ImmutableArray<ImmutableArray<int>> heapSizes; private readonly ImmutableArray<ImmutableArray<RowCounts>> rowCounts; // internal for testing internal struct RowCounts : IComparable<RowCounts> { public int AggregateInserts; public int Updates; public int CompareTo(RowCounts other) { return AggregateInserts - other.AggregateInserts; } public override string ToString() { return string.Format("+0x{0:x} ~0x{1:x}", AggregateInserts, Updates); } } public MetadataAggregator(MetadataReader baseReader, IReadOnlyList<MetadataReader> deltaReaders) : this(baseReader, null, null, deltaReaders) { } public MetadataAggregator( IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) : this(null, baseTableRowCounts, baseHeapSizes, deltaReaders) { } private MetadataAggregator( MetadataReader baseReader, IReadOnlyList<int> baseTableRowCounts, IReadOnlyList<int> baseHeapSizes, IReadOnlyList<MetadataReader> deltaReaders) { if (baseTableRowCounts == null) { if (baseReader == null) { throw new ArgumentNullException("deltaReaders"); } if (baseReader.GetTableRowCount(TableIndex.EncMap) != 0) { throw new ArgumentException("Base reader must be a full metadata reader.", "baseReader"); } CalculateBaseCounts(baseReader, out baseTableRowCounts, out baseHeapSizes); } else { if (baseTableRowCounts == null) { throw new ArgumentNullException("baseTableRowCounts"); } if (baseTableRowCounts.Count != MetadataTokens.TableCount) { throw new ArgumentException("Must have " + MetadataTokens.TableCount + " elements", "baseTableRowCounts"); } if (baseHeapSizes == null) { throw new ArgumentNullException("baseHeapSizes"); } if (baseHeapSizes.Count != MetadataTokens.HeapCount) { throw new ArgumentException("Must have " + MetadataTokens.HeapCount + " elements", "baseTableRowCounts"); } } if (deltaReaders == null || deltaReaders.Count == 0) { throw new ArgumentException("Must not be empty.", "deltaReaders"); } for (int i = 0; i < deltaReaders.Count; i++) { if (deltaReaders[i].GetTableRowCount(TableIndex.EncMap) == 0 || !deltaReaders[i].IsMinimalDelta) { throw new ArgumentException("All delta readers must be minimal delta metadata readers.", "deltaReaders"); } } this.heapSizes = CalculateHeapSizes(baseHeapSizes, deltaReaders); this.rowCounts = CalculateRowCounts(baseTableRowCounts, deltaReaders); } // for testing only internal MetadataAggregator(RowCounts[][] rowCounts, int[][] heapSizes) { this.rowCounts = ToImmutable(rowCounts); this.heapSizes = ToImmutable(heapSizes); } private static void CalculateBaseCounts( MetadataReader baseReader, out IReadOnlyList<int> baseTableRowCounts, out IReadOnlyList<int> baseHeapSizes) { int[] rowCounts = new int[MetadataTokens.TableCount]; int[] heapSizes = new int[MetadataTokens.HeapCount]; for (int i = 0; i < rowCounts.Length; i++) { rowCounts[i] = baseReader.GetTableRowCount((TableIndex)i); } for (int i = 0; i < heapSizes.Length; i++) { heapSizes[i] = baseReader.GetHeapSize((HeapIndex)i); } baseTableRowCounts = rowCounts; baseHeapSizes = heapSizes; } private static ImmutableArray<ImmutableArray<int>> CalculateHeapSizes( IReadOnlyList<int> baseSizes, IReadOnlyList<MetadataReader> deltaReaders) { // GUID heap index is multiple of sizeof(Guid) == 16 const int guidSize = 16; int generationCount = 1 + deltaReaders.Count; var userStringSizes = new int[generationCount]; var stringSizes = new int[generationCount]; var blobSizes = new int[generationCount]; var guidSizes = new int[generationCount]; userStringSizes[0] = baseSizes[(int)HeapIndex.UserString]; stringSizes[0] = baseSizes[(int)HeapIndex.String]; blobSizes[0] = baseSizes[(int)HeapIndex.Blob]; guidSizes[0] = baseSizes[(int)HeapIndex.Guid] / guidSize; for (int r = 0; r < deltaReaders.Count; r++) { userStringSizes[r + 1] = userStringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.UserString); stringSizes[r + 1] = stringSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.String); blobSizes[r + 1] = blobSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Blob); guidSizes[r + 1] = guidSizes[r] + deltaReaders[r].GetHeapSize(HeapIndex.Guid) / guidSize; } return ImmutableArray.Create( userStringSizes.ToImmutableArray(), stringSizes.ToImmutableArray(), blobSizes.ToImmutableArray(), guidSizes.ToImmutableArray()); } private static ImmutableArray<ImmutableArray<RowCounts>> CalculateRowCounts( IReadOnlyList<int> baseRowCounts, IReadOnlyList<MetadataReader> deltaReaders) { // TODO: optimize - we don't need to allocate all these arrays var rowCounts = GetBaseRowCounts(baseRowCounts, generations: 1 + deltaReaders.Count); for (int generation = 1; generation <= deltaReaders.Count; generation++) { CalculateDeltaRowCountsForGeneration(rowCounts, generation, ref deltaReaders[generation - 1].EncMapTable); } return ToImmutable(rowCounts); } private static ImmutableArray<ImmutableArray<T>> ToImmutable<T>(T[][] array) { var immutable = new ImmutableArray<T>[array.Length]; for (int i = 0; i < array.Length; i++) { immutable[i] = array[i].ToImmutableArray(); } return immutable.ToImmutableArray(); } // internal for testing internal static RowCounts[][] GetBaseRowCounts(IReadOnlyList<int> baseRowCounts, int generations) { var rowCounts = new RowCounts[TableIndexExtensions.Count][]; for (int t = 0; t < rowCounts.Length; t++) { rowCounts[t] = new RowCounts[generations]; rowCounts[t][0].AggregateInserts = baseRowCounts[t]; } return rowCounts; } // internal for testing internal static void CalculateDeltaRowCountsForGeneration(RowCounts[][] rowCounts, int generation, ref EnCMapTableReader encMapTable) { foreach (var tableRowCounts in rowCounts) { tableRowCounts[generation].AggregateInserts = tableRowCounts[generation - 1].AggregateInserts; } int mapRowCount = (int)encMapTable.NumberOfRows; for (uint mapRid = 1; mapRid <= mapRowCount; mapRid++) { uint token = encMapTable.GetToken(mapRid); int rid = (int)(token & TokenTypeIds.RIDMask); var tableRowCounts = rowCounts[token >> TokenTypeIds.RowIdBitCount]; if (rid > tableRowCounts[generation].AggregateInserts) { if (rid != tableRowCounts[generation].AggregateInserts + 1) { throw new BadImageFormatException(MetadataResources.EnCMapNotSorted); } // insert: tableRowCounts[generation].AggregateInserts = rid; } else { // update: tableRowCounts[generation].Updates++; } } } public Handle GetGenerationHandle(Handle handle, out int generation) { if (handle.IsVirtual) { // TODO: if a virtual handle is connected to real handle then translate the rid, // otherwise return vhandle and base. throw new NotSupportedException(); } int rowId = (int)handle.RowId; uint typeId = handle.TokenType; int relativeRowId; if (handle.IsHeapHandle) { HeapIndex heapIndex; MetadataTokens.TryGetHeapIndex(handle.Kind, out heapIndex); var sizes = heapSizes[(int)heapIndex]; generation = sizes.BinarySearch(rowId); if (generation >= 0) { DebugCorlib.Assert(sizes[generation] == rowId); // the index points to the start of the next generation that added data to the heap: do { generation++; } while (generation < sizes.Length && sizes[generation] == rowId); } else { generation = ~generation; } if (generation >= sizes.Length) { throw new ArgumentException("Handle belongs to a future generation", "handle"); } // GUID heap accumulates - previous heap is copied to the next generation relativeRowId = (typeId == TokenTypeIds.Guid || generation == 0) ? rowId : rowId - sizes[generation - 1]; } else { var sizes = rowCounts[(int)handle.value >> TokenTypeIds.RowIdBitCount]; generation = sizes.BinarySearch(new RowCounts { AggregateInserts = rowId }); if (generation >= 0) { DebugCorlib.Assert(sizes[generation].AggregateInserts == rowId); // the row is in a generation that inserted exactly one row -- the one that we are looking for; // or it's in a preceeding generation if the current one didn't insert any rows of the kind: while (generation > 0 && sizes[generation - 1].AggregateInserts == rowId) { generation--; } } else { // the row is in a generation that inserted multiple new rows: generation = ~generation; if (generation >= sizes.Length) { throw new ArgumentException("Handle belongs to a future generation", "handle"); } } // In each delta table updates always precede inserts. relativeRowId = (generation == 0) ? rowId : rowId - sizes[generation - 1].AggregateInserts + sizes[generation].Updates; } return new Handle(typeId | (uint)relativeRowId); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// In this algortihm we show how you can easily use the universe selection feature to fetch symbols /// to be traded using the BaseData custom data system in combination with the AddUniverse{T} method. /// AddUniverse{T} requires a function that will return the symbols to be traded. /// </summary> /// <meta name="tag" content="using data" /> /// <meta name="tag" content="universes" /> /// <meta name="tag" content="custom universes" /> public class DropboxBaseDataUniverseSelectionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { // the changes from the previous universe selection private SecurityChanges _changes = SecurityChanges.None; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { UniverseSettings.Resolution = Resolution.Daily; SetStartDate(2013, 01, 01); SetEndDate(2013, 12, 31); AddUniverse<StockDataSource>("my-stock-data-source", stockDataSource => { return stockDataSource.SelectMany(x => x.Symbols); }); } /// <summary> /// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event /// </summary> /// <code> /// TradeBars bars = slice.Bars; /// Ticks ticks = slice.Ticks; /// TradeBar spy = slice["SPY"]; /// List{Tick} aaplTicks = slice["AAPL"] /// Quandl oil = slice["OIL"] /// dynamic anySymbol = slice[symbol]; /// DataDictionary{Quandl} allQuandlData = slice.Get{Quand} /// Quandl oil = slice.Get{Quandl}("OIL") /// </code> /// <param name="slice">The current slice of data keyed by symbol string</param> public override void OnData(Slice slice) { if (slice.Bars.Count == 0) return; if (_changes == SecurityChanges.None) return; // start fresh Liquidate(); var percentage = 1m / slice.Bars.Count; foreach (var tradeBar in slice.Bars.Values) { SetHoldings(tradeBar.Symbol, percentage); } // reset changes _changes = SecurityChanges.None; } /// <summary> /// Event fired each time the we add/remove securities from the data feed /// </summary> /// <param name="changes"></param> public override void OnSecuritiesChanged(SecurityChanges changes) { // each time our securities change we'll be notified here _changes = changes; } /// <summary> /// Our custom data type that defines where to get and how to read our backtest and live data. /// </summary> class StockDataSource : BaseData { private const string LiveUrl = @"https://www.dropbox.com/s/2az14r5xbx4w5j6/daily-stock-picker-live.csv?dl=1"; private const string BacktestUrl = @"https://www.dropbox.com/s/rmiiktz0ntpff3a/daily-stock-picker-backtest.csv?dl=1"; /// <summary> /// The symbols to be selected /// </summary> public List<string> Symbols { get; set; } /// <summary> /// Required default constructor /// </summary> public StockDataSource() { // initialize our list to empty Symbols = new List<string>(); } /// <summary> /// Return the URL string source of the file. This will be converted to a stream /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source file</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>String URL of source file.</returns> public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { var url = isLiveMode ? LiveUrl : BacktestUrl; return new SubscriptionDataSource(url, SubscriptionTransportMedium.RemoteFile); } /// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { try { // create a new StockDataSource and set the symbol using config.Symbol var stocks = new StockDataSource {Symbol = config.Symbol}; // break our line into csv pieces var csv = line.ToCsv(); if (isLiveMode) { // our live mode format does not have a date in the first column, so use date parameter stocks.Time = date; stocks.Symbols.AddRange(csv); } else { // our backtest mode format has the first column as date, parse it stocks.Time = DateTime.ParseExact(csv[0], "yyyyMMdd", null); // any following comma separated values are symbols, save them off stocks.Symbols.AddRange(csv.Skip(1)); } return stocks; } // return null if we encounter any errors catch { return null; } } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "90"}, {"Average Win", "0.78%"}, {"Average Loss", "-0.39%"}, {"Compounding Annual Return", "18.547%"}, {"Drawdown", "4.700%"}, {"Expectancy", "1.068"}, {"Net Profit", "18.547%"}, {"Sharpe Ratio", "1.993"}, {"Loss Rate", "30%"}, {"Win Rate", "70%"}, {"Profit-Loss Ratio", "1.96"}, {"Alpha", "0.119"}, {"Beta", "2.617"}, {"Annual Standard Deviation", "0.086"}, {"Annual Variance", "0.007"}, {"Information Ratio", "1.764"}, {"Tracking Error", "0.086"}, {"Treynor Ratio", "0.065"}, {"Total Fees", "$251.12"} }; } }
// 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.IO; using System.Text; using System.Text.RegularExpressions; using System.Data; using System.Reflection; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Xml; using System.Net.Mail; using System.Web; using System.Web.Caching; using WebsitePanel.Providers; using WebsitePanel.Providers.Web; using WebsitePanel.Providers.FTP; using WebsitePanel.Providers.Mail; using WebsitePanel.Providers.Database; using WebsitePanel.Providers.OS; using OS = WebsitePanel.Providers.OS; namespace WebsitePanel.EnterpriseServer { public class WebApplicationsInstaller { public const string PROPERTY_CONTENT_PATH = "installer.contentpath"; public const string PROPERTY_ABSOLUTE_CONTENT_PATH = "installer.absolute.contentpath"; public const string PROPERTY_VDIR_CREATED = "installer.virtualdircreated"; public const string PROPERTY_DATABASE_CREATED = "installer.databasecreated"; public const string PROPERTY_USER_CREATED = "installer.usercreated"; public const string PROPERTY_INSTALLED_FILES = "installer.installedfiles"; public const string PROPERTY_DELETE_FILES = "installer.deletefiles"; public const string PROPERTY_DELETE_VDIR = "installer.deletevdir"; public const string PROPERTY_DELETE_SQL = "installer.deletesql"; public const string PROPERTY_DELETE_DATABASE = "installer.deletedatabase"; public const string PROPERTY_DELETE_USER = "installer.deleteuser"; public static int InstallApplication(InstallationInfo inst) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // check package int packageCheck = SecurityContext.CheckPackage(inst.PackageId, DemandPackage.IsActive); if (packageCheck < 0) return packageCheck; // install application WebApplicationsInstaller installer = new WebApplicationsInstaller(); return installer.InstallWebApplication(inst); } ApplicationInfo app = null; private string contentPath = null; private string siteId = null; private OS.OperatingSystem os = null; private DatabaseServer sql = null; private string serverIpAddressExternal = null; private string serverIpAddressInternal = null; private string webSiteName = ""; public int InstallWebApplication(InstallationInfo inst) { // place log record TaskManager.StartTask("APP_INSTALLER", "INSTALL_APPLICATION", inst.PackageId); TaskManager.WriteParameter("Virtual directory", inst.VirtualDir); TaskManager.WriteParameter("Database group", inst.DatabaseGroup); try { // get application info app = GetApplication(inst.PackageId, inst.ApplicationId); BackgroundTask topTask = TaskManager.TopTask; topTask.ItemName = app.Name; TaskController.UpdateTask(topTask); // check web site for existance WebSite webSite = WebServerController.GetWebSite(inst.WebSiteId); if (webSite == null) return BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS; TaskManager.WriteParameter("Web site", webSite.Name); webSiteName = webSite.Name; siteId = webSite.SiteId; // change web site properties if required if (String.IsNullOrEmpty(inst.VirtualDir)) { ChangeVirtualDirectoryProperties(webSite, app.WebSettings); WebServerController.UpdateWebSite(webSite); } // get OS service int osId = PackageController.GetPackageServiceId(inst.PackageId, "os"); os = new OS.OperatingSystem(); ServiceProviderProxy.Init(os, osId); // get remote content path contentPath = webSite.ContentPath; // create virtual dir if required if (!String.IsNullOrEmpty(inst.VirtualDir)) { // check if the required virtual dir already exists contentPath = Path.Combine(contentPath, inst.VirtualDir); WebVirtualDirectory vdir = null; int result = WebServerController.AddVirtualDirectory(inst.WebSiteId, inst.VirtualDir, contentPath); if (result == BusinessErrorCodes.ERROR_VDIR_ALREADY_EXISTS) { // the directory alredy exists vdir = WebServerController.GetVirtualDirectory( inst.WebSiteId, inst.VirtualDir); contentPath = vdir.ContentPath; } else { vdir = WebServerController.GetVirtualDirectory( inst.WebSiteId, inst.VirtualDir); inst[PROPERTY_VDIR_CREATED] = "True"; } // change virtual directory properties if required ChangeVirtualDirectoryProperties(vdir, app.WebSettings); WebServerController.UpdateVirtualDirectory(inst.WebSiteId, vdir); } // deploy application codebase ZIP and then unpack it string codebasePath = app.Codebase; string remoteCodebasePath = Path.Combine(contentPath, Path.GetFileName(app.Codebase)); // make content path absolute string absContentPath = FilesController.GetFullPackagePath(inst.PackageId, contentPath); // save content path inst[PROPERTY_CONTENT_PATH] = contentPath; inst[PROPERTY_ABSOLUTE_CONTENT_PATH] = absContentPath; // copy ZIP to the target server FileStream stream = File.OpenRead(codebasePath); int BUFFER_LENGTH = 5000000; byte[] buffer = new byte[BUFFER_LENGTH]; int readBytes = 0; while (true) { readBytes = stream.Read(buffer, 0, BUFFER_LENGTH); if (readBytes < BUFFER_LENGTH) Array.Resize<byte>(ref buffer, readBytes); FilesController.AppendFileBinaryChunk(inst.PackageId, remoteCodebasePath, buffer); if (readBytes < BUFFER_LENGTH) break; } // unpack codebase inst[PROPERTY_INSTALLED_FILES] = String.Join(";", FilesController.UnzipFiles(inst.PackageId, new string[] { remoteCodebasePath })); // delete codebase zip FilesController.DeleteFiles(inst.PackageId, new string[] { remoteCodebasePath }); // check/create databases if (!String.IsNullOrEmpty(inst.DatabaseGroup) && String.Compare(inst.DatabaseGroup, "None", true) != 0) { // database if (inst.DatabaseId == 0) { TaskManager.WriteParameter("Database name", inst.DatabaseName); // we should create a new database SqlDatabase db = new SqlDatabase(); db.PackageId = inst.PackageId; db.Name = inst.DatabaseName; inst.DatabaseId = DatabaseServerController.AddSqlDatabase(db, inst.DatabaseGroup); if (inst.DatabaseId < 0) { // rollback installation RollbackInstallation(inst); // return error return inst.DatabaseId; // there was an error when creating database } inst[PROPERTY_DATABASE_CREATED] = "True"; } else { // existing database SqlDatabase db = DatabaseServerController.GetSqlDatabase(inst.DatabaseId); inst.DatabaseName = db.Name; TaskManager.WriteParameter("Database name", inst.DatabaseName); } SqlUser user = null; // database user if (inst.UserId == 0) { TaskManager.WriteParameter("Database user", inst.Username); // NEW USER user = new SqlUser(); user.PackageId = inst.PackageId; user.Name = inst.Username; user.Databases = new string[] { inst.DatabaseName }; user.Password = inst.Password; inst.UserId = DatabaseServerController.AddSqlUser(user, inst.DatabaseGroup); if (inst.UserId < 0) { // rollback installation RollbackInstallation(inst); // return error return inst.UserId; // error while adding user } inst[PROPERTY_USER_CREATED] = "True"; } else { // EXISTING USER user = DatabaseServerController.GetSqlUser(inst.UserId); inst.Username = user.Name; TaskManager.WriteParameter("Database user", inst.Username); List<string> databases = new List<string>(); databases.AddRange(user.Databases); if (!databases.Contains(inst.DatabaseName)) { databases.Add(inst.DatabaseName); user.Databases = databases.ToArray(); DatabaseServerController.UpdateSqlUser(user); } } // check connectivity with SQL Server and credentials provided // load user item int sqlServiceId = PackageController.GetPackageServiceId(inst.PackageId, inst.DatabaseGroup); sql = new DatabaseServer(); ServiceProviderProxy.Init(sql, sqlServiceId); if (!sql.CheckConnectivity(inst.DatabaseName, inst.Username, inst.Password)) { // can't connect to the database RollbackInstallation(inst); return BusinessErrorCodes.ERROR_WEB_INSTALLER_CANT_CONNECT_DATABASE; } // read SQL server settings StringDictionary settings = ServerController.GetServiceSettings(sqlServiceId); serverIpAddressExternal = settings["ExternalAddress"]; if (settings.ContainsKey("InternalAddress")) { serverIpAddressInternal = settings["InternalAddress"]; } } // ********* RUN INSTALL SCENARIO *********** int scriptResult = RunInstallScenario(inst); if (scriptResult < 0) { // rollback installation RollbackInstallation(inst); // return error return scriptResult; } // add new installation to the database return 0; } catch (Exception ex) { // rollback installation RollbackInstallation(inst); throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } private void ChangeVirtualDirectoryProperties(WebVirtualDirectory vdir, ApplicationWebSetting[] settings) { if (settings == null) return; // get type properties Type vdirType = vdir.GetType(); foreach (ApplicationWebSetting setting in settings) { PropertyInfo prop = vdirType.GetProperty(setting.Name, BindingFlags.Public | BindingFlags.Instance); if (prop != null) { prop.SetValue(vdir, ObjectUtils.Cast(setting.Value, prop.PropertyType), null); } } } private int RunInstallScenario(InstallationInfo inst) { string scenarioPath = Path.Combine(app.Folder, "Install.xml"); return RunScenario(scenarioPath, inst, true); } private string GetFullPathToInstallFolder(int userId) { string userhomeFolder = String.Empty; string[] osSesstings = os.ServiceProviderSettingsSoapHeaderValue.Settings; foreach (string s in osSesstings) { if (s.Contains("usershome")) { string[] split = s.Split(new char[] {'='}); userhomeFolder = split[1]; } } UserInfo info = UserController.GetUser(userId); return Path.Combine(userhomeFolder, info.Username); } private int RunScenario(string scenarioPath, InstallationInfo inst, bool throwExceptions) { // load XML document XmlDocument docScenario = new XmlDocument(); docScenario.Load(scenarioPath); // go through "check" section XmlNode nodeCheck = docScenario.SelectSingleNode("//check"); if (nodeCheck != null) { foreach (XmlNode nodeStep in nodeCheck.ChildNodes) { if (nodeStep.Name == "fileExists") { /* // check if the specified file exists string fileName = nodeStep.Attributes["path"].Value; fileName = ExpandVariables(fileName, inst); if (fileName.StartsWith("\\")) { fileName = fileName.Substring(1); } //get full path to instal folder PackageInfo package = PackageController.GetPackage(inst.PackageId); string fullPath = Path.Combine(GetFullPathToInstallFolder(package.UserId), fileName); if (os.FileExists(fullPath)) return BusinessErrorCodes.ERROR_WEB_INSTALLER_TARGET_WEBSITE_UNSUITABLE; */ } else if (nodeStep.Name == "sql") { string cmdText = nodeStep.InnerText; cmdText = ExpandVariables(cmdText, inst); DataSet dsResults = sql.ExecuteSqlQuery(inst.DatabaseName, cmdText); if (dsResults.Tables[0].Rows.Count > 0) return BusinessErrorCodes.ERROR_WEB_INSTALLER_TARGET_DATABASE_UNSUITABLE; } } } // go through "commands" section XmlNode nodeCommands = docScenario.SelectSingleNode("//commands"); if (nodeCommands != null) { foreach (XmlNode nodeCommand in nodeCommands.ChildNodes) { if (nodeCommand.Name == "processFile") { // process remote file string fileName = nodeCommand.Attributes["path"].Value; fileName = ExpandVariables(fileName, inst); byte[] fileBinaryContent = FilesController.GetFileBinaryContent(inst.PackageId, fileName); if (fileBinaryContent == null) throw new Exception("Could not process scenario file: " + fileName); string fileContent = Encoding.UTF8.GetString(fileBinaryContent); fileContent = ExpandVariables(fileContent, inst); FilesController.UpdateFileBinaryContent(inst.PackageId, fileName, Encoding.UTF8.GetBytes(fileContent)); } else if (nodeCommand.Name == "runSql") { string cmdText = nodeCommand.InnerText; if (nodeCommand.Attributes["path"] != null) { // load SQL from file string sqlPath = Path.Combine(app.Folder, nodeCommand.Attributes["path"].Value); if (!File.Exists(sqlPath)) continue; StreamReader reader = new StreamReader(sqlPath); cmdText = reader.ReadToEnd(); reader.Close(); } bool run = true; if (nodeCommand.Attributes["dependsOnProperty"] != null) { string[] propNames = nodeCommand.Attributes["dependsOnProperty"].Value.Split(','); foreach (string propName in propNames) { if (inst[propName.Trim()] == null) { run = false; break; } } } if (run) { try { cmdText = ExpandVariables(cmdText, inst); sql.ExecuteSqlNonQuerySafe(inst.DatabaseName, inst.Username, inst.Password, cmdText); } catch (Exception ex) { if (throwExceptions) throw ex; } } } } } return 0; } string appUrls = null; private string ExpandVariables(string str, InstallationInfo inst) { str = ReplaceTemplateVariable(str, "installer.contentpath", inst[PROPERTY_CONTENT_PATH]); str = ReplaceTemplateVariable(str, "installer.website", webSiteName); str = ReplaceTemplateVariable(str, "installer.virtualdir", inst.VirtualDir); string fullWebPath = webSiteName; if (!String.IsNullOrEmpty(inst.VirtualDir)) fullWebPath += "/" + inst.VirtualDir; // try to load domain info DomainInfo domain = ServerController.GetDomain(webSiteName); string fullWebPathPrefix = (domain != null && domain.IsSubDomain) ? "" : "www."; // app URLs if (appUrls == null) { // read web pointers List<DomainInfo> sitePointers = WebServerController.GetWebSitePointers(inst.WebSiteId); StringBuilder sb = new StringBuilder(); sb.Append("<urls>"); sb.Append("<url value=\"").Append(fullWebPath).Append("\"/>"); foreach (DomainInfo pointer in sitePointers) { string pointerWebPath = pointer.DomainName; if (!String.IsNullOrEmpty(inst.VirtualDir)) pointerWebPath += "/" + inst.VirtualDir; sb.Append("<url value=\"").Append(pointerWebPath).Append("\"/>"); } sb.Append("</urls>"); appUrls = sb.ToString(); } str = ReplaceTemplateVariable(str, "installer.appurls", appUrls); string slashVirtualDir = ""; if (!String.IsNullOrEmpty(inst.VirtualDir)) slashVirtualDir = "/" + inst.VirtualDir; str = ReplaceTemplateVariable(str, "installer.slashvirtualdir", slashVirtualDir); str = ReplaceTemplateVariable(str, "installer.website.www", fullWebPathPrefix + webSiteName); str = ReplaceTemplateVariable(str, "installer.fullwebpath", fullWebPath); str = ReplaceTemplateVariable(str, "installer.fullwebpath.www", fullWebPathPrefix + fullWebPath); //Replace ObjectQualifierNormalized which is not defined on portal str = ReplaceTemplateVariable(str, "ObjectQualifierNormalized", ""); /* * Application installer variable 'installer.database.server' is obsolete * and should not be used to install Application Packs. * Instead, please use the following two variables: * - installer.database.server.external - defines external database address * - installer.database.server.internal - defines internal database address * * See TFS Issue 952 for details. */ //apply external database address str = ReplaceTemplateVariable(str, "installer.database.server", ((serverIpAddressExternal != null) ? serverIpAddressExternal : "")); str = ReplaceTemplateVariable(str, "installer.database.server.external", ((serverIpAddressExternal != null) ? serverIpAddressExternal : String.Empty)); //apply internal database address str = ReplaceTemplateVariable(str, "installer.database.server.internal", ((serverIpAddressInternal != null) ? serverIpAddressInternal : String.Empty)); str = ReplaceTemplateVariable(str, "installer.database", inst.DatabaseName); str = ReplaceTemplateVariable(str, "installer.database.user", inst.Username); str = ReplaceTemplateVariable(str, "installer.database.password", ((inst.Password != null) ? inst.Password : "")); foreach (string[] pair in inst.PropertiesArray) str = ReplaceTemplateVariable(str, pair[0], pair[1]); return str; } private string ReplaceTemplateVariable(string str, string varName, string varValue) { if (String.IsNullOrEmpty(str) || String.IsNullOrEmpty(varName)) return str; str = Regex.Replace(str, "\\$\\{" + varName + "\\}+", varValue, RegexOptions.IgnoreCase); str = Regex.Replace(str, "\\$\\{" + varName + ".mysql-escaped\\}+", EscapeMySql(varValue), RegexOptions.IgnoreCase); return Regex.Replace(str, "\\$\\{" + varName + ".mssql-escaped\\}+", EscapeMsSql(varValue), RegexOptions.IgnoreCase); } private string EscapeMySql(string str) { if (String.IsNullOrEmpty(str)) return str; return str.Replace("'", "\\'") .Replace("\"", "\\\"") .Replace("\n", "\\n") .Replace("\r", "\\r") .Replace("\t", "\\t") .Replace("\\", "\\\\") .Replace("\0", "\\0"); } private string EscapeMsSql(string str) { if (String.IsNullOrEmpty(str)) return str; return str.Replace("'", "''"); } private void RollbackInstallation(InstallationInfo inst) { // remove virtual dir if (inst[PROPERTY_VDIR_CREATED] != null) { // delete virtual directory WebServerController.DeleteVirtualDirectory(inst.WebSiteId, inst.VirtualDir); // delete folder FilesController.DeleteFiles(inst.PackageId, new string[] { inst[PROPERTY_CONTENT_PATH] }); } // remove database if (inst[PROPERTY_DATABASE_CREATED] != null) DatabaseServerController.DeleteSqlDatabase(inst.DatabaseId); // remove database user if (inst[PROPERTY_USER_CREATED] != null) DatabaseServerController.DeleteSqlUser(inst.UserId); } public static List<ApplicationCategory> GetCategories() { List<ApplicationCategory> categories = null; string key = "WebApplicationCategories"; // look up in the cache if (HttpContext.Current != null) categories = (List<ApplicationCategory>)HttpContext.Current.Cache[key]; if (categories == null) { string catsPath = Path.Combine(ConfigSettings.WebApplicationsPath, "Applications.xml"); if (File.Exists(catsPath)) { categories = new List<ApplicationCategory>(); // parse file XmlDocument doc = new XmlDocument(); doc.Load(catsPath); XmlNodeList nodesCategories = doc.SelectNodes("categories/category"); foreach (XmlNode nodeCategory in nodesCategories) { ApplicationCategory category = new ApplicationCategory(); category.Id = nodeCategory.Attributes["id"].Value; category.Name = GetNodeValue(nodeCategory, "name", category.Id); categories.Add(category); // read applications List<string> catApps = new List<string>(); XmlNodeList nodesApps = nodeCategory.SelectNodes("applications/application"); foreach (XmlNode nodeApp in nodesApps) catApps.Add(nodeApp.Attributes["name"].Value); category.Applications = catApps.ToArray(); } } // place to the cache if (HttpContext.Current != null) HttpContext.Current.Cache.Insert(key, categories, new CacheDependency(catsPath)); } return categories; } public static List<ApplicationInfo> GetApplications(int packageId) { return GetApplications(packageId, null); } public static List<ApplicationInfo> GetApplications(int packageId, string categoryId) { string key = "WebApplicationsList"; Dictionary<string, ApplicationInfo> apps = null; // look up in the cache if(HttpContext.Current != null) apps = (Dictionary<string, ApplicationInfo>)HttpContext.Current.Cache[key]; if (apps == null) { // create apps list apps = new Dictionary<string, ApplicationInfo>(); string appsRoot = ConfigSettings.WebApplicationsPath; string[] dirs = Directory.GetDirectories(appsRoot); foreach (string dir in dirs) { string appFile = Path.Combine(dir, "Application.xml"); if (!File.Exists(appFile)) continue; // read and parse web applications xml file XmlDocument doc = new XmlDocument(); doc.Load(appFile); XmlNode nodeApp = doc.SelectSingleNode("//application"); string appFolder = dir; // parse node ApplicationInfo app = CreateApplicationInfoFromXml(appFolder, nodeApp); // add to the collection apps.Add(app.Id, app); } // place to the cache if (HttpContext.Current != null) HttpContext.Current.Cache.Insert(key, apps, new CacheDependency(appsRoot)); } // filter applications based on category List<ApplicationInfo> categoryApps = new List<ApplicationInfo>(); // check if the application fits requirements PackageContext cntx = PackageController.GetPackageContext(packageId); List<ApplicationCategory> categories = GetCategories(); foreach (ApplicationCategory category in categories) { // skip category if required if (!String.IsNullOrEmpty(categoryId) && String.Compare(category.Id, categoryId, true) != 0) continue; // iterate through applications foreach (string appId in category.Applications) { if (apps.ContainsKey(appId) && IsApplicattionFitsRequirements(cntx, apps[appId])) categoryApps.Add(apps[appId]); } } return categoryApps; } public static ApplicationInfo GetApplication(int packageId, string applicationId) { // get all applications List<ApplicationInfo> apps = GetApplications(packageId); // check if the application fits requirements PackageContext cntx = PackageController.GetPackageContext(packageId); // find the application foreach (ApplicationInfo app in apps) { if (app.Id.ToLower() == applicationId.ToLower()) { return IsApplicattionFitsRequirements(cntx, app) ? app : null; } } return null; } public static bool IsApplicattionFitsRequirements(PackageContext cntx, ApplicationInfo app) { if (app.Requirements == null) return true; // empty requirements foreach (ApplicationRequirement req in app.Requirements) { // check if this is a group if (req.Groups != null) { bool groupFits = false; foreach (string group in req.Groups) { if (cntx.Groups.ContainsKey(group)) { groupFits = true; break; } } if (!groupFits) return false; } // check if this is a quota if (req.Quotas != null) { bool quotaFits = false; foreach (string quota in req.Quotas) { if (cntx.Quotas.ContainsKey(quota) && !cntx.Quotas[quota].QuotaExhausted) { quotaFits = true; break; } } if (!quotaFits) return false; } } return true; } #region private helper methods private static ApplicationInfo CreateApplicationInfoFromXml(string appFolder, XmlNode nodeApp) { ApplicationInfo app = new ApplicationInfo(); // category name app.CategoryName = GetNodeValue(nodeApp, "category", ""); // attributes app.Id = nodeApp.Attributes["id"].Value; app.Codebase = nodeApp.Attributes["codebase"].Value; app.SettingsControl = nodeApp.Attributes["settingsControl"].Value; app.Folder = appFolder; // child nodes app.Name = GetNodeValue(nodeApp, "name", ""); app.ShortDescription = GetNodeValue(nodeApp, "shortDescription", ""); app.FullDescription = GetNodeValue(nodeApp, "fullDescription", ""); app.Logo = GetNodeValue(nodeApp, "logo", ""); app.Version = GetNodeValue(nodeApp, "version", ""); app.Size = Int32.Parse(GetNodeValue(nodeApp, "size", "0")); app.HomeSite = GetNodeValue(nodeApp, "homeSite", ""); app.SupportSite = GetNodeValue(nodeApp, "supportSite", ""); app.DocsSite = GetNodeValue(nodeApp, "docSite", ""); app.Manufacturer = GetNodeValue(nodeApp, "manufacturer", ""); app.License = GetNodeValue(nodeApp, "license", ""); // process codebase path app.Codebase = Path.Combine(appFolder, app.Codebase); // web settings List<ApplicationWebSetting> settings = new List<ApplicationWebSetting>(); XmlNodeList nodesWebSettings = nodeApp.SelectNodes("webSettings/add"); foreach (XmlNode nodeSetting in nodesWebSettings) { ApplicationWebSetting setting = new ApplicationWebSetting(); setting.Name = nodeSetting.Attributes["name"].Value; setting.Value = nodeSetting.Attributes["value"].Value; settings.Add(setting); } app.WebSettings = settings.ToArray(); // requirements List<ApplicationRequirement> requirements = new List<ApplicationRequirement>(); XmlNodeList nodesRequirements = nodeApp.SelectNodes("requirements/add"); foreach (XmlNode nodesRequirement in nodesRequirements) { ApplicationRequirement req = new ApplicationRequirement(); if (nodesRequirement.Attributes["group"] != null) req.Groups = nodesRequirement.Attributes["group"].Value.Split('|'); if (nodesRequirement.Attributes["quota"] != null) req.Quotas = nodesRequirement.Attributes["quota"].Value.Split('|'); req.Display = true; if (nodesRequirement.Attributes["display"] != null) req.Display = Utils.ParseBool(nodesRequirement.Attributes["display"].Value, true); requirements.Add(req); } app.Requirements = requirements.ToArray(); return app; } private static string GetNodeValue(XmlNode parentNode, string nodeName, string defaultValue) { XmlNode node = parentNode.SelectSingleNode(nodeName); if (node != null) { return node.InnerText.Trim(); } // return default value return defaultValue; } #endregion } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEngine.EventSystems; /// Draws a circular reticle in front of any object that the user points at. /// The circle dilates if the object is clickable. public class GvrReticlePointer : GvrBasePointer { // The constants below are expsed for testing. // Minimum inner angle of the reticle (in degrees). public const float RETICLE_MIN_INNER_ANGLE = 0.0f; // Minimum outer angle of the reticle (in degrees). public const float RETICLE_MIN_OUTER_ANGLE = 0.5f; // Angle at which to expand the reticle when intersecting with an object // (in degrees). public const float RETICLE_GROWTH_ANGLE = 1.5f; // Minimum distance of the reticle (in meters). public const float RETICLE_DISTANCE_MIN = 0.45f; // Maximum distance of the reticle (in meters). public const float RETICLE_DISTANCE_MAX = 10.0f; /// Number of segments making the reticle circle. public int reticleSegments = 20; /// Growth speed multiplier for the reticle/ public float reticleGrowthSpeed = 8.0f; /// Sorting order to use for the reticle's renderer. /// Range values come from https://docs.unity3d.com/ScriptReference/Renderer-sortingOrder.html. /// Default value 32767 ensures gaze reticle is always rendered on top. [Range(-32767, 32767)] public int reticleSortingOrder = 32767; public Material MaterialComp { private get; set; } // Current inner angle of the reticle (in degrees). // Exposed for testing. public float ReticleInnerAngle { get; private set; } // Current outer angle of the reticle (in degrees). // Exposed for testing. public float ReticleOuterAngle { get; private set; } // Current distance of the reticle (in meters). // Getter exposed for testing. public float ReticleDistanceInMeters { get; private set; } // Current inner and outer diameters of the reticle, before distance multiplication. // Getters exposed for testing. public float ReticleInnerDiameter { get; private set; } public float ReticleOuterDiameter { get; private set; } public override float MaxPointerDistance { get { return RETICLE_DISTANCE_MAX; } } public override void OnPointerEnter(RaycastResult raycastResultResult, bool isInteractive) { SetPointerTarget(raycastResultResult.worldPosition, isInteractive); } public override void OnPointerHover(RaycastResult raycastResultResult, bool isInteractive) { SetPointerTarget(raycastResultResult.worldPosition, isInteractive); } public override void OnPointerExit(GameObject previousObject) { ReticleDistanceInMeters = RETICLE_DISTANCE_MAX; ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } public override void OnPointerClickDown() {} public override void OnPointerClickUp() {} public override void GetPointerRadius(out float enterRadius, out float exitRadius) { float min_inner_angle_radians = Mathf.Deg2Rad * RETICLE_MIN_INNER_ANGLE; float max_inner_angle_radians = Mathf.Deg2Rad * (RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE); enterRadius = 2.0f * Mathf.Tan(min_inner_angle_radians); exitRadius = 2.0f * Mathf.Tan(max_inner_angle_radians); } public void UpdateDiameters() { ReticleDistanceInMeters = Mathf.Clamp(ReticleDistanceInMeters, RETICLE_DISTANCE_MIN, RETICLE_DISTANCE_MAX); if (ReticleInnerAngle < RETICLE_MIN_INNER_ANGLE) { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; } if (ReticleOuterAngle < RETICLE_MIN_OUTER_ANGLE) { ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } float inner_half_angle_radians = Mathf.Deg2Rad * ReticleInnerAngle * 0.5f; float outer_half_angle_radians = Mathf.Deg2Rad * ReticleOuterAngle * 0.5f; float inner_diameter = 2.0f * Mathf.Tan(inner_half_angle_radians); float outer_diameter = 2.0f * Mathf.Tan(outer_half_angle_radians); ReticleInnerDiameter = Mathf.Lerp(ReticleInnerDiameter, inner_diameter, Time.deltaTime * reticleGrowthSpeed); ReticleOuterDiameter = Mathf.Lerp(ReticleOuterDiameter, outer_diameter, Time.deltaTime * reticleGrowthSpeed); MaterialComp.SetFloat("_InnerDiameter", ReticleInnerDiameter * ReticleDistanceInMeters); MaterialComp.SetFloat("_OuterDiameter", ReticleOuterDiameter * ReticleDistanceInMeters); MaterialComp.SetFloat("_DistanceInMeters", ReticleDistanceInMeters); } void Awake() { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } protected override void Start() { base.Start(); Renderer rendererComponent = GetComponent<Renderer>(); rendererComponent.sortingOrder = reticleSortingOrder; MaterialComp = rendererComponent.material; CreateReticleVertices(); } void Update() { UpdateDiameters(); } private bool SetPointerTarget(Vector3 target, bool interactive) { if (base.PointerTransform == null) { Debug.LogWarning("Cannot operate on a null pointer transform"); return false; } Vector3 targetLocalPosition = base.PointerTransform.InverseTransformPoint(target); ReticleDistanceInMeters = Mathf.Clamp(targetLocalPosition.z, RETICLE_DISTANCE_MIN, RETICLE_DISTANCE_MAX); if (interactive) { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE + RETICLE_GROWTH_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE + RETICLE_GROWTH_ANGLE; } else { ReticleInnerAngle = RETICLE_MIN_INNER_ANGLE; ReticleOuterAngle = RETICLE_MIN_OUTER_ANGLE; } return true; } private void CreateReticleVertices() { Mesh mesh = new Mesh(); gameObject.AddComponent<MeshFilter>(); GetComponent<MeshFilter>().mesh = mesh; int segments_count = reticleSegments; int vertex_count = (segments_count+1)*2; #region Vertices Vector3[] vertices = new Vector3[vertex_count]; const float kTwoPi = Mathf.PI * 2.0f; int vi = 0; for (int si = 0; si <= segments_count; ++si) { // Add two vertices for every circle segment: one at the beginning of the // prism, and one at the end of the prism. float angle = (float)si / (float)(segments_count) * kTwoPi; float x = Mathf.Sin(angle); float y = Mathf.Cos(angle); vertices[vi++] = new Vector3(x, y, 0.0f); // Outer vertex. vertices[vi++] = new Vector3(x, y, 1.0f); // Inner vertex. } #endregion #region Triangles int indices_count = (segments_count+1)*3*2; int[] indices = new int[indices_count]; int vert = 0; int idx = 0; for (int si = 0; si < segments_count; ++si) { indices[idx++] = vert+1; indices[idx++] = vert; indices[idx++] = vert+2; indices[idx++] = vert+1; indices[idx++] = vert+2; indices[idx++] = vert+3; vert += 2; } #endregion mesh.vertices = vertices; mesh.triangles = indices; mesh.RecalculateBounds(); #if !UNITY_5_5_OR_NEWER // Optimize() is deprecated as of Unity 5.5.0p1. mesh.Optimize(); #endif // !UNITY_5_5_OR_NEWER } }
// Template: Client Proxy T4 Template (RAMLClient.t4) version 4.0 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Xml.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using RAML.Api.Core; using Raml.Common; namespace RAMLDemo.Api.Tests.Api { public partial class StatusParcelId { private readonly ParcelDeliveryApiClient proxy; internal StatusParcelId(ParcelDeliveryApiClient proxy) { this.proxy = proxy; } /// <summary> /// Retrieves the current status for the specified parcel ID. - Parcel Status Information /// </summary> /// <param name="parcelId"></param> public virtual async Task<Models.StatusParcelIdGetResponse> Get(string parcelId) { var url = "status/{parcelId}"; url = url.Replace("{parcelId}", parcelId.ToString()); var req = new HttpRequestMessage(HttpMethod.Get, url); var response = await proxy.Client.SendAsync(req); if (proxy.SchemaValidation.Enabled) { if(proxy.SchemaValidation.RaiseExceptions) { await SchemaValidator.ValidateWithExceptionAsync(Models.StatusParcelIdGetResponse.GetSchema(response.StatusCode), response.Content); } } return new Models.StatusParcelIdGetResponse { RawContent = response.Content, RawHeaders = response.Headers, StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, SchemaValidation = new Lazy<SchemaValidationResults>(() => SchemaValidator.IsValid(Models.StatusParcelIdGetResponse.GetSchema(response.StatusCode), response.Content), true) }; } /// <summary> /// Retrieves the current status for the specified parcel ID. - Parcel Status Information /// </summary> /// <param name="request">Models.StatusParcelIdGetRequest</param> /// <param name="responseFormatters">response formmaters</param> public virtual async Task<Models.StatusParcelIdGetResponse> Get(Models.StatusParcelIdGetRequest request, IEnumerable<MediaTypeFormatter> responseFormatters = null) { var url = "status/{parcelId}"; if(request.UriParameters == null) throw new InvalidOperationException("Uri Parameters cannot be null"); if(request.UriParameters.ParcelId == null) throw new InvalidOperationException("Uri Parameter ParcelId cannot be null"); url = url.Replace("{parcelId}", request.UriParameters.ParcelId.ToString()); var req = new HttpRequestMessage(HttpMethod.Get, url); if(request.RawHeaders != null) { foreach(var header in request.RawHeaders) { req.Headers.TryAddWithoutValidation(header.Key, string.Join(",", header.Value)); } } var response = await proxy.Client.SendAsync(req); if (proxy.SchemaValidation.Enabled && proxy.SchemaValidation.RaiseExceptions) { if(proxy.SchemaValidation.RaiseExceptions) { await SchemaValidator.ValidateWithExceptionAsync(Models.StatusParcelIdGetResponse.GetSchema(response.StatusCode), response.Content); } } return new Models.StatusParcelIdGetResponse { RawContent = response.Content, RawHeaders = response.Headers, Formatters = responseFormatters, StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, SchemaValidation = new Lazy<SchemaValidationResults>(() => SchemaValidator.IsValid(Models.StatusParcelIdGetResponse.GetSchema(response.StatusCode), response.Content), true) }; } /// <summary> /// Creates or updates the status for the specified parcel ID. - Parcel Status Information /// </summary> /// <param name="statusparcelidputrequestcontent"></param> /// <param name="parcelId"></param> public virtual async Task<Models.StatusParcelIdPutResponse> Put(Models.StatusParcelIdPutRequestContent statusparcelidputrequestcontent, string parcelId) { var url = "status/{parcelId}"; url = url.Replace("{parcelId}", parcelId.ToString()); var req = new HttpRequestMessage(HttpMethod.Put, url); req.Content = new ObjectContent(typeof(Models.StatusParcelIdPutRequestContent), statusparcelidputrequestcontent, new JsonMediaTypeFormatter()); var response = await proxy.Client.SendAsync(req); if (proxy.SchemaValidation.Enabled) { if(proxy.SchemaValidation.RaiseExceptions) { await SchemaValidator.ValidateWithExceptionAsync(Models.StatusParcelIdPutResponse.GetSchema(response.StatusCode), response.Content); } } return new Models.StatusParcelIdPutResponse { RawContent = response.Content, RawHeaders = response.Headers, StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, SchemaValidation = new Lazy<SchemaValidationResults>(() => SchemaValidator.IsValid(Models.StatusParcelIdPutResponse.GetSchema(response.StatusCode), response.Content), true) }; } /// <summary> /// Creates or updates the status for the specified parcel ID. - Parcel Status Information /// </summary> /// <param name="request">Models.StatusParcelIdPutRequest</param> /// <param name="responseFormatters">response formmaters</param> public virtual async Task<Models.StatusParcelIdPutResponse> Put(Models.StatusParcelIdPutRequest request, IEnumerable<MediaTypeFormatter> responseFormatters = null) { var url = "status/{parcelId}"; if(request.UriParameters == null) throw new InvalidOperationException("Uri Parameters cannot be null"); if(request.UriParameters.ParcelId == null) throw new InvalidOperationException("Uri Parameter ParcelId cannot be null"); url = url.Replace("{parcelId}", request.UriParameters.ParcelId.ToString()); var req = new HttpRequestMessage(HttpMethod.Put, url); if(request.RawHeaders != null) { foreach(var header in request.RawHeaders) { req.Headers.TryAddWithoutValidation(header.Key, string.Join(",", header.Value)); } } if(request.Formatter == null) request.Formatter = new JsonMediaTypeFormatter(); var response = await proxy.Client.SendAsync(req); if (proxy.SchemaValidation.Enabled && proxy.SchemaValidation.RaiseExceptions) { if(proxy.SchemaValidation.RaiseExceptions) { await SchemaValidator.ValidateWithExceptionAsync(Models.StatusParcelIdPutResponse.GetSchema(response.StatusCode), response.Content); } } return new Models.StatusParcelIdPutResponse { RawContent = response.Content, RawHeaders = response.Headers, Formatters = responseFormatters, StatusCode = response.StatusCode, ReasonPhrase = response.ReasonPhrase, SchemaValidation = new Lazy<SchemaValidationResults>(() => SchemaValidator.IsValid(Models.StatusParcelIdPutResponse.GetSchema(response.StatusCode), response.Content), true) }; } } /// <summary> /// Main class for grouping root resources. Nested resources are defined as properties. The constructor can optionally receive an URL and HttpClient instance to override the default ones. /// </summary> public partial class ParcelDeliveryApiClient { public SchemaValidationSettings SchemaValidation { get; private set; } protected readonly HttpClient client; public const string BaseUri = "https://raml-demo-api.azurewebsites.net/{version}/"; internal HttpClient Client { get { return client; } } public ParcelDeliveryApiClient(string endpointUrl) { SchemaValidation = new SchemaValidationSettings { Enabled = true, RaiseExceptions = true }; if(string.IsNullOrWhiteSpace(endpointUrl)) throw new ArgumentException("You must specify the endpoint URL", "endpointUrl"); if (endpointUrl.Contains("{")) { var regex = new Regex(@"\{([^\}]+)\}"); var matches = regex.Matches(endpointUrl); var parameters = new List<string>(); foreach (Match match in matches) { parameters.Add(match.Groups[1].Value); } throw new InvalidOperationException("Please replace parameter/s " + string.Join(", ", parameters) + " in the URL before passing it to the constructor "); } client = new HttpClient {BaseAddress = new Uri(endpointUrl)}; } public ParcelDeliveryApiClient(HttpClient httpClient) { if(httpClient.BaseAddress == null) throw new InvalidOperationException("You must set the BaseAddress property of the HttpClient instance"); client = httpClient; SchemaValidation = new SchemaValidationSettings { Enabled = true, RaiseExceptions = true }; } public virtual StatusParcelId StatusParcelId { get { return new StatusParcelId(this); } } public void AddDefaultRequestHeader(string name, string value) { client.DefaultRequestHeaders.Add(name, value); } public void AddDefaultRequestHeader(string name, IEnumerable<string> values) { client.DefaultRequestHeaders.Add(name, values); } } } // end namespace namespace RAMLDemo.Api.Tests.Api.Models { public partial class ErrorMessage { /// <summary> /// The error message of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } } // end class public partial class StatusParcelIdPutRequestContent { /// <summary> /// The new status update message. /// </summary> [JsonProperty("status")] public string Status { get; set; } } // end class public partial class StatusParcelIdGetOKResponseContent { /// <summary> /// The current status of the delivery. /// </summary> [JsonProperty("status")] public string Status { get; set; } /// <summary> /// The date time the last status update. /// </summary> [JsonProperty("updated")] public string Updated { get; set; } } // end class public partial class StatusParcelIdGetNotFoundResponseContent { /// <summary> /// The error message of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } } // end class public partial class StatusParcelIdGetNotAcceptableResponseContent { /// <summary> /// The error message of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } } // end class public partial class StatusParcelIdPutNotFoundResponseContent { /// <summary> /// The error message of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } } // end class public partial class StatusParcelIdPutNotAcceptableResponseContent { /// <summary> /// The error message of the error. /// </summary> [JsonProperty("message")] public string Message { get; set; } } // end class /// <summary> /// Multiple Response Types StatusParcelIdGetOKResponseContent, StatusParcelIdGetNotFoundResponseContent, StatusParcelIdGetNotAcceptableResponseContent /// </summary> public partial class MultipleStatusParcelIdGet : ApiMultipleResponse { static readonly Dictionary<HttpStatusCode, string> schemas = new Dictionary<HttpStatusCode, string> { { (HttpStatusCode)200, "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"Delivery Status\", \"type\": \"object\", \"properties\": { \"status\": { \"description\": \"The current status of the delivery.\", \"type\": \"string\" }, \"updated\": { \"description\": \"The date time the last status update.\", \"type\": \"string\" } }}"}, { (HttpStatusCode)404, "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"Error Message\", \"type\": \"object\", \"properties\": { \"message\": { \"description\": \"The error message of the error.\", \"type\": \"string\" } }}"}, { (HttpStatusCode)406, "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"Error Message\", \"type\": \"object\", \"properties\": { \"message\": { \"description\": \"The error message of the error.\", \"type\": \"string\" } }}"}, }; public static string GetSchema(HttpStatusCode statusCode) { return schemas.ContainsKey(statusCode) ? schemas[statusCode] : string.Empty; } public MultipleStatusParcelIdGet() { names.Add((HttpStatusCode)200, "StatusParcelIdGetOKResponseContent"); types.Add((HttpStatusCode)200, typeof(StatusParcelIdGetOKResponseContent)); names.Add((HttpStatusCode)404, "StatusParcelIdGetNotFoundResponseContent"); types.Add((HttpStatusCode)404, typeof(StatusParcelIdGetNotFoundResponseContent)); names.Add((HttpStatusCode)406, "StatusParcelIdGetNotAcceptableResponseContent"); types.Add((HttpStatusCode)406, typeof(StatusParcelIdGetNotAcceptableResponseContent)); } /// <summary> /// Current status. /// </summary> public StatusParcelIdGetOKResponseContent StatusParcelIdGetOKResponseContent { get; set; } /// <summary> /// Could not find the specified parcel ID. /// </summary> public StatusParcelIdGetNotFoundResponseContent StatusParcelIdGetNotFoundResponseContent { get; set; } /// <summary> /// Parcel ID was in an incorrect format. /// </summary> public StatusParcelIdGetNotAcceptableResponseContent StatusParcelIdGetNotAcceptableResponseContent { get; set; } } // end class /// <summary> /// Multiple Response Types StatusParcelIdPutNotFoundResponseContent, StatusParcelIdPutNotAcceptableResponseContent /// </summary> public partial class MultipleStatusParcelIdPut : ApiMultipleResponse { static readonly Dictionary<HttpStatusCode, string> schemas = new Dictionary<HttpStatusCode, string> { { (HttpStatusCode)404, "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"Error Message\", \"type\": \"object\", \"properties\": { \"message\": { \"description\": \"The error message of the error.\", \"type\": \"string\" } }}"}, { (HttpStatusCode)406, "{ \"$schema\": \"http://json-schema.org/draft-04/schema#\", \"title\": \"Error Message\", \"type\": \"object\", \"properties\": { \"message\": { \"description\": \"The error message of the error.\", \"type\": \"string\" } }}"}, }; public static string GetSchema(HttpStatusCode statusCode) { return schemas.ContainsKey(statusCode) ? schemas[statusCode] : string.Empty; } public MultipleStatusParcelIdPut() { names.Add((HttpStatusCode)404, "StatusParcelIdPutNotFoundResponseContent"); types.Add((HttpStatusCode)404, typeof(StatusParcelIdPutNotFoundResponseContent)); names.Add((HttpStatusCode)406, "StatusParcelIdPutNotAcceptableResponseContent"); types.Add((HttpStatusCode)406, typeof(StatusParcelIdPutNotAcceptableResponseContent)); } /// <summary> /// Could not find the specified parcel ID. /// </summary> public StatusParcelIdPutNotFoundResponseContent StatusParcelIdPutNotFoundResponseContent { get; set; } /// <summary> /// Parcel ID was in an incorrect format. /// </summary> public StatusParcelIdPutNotAcceptableResponseContent StatusParcelIdPutNotAcceptableResponseContent { get; set; } } // end class /// <summary> /// Uri Parameters for resource /status/{parcelId} /// </summary> public partial class StatusParcelIdUriParameters { [JsonProperty("parcelId")] public string ParcelId { get; set; } } // end class /// <summary> /// Request object for method Get of class StatusParcelId /// </summary> public partial class StatusParcelIdGetRequest : ApiRequest { public StatusParcelIdGetRequest(StatusParcelIdUriParameters UriParameters) { this.UriParameters = UriParameters; } /// <summary> /// Request Uri Parameters /// </summary> public StatusParcelIdUriParameters UriParameters { get; set; } } // end class /// <summary> /// Request object for method Put of class StatusParcelId /// </summary> public partial class StatusParcelIdPutRequest : ApiRequest { public StatusParcelIdPutRequest(StatusParcelIdUriParameters UriParameters, StatusParcelIdPutRequestContent Content = null, MediaTypeFormatter Formatter = null) { this.Content = Content; this.Formatter = Formatter; this.UriParameters = UriParameters; } /// <summary> /// Request content /// </summary> public StatusParcelIdPutRequestContent Content { get; set; } /// <summary> /// Request formatter /// </summary> public MediaTypeFormatter Formatter { get; set; } /// <summary> /// Request Uri Parameters /// </summary> public StatusParcelIdUriParameters UriParameters { get; set; } } // end class /// <summary> /// Response object for method Get of class StatusParcelId /// </summary> public partial class StatusParcelIdGetResponse : ApiResponse { private MultipleStatusParcelIdGet typedContent; /// <summary> /// Typed response content /// </summary> public MultipleStatusParcelIdGet Content { get { if (typedContent != null) return typedContent; typedContent = new MultipleStatusParcelIdGet(); IEnumerable<string> values = new List<string>(); if (RawContent != null && RawContent.Headers != null) RawContent.Headers.TryGetValues("Content-Type", out values); if (values.Any(hv => hv.ToLowerInvariant().Contains("xml")) && !values.Any(hv => hv.ToLowerInvariant().Contains("json"))) { var task = RawContent.ReadAsStreamAsync(); var xmlStream = task.GetAwaiter().GetResult(); var content = new XmlSerializer(typedContent.GetTypeByStatusCode(StatusCode)).Deserialize(xmlStream); typedContent.SetPropertyByStatusCode(StatusCode, content); } else { var task = Formatters != null && Formatters.Any() ? RawContent.ReadAsAsync(typedContent.GetTypeByStatusCode(StatusCode), Formatters).ConfigureAwait(false) : RawContent.ReadAsAsync(typedContent.GetTypeByStatusCode(StatusCode)).ConfigureAwait(false); var content = task.GetAwaiter().GetResult(); typedContent.SetPropertyByStatusCode(StatusCode, content); } return typedContent; } } public static string GetSchema(HttpStatusCode statusCode) { return MultipleStatusParcelIdGet.GetSchema(statusCode); } } // end class /// <summary> /// Response object for method Put of class StatusParcelId /// </summary> public partial class StatusParcelIdPutResponse : ApiResponse { private MultipleStatusParcelIdPut typedContent; /// <summary> /// Typed response content /// </summary> public MultipleStatusParcelIdPut Content { get { if (typedContent != null) return typedContent; typedContent = new MultipleStatusParcelIdPut(); IEnumerable<string> values = new List<string>(); if (RawContent != null && RawContent.Headers != null) RawContent.Headers.TryGetValues("Content-Type", out values); if (values.Any(hv => hv.ToLowerInvariant().Contains("xml")) && !values.Any(hv => hv.ToLowerInvariant().Contains("json"))) { var task = RawContent.ReadAsStreamAsync(); var xmlStream = task.GetAwaiter().GetResult(); var content = new XmlSerializer(typedContent.GetTypeByStatusCode(StatusCode)).Deserialize(xmlStream); typedContent.SetPropertyByStatusCode(StatusCode, content); } else { var task = Formatters != null && Formatters.Any() ? RawContent.ReadAsAsync(typedContent.GetTypeByStatusCode(StatusCode), Formatters).ConfigureAwait(false) : RawContent.ReadAsAsync(typedContent.GetTypeByStatusCode(StatusCode)).ConfigureAwait(false); var content = task.GetAwaiter().GetResult(); typedContent.SetPropertyByStatusCode(StatusCode, content); } return typedContent; } } public static string GetSchema(HttpStatusCode statusCode) { return MultipleStatusParcelIdPut.GetSchema(statusCode); } } // end class } // end Models namespace
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition { using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Sql.Fluent; using Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Definition; /// <summary> /// The SQL Elastic Pool definition to set the minimum DTU for database. /// </summary> public interface IWithDatabaseDtuMin { /// <summary> /// Sets the minimum DTU all SQL Azure Databases are guaranteed. /// </summary> /// <param name="databaseDtuMin">Minimum DTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithDatabaseDtuMin(int databaseDtuMin); } /// <summary> /// The SQL Elastic Pool definition to set the maximum DTU for one database. /// </summary> public interface IWithDatabaseDtuMax { /// <summary> /// Sets the maximum DTU any one SQL Azure Database can consume. /// </summary> /// <param name="databaseDtuMax">Maximum DTU any one SQL Azure Database can consume.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithDatabaseDtuMax(int databaseDtuMax); } /// <summary> /// A SQL Server definition with sufficient inputs to create a new SQL Elastic Pool in the cloud, /// but exposing additional optional inputs to specify. /// </summary> public interface IWithCreate : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithDatabaseDtuMin, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithDatabaseDtuMax, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithDtu, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStorageCapacity, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithDatabase, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Definition.IDefinitionWithTags<Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.ICreatable<Microsoft.Azure.Management.Sql.Fluent.ISqlElasticPool> { } /// <summary> /// The first stage of the SQL Server Elastic Pool definition. /// </summary> public interface IWithSqlServer { /// <summary> /// Sets the parent SQL server name and resource group it belongs to. /// </summary> /// <param name="resourceGroupName">The name of the resource group the parent SQL server.</param> /// <param name="sqlServerName">The parent SQL server name.</param> /// <param name="location">The parent SQL server location.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithEdition WithExistingSqlServer(string resourceGroupName, string sqlServerName, string location); /// <summary> /// Sets the parent SQL server for the new Elastic Pool. /// </summary> /// <param name="sqlServer">The parent SQL server.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithEdition WithExistingSqlServer(ISqlServer sqlServer); } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a basic pool. /// </summary> public interface IWithBasicEdition : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithBasicEditionBeta { } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a premium pool. /// </summary> public interface IWithPremiumEdition : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEditionBeta { } /// <summary> /// The SQL Elastic Pool definition to set the edition type. /// </summary> public interface IWithEdition : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithEditionBeta { } /// <summary> /// The SQL Elastic Pool definition to set the storage limit for the SQL Azure Database Elastic Pool in MB. /// </summary> public interface IWithStorageCapacity { /// <summary> /// Sets the storage limit for the SQL Azure Database Elastic Pool in MB. /// </summary> /// <param name="storageMB">Storage limit for the SQL Azure Database Elastic Pool in MB.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithStorageCapacity(int storageMB); } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a standard pool. /// </summary> public interface IWithStandardEdition : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate, Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEditionBeta { } /// <summary> /// The SQL Elastic Pool definition to set the number of shared DTU for elastic pool. /// </summary> public interface IWithDtu { /// <summary> /// Sets the total shared DTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="dtu">Total shared DTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithDtu(int dtu); } /// <summary> /// The SQL Elastic Pool definition to add the Database in the Elastic Pool. /// </summary> public interface IWithDatabase : Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithDatabaseBeta { /// <summary> /// Adds an existing database in the SQL elastic pool. /// </summary> /// <param name="databaseName">Name of the existing database to be added in the elastic pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithExistingDatabase(string databaseName); /// <summary> /// Adds the database in the SQL elastic pool. /// </summary> /// <param name="database">Database instance to be added in SQL elastic pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithExistingDatabase(ISqlDatabase database); /// <summary> /// Creates a new database in the SQL elastic pool. /// </summary> /// <param name="databaseName">Name of the new database to be added in the elastic pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithNewDatabase(string databaseName); } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a basic pool. /// </summary> public interface IWithBasicEditionBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithBasicEdition WithDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs eDTU); /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithBasicEdition WithReservedDtu(SqlElasticPoolBasicEDTUs eDTU); /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithBasicEdition WithDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs eDTU); } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a premium pool. /// </summary> public interface IWithPremiumEditionBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEdition WithDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs eDTU); /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEdition WithReservedDtu(SqlElasticPoolPremiumEDTUs eDTU); /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEdition WithDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs eDTU); /// <summary> /// Sets the storage capacity for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="storageCapacity">Storage capacity for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEdition WithStorageCapacity(SqlElasticPoolPremiumSorage storageCapacity); } /// <summary> /// The SQL Elastic Pool definition to set the edition type. /// </summary> public interface IWithEditionBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Sets the basic edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithBasicEdition WithBasicPool(); /// <summary> /// Sets the standard edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEdition WithStandardPool(); /// <summary> /// Sets the edition for the SQL Elastic Pool. /// </summary> /// <param name="edition">Edition to be set for Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate WithEdition(string edition); /// <summary> /// Sets the premium edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithPremiumEdition WithPremiumPool(); } /// <summary> /// The SQL Elastic Pool definition to set the eDTU and storage capacity limits for a standard pool. /// </summary> public interface IWithStandardEditionBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEdition WithDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs eDTU); /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEdition WithReservedDtu(SqlElasticPoolStandardEDTUs eDTU); /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEdition WithDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs eDTU); /// <summary> /// Sets the storage capacity for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="storageCapacity">Storage capacity for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithStandardEdition WithStorageCapacity(SqlElasticPoolStandardStorage storageCapacity); } /// <summary> /// The SQL Elastic Pool definition to add the Database in the Elastic Pool. /// </summary> public interface IWithDatabaseBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Begins the definition of a new SQL Database to be added to this server. /// </summary> /// <param name="databaseName">The name of the new SQL Database.</param> /// <return>The first stage of the new SQL Database definition.</return> Microsoft.Azure.Management.Sql.Fluent.SqlDatabase.Definition.IWithExistingDatabaseAfterElasticPool<Microsoft.Azure.Management.Sql.Fluent.SqlElasticPoolOperations.Definition.IWithCreate> DefineDatabase(string databaseName); } }
// 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; namespace System.Collections.Immutable { /// <summary> /// A set of initialization methods for instances of <see cref="ImmutableList{T}"/>. /// </summary> public static class ImmutableList { /// <summary> /// Returns an empty collection. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>() => ImmutableList<T>.Empty; /// <summary> /// Creates a new immutable collection prefilled with the specified item. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="item">The item to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(T item) => ImmutableList<T>.Empty.Add(item); /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> CreateRange<T>(IEnumerable<T> items) => ImmutableList<T>.Empty.AddRange(items); /// <summary> /// Creates a new immutable collection prefilled with the specified items. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <param name="items">The items to prepopulate.</param> /// <returns>The new immutable collection.</returns> [Pure] public static ImmutableList<T> Create<T>(params T[] items) => ImmutableList<T>.Empty.AddRange(items); /// <summary> /// Creates a new immutable list builder. /// </summary> /// <typeparam name="T">The type of items stored by the collection.</typeparam> /// <returns>The immutable collection builder.</returns> [Pure] public static ImmutableList<T>.Builder CreateBuilder<T>() => Create<T>().ToBuilder(); /// <summary> /// Enumerates a sequence exactly once and produces an immutable list of its contents. /// </summary> /// <typeparam name="TSource">The type of element in the sequence.</typeparam> /// <param name="source">The sequence to enumerate.</param> /// <returns>An immutable list.</returns> [Pure] public static ImmutableList<TSource> ToImmutableList<TSource>(this IEnumerable<TSource> source) { var existingList = source as ImmutableList<TSource>; if (existingList != null) { return existingList; } return ImmutableList<TSource>.Empty.AddRange(source); } /// <summary> /// Returns an immutable copy of the current contents of the builder's collection. /// </summary> /// <param name="builder">The builder to create the immutable list from.</param> /// <returns>An immutable list.</returns> [Pure] public static ImmutableList<TSource> ToImmutableList<TSource>(this ImmutableList<TSource>.Builder builder) { Requires.NotNull(builder, nameof(builder)); return builder.ToImmutable(); } /// <summary> /// Replaces the first equal element in the list with the specified element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="oldValue">The element to replace.</param> /// <param name="newValue">The element to replace the old element with.</param> /// <returns>The new list -- even if the value being replaced is equal to the new value for that position.</returns> /// <exception cref="ArgumentException">Thrown when the old value does not exist in the list.</exception> [Pure] public static IImmutableList<T> Replace<T>(this IImmutableList<T> list, T oldValue, T newValue) { Requires.NotNull(list, nameof(list)); return list.Replace(oldValue, newValue, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified value from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="value">The value to remove.</param> /// <returns>A new list with the element removed, or this list if the element is not in this list.</returns> [Pure] public static IImmutableList<T> Remove<T>(this IImmutableList<T> list, T value) { Requires.NotNull(list, nameof(list)); return list.Remove(value, EqualityComparer<T>.Default); } /// <summary> /// Removes the specified values from this list. /// </summary> /// <param name="list">The list to search.</param> /// <param name="items">The items to remove if matches are found in this list.</param> /// <returns> /// A new list with the elements removed. /// </returns> [Pure] public static IImmutableList<T> RemoveRange<T>(this IImmutableList<T> list, IEnumerable<T> items) { Requires.NotNull(list, nameof(list)); return list.RemoveRange(items, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, 0, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, 0, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, startIndex, list.Count - startIndex, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// first occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the specified index to the last element. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the search. 0 (zero) is valid in an empty /// list. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the first occurrence of item within the range of /// elements in the <see cref="IImmutableList{T}"/> that extends from index /// to the last element, if found; otherwise, -1. /// </returns> [Pure] public static int IndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, nameof(list)); return list.IndexOf(item, startIndex, count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// <see cref="IImmutableList{T}"/>, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item) { Requires.NotNull(list, nameof(list)); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the entire <see cref="IImmutableList{T}"/>. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="equalityComparer">The equality comparer to use in the search.</param> /// <returns> /// The zero-based index of the last occurrence of item within the entire the /// <see cref="IImmutableList{T}"/>, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, IEqualityComparer<T> equalityComparer) { Requires.NotNull(list, nameof(list)); if (list.Count == 0) { // Avoid argument out of range exceptions. return -1; } return list.LastIndexOf(item, list.Count - 1, list.Count, equalityComparer); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the <see cref="IImmutableList{T}"/> that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex) { Requires.NotNull(list, nameof(list)); if (list.Count == 0 && startIndex == 0) { return -1; } return list.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default); } /// <summary> /// Searches for the specified object and returns the zero-based index of the /// last occurrence within the range of elements in the <see cref="IImmutableList{T}"/> /// that extends from the first element to the specified index. /// </summary> /// <param name="list">The list to search.</param> /// <param name="item"> /// The object to locate in the <see cref="IImmutableList{T}"/>. The value /// can be null for reference types. /// </param> /// <param name="startIndex"> /// The zero-based starting index of the backward search. /// </param> /// <param name="count"> /// The number of elements in the section to search. /// </param> /// <returns> /// The zero-based index of the last occurrence of item within the range of elements /// in the <see cref="IImmutableList{T}"/> that extends from the first element /// to index, if found; otherwise, -1. /// </returns> [Pure] public static int LastIndexOf<T>(this IImmutableList<T> list, T item, int startIndex, int count) { Requires.NotNull(list, nameof(list)); return list.LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default); } } }
// 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.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; namespace System.Runtime.InteropServices.WindowsRuntime { [System.Runtime.CompilerServices.DependencyReductionRootAttribute] [McgInternalTypeAttribute] public class PropertyValueImpl : BoxedValue, IPropertyValue { internal PropertyValueImpl(object val, int type) : base(val, type) { } public PropertyType get_Type() { return (PropertyType)m_type; } public bool IsNumericScalar { get { return IsNumericScalarImpl((PropertyType)m_type, m_data); } } public byte GetUInt8() { return CoerceScalarValue<byte>(PropertyType.UInt8); } public short GetInt16() { return CoerceScalarValue<short>(PropertyType.Int16); } public ushort GetUInt16() { return CoerceScalarValue<ushort>(PropertyType.UInt16); } public int GetInt32() { return CoerceScalarValue<int>(PropertyType.Int32); } public uint GetUInt32() { return CoerceScalarValue<uint>(PropertyType.UInt32); } public long GetInt64() { return CoerceScalarValue<long>(PropertyType.Int64); } public ulong GetUInt64() { return CoerceScalarValue<ulong>(PropertyType.UInt64); } public float GetSingle() { return CoerceScalarValue<float>(PropertyType.Single); } public double GetDouble() { return CoerceScalarValue<double>(PropertyType.Double); } public char GetChar16() { CheckType(PropertyType.Char16); return (char)m_data; } public bool GetBoolean() { CheckType(PropertyType.Boolean); return (bool)m_data; } public string GetString() { return CoerceScalarValue<string>(PropertyType.String); } public object GetInspectable() { CheckType(PropertyType.Inspectable); return m_data; } public System.Guid GetGuid() { return CoerceScalarValue<System.Guid>(PropertyType.Guid); } public System.DateTimeOffset GetDateTime() { CheckType(PropertyType.DateTime); return (System.DateTimeOffset)m_data; } public System.TimeSpan GetTimeSpan() { CheckType(PropertyType.TimeSpan); return (System.TimeSpan)m_data; } public global::Windows.Foundation.Point GetPoint() { CheckType(PropertyType.Point); return (global::Windows.Foundation.Point)m_data; } public global::Windows.Foundation.Size GetSize() { CheckType(PropertyType.Size); return (global::Windows.Foundation.Size)m_data; } public global::Windows.Foundation.Rect GetRect() { CheckType(PropertyType.Rect); return (global::Windows.Foundation.Rect)m_data; } public void GetUInt8Array(out byte[] array) { array = CoerceArrayValue<byte>(PropertyType.UInt8Array); } public void GetInt16Array(out short[] array) { array = CoerceArrayValue<short>(PropertyType.Int16Array); } public void GetUInt16Array(out ushort[] array) { array = CoerceArrayValue<ushort>(PropertyType.UInt16Array); } public void GetInt32Array(out int[] array) { array = CoerceArrayValue<int>(PropertyType.Int32Array); } public void GetUInt32Array(out uint[] array) { array = CoerceArrayValue<uint>(PropertyType.UInt32Array); } public void GetInt64Array(out long[] array) { array = CoerceArrayValue<long>(PropertyType.Int64Array); } public void GetUInt64Array(out ulong[] array) { array = CoerceArrayValue<ulong>(PropertyType.UInt64Array); } public void GetSingleArray(out float[] array) { array = CoerceArrayValue<float>(PropertyType.SingleArray); } public void GetDoubleArray(out double[] array) { array = CoerceArrayValue<double>(PropertyType.DoubleArray); } public void GetChar16Array(out char[] array) { CheckType(PropertyType.Char16Array); array = (char[])m_data; } public void GetBooleanArray(out bool[] array) { CheckType(PropertyType.BooleanArray); array = (bool[])m_data; } public void GetStringArray(out string[] array) { array = CoerceArrayValue<string>(PropertyType.StringArray); } public void GetInspectableArray(out object[] array) { CheckType(PropertyType.InspectableArray); array = (object[])m_data; } public void GetGuidArray(out System.Guid[] array) { array = CoerceArrayValue<System.Guid>(PropertyType.GuidArray); } public void GetDateTimeArray(out System.DateTimeOffset[] array) { CheckType(PropertyType.DateTimeArray); array = (System.DateTimeOffset[])m_data; } public void GetTimeSpanArray(out System.TimeSpan[] array) { CheckType(PropertyType.TimeSpanArray); array = (System.TimeSpan[])m_data; } public void GetPointArray(out global::Windows.Foundation.Point[] array) { CheckType(PropertyType.PointArray); array = (global::Windows.Foundation.Point[])m_data; } public void GetSizeArray(out global::Windows.Foundation.Size[] array) { CheckType(PropertyType.SizeArray); array = (global::Windows.Foundation.Size[])m_data; } public void GetRectArray(out global::Windows.Foundation.Rect[] array) { CheckType(PropertyType.RectArray); array = (global::Windows.Foundation.Rect[])m_data; } private T[] CoerceArrayValue<T>(PropertyType unboxType) { // If we contain the type being looked for directly, then take the fast-path if (m_type == (int)unboxType) { return (T[])m_data; } // Make sure we have an array to begin with System.Array dataArray = m_data as System.Array; if (dataArray == null) { throw CreateExceptionForInvalidCast((PropertyType)m_type, unboxType); } // Array types are 1024 larger than their equivilent scalar counterpart if ((m_type <= 1024) || ((int)unboxType <= 1024)) { throw CreateExceptionForInvalidCast((PropertyType)m_type, unboxType); } PropertyType scalarType = (PropertyType)(m_type - 1024); PropertyType unboxTypeT = unboxType - 1024; // If we do not have the correct array type, then we need to convert the array element-by-element // to a new array of the requested type T[] coercedArray = new T[dataArray.Length]; for (int i = 0; i < dataArray.Length; ++i) { coercedArray[i] = (T)CoerceScalarValue(scalarType, dataArray.GetValue(i), unboxTypeT); } return coercedArray; } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] private T CoerceScalarValue<T>(PropertyType unboxType) { object result = m_data; // If we are just a boxed version of the requested type, then take the fast path out if (m_type != (int)unboxType) { result = CoerceScalarValue((PropertyType)m_type, result, unboxType); } return (T)result; } static private object CoerceScalarValue(PropertyType type, object value, PropertyType unboxType) { // If the property type is neither one of the coercable numeric types nor IInspectable, we // should not attempt coersion, even if the underlying value is technically convertable if ((type == PropertyType.Guid) && (unboxType == PropertyType.String)) { // String <--> Guid is allowed return ((System.Guid)value).ToString(); } else if ((type == PropertyType.String) && (unboxType == PropertyType.Guid)) { System.Guid result; if (System.Guid.TryParse((string)value, out result)) { return result; } } else if (type == PropertyType.Inspectable) { // If the property type is IInspectable, and we have a nested IPropertyValue, then we need // to pass along the request to coerce the value. IPropertyValue ipv = value as IPropertyValue; if (ipv != null) { object result = ReferenceUtility.GetWellKnownScalar(ipv, unboxType); if (result != null) { return result; } Debug.Assert( false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync" ); } } else if (type == PropertyType.Boolean || type == PropertyType.Char16) { throw CreateExceptionForInvalidCoersion(type, value, unboxType, Interop.COM.TYPE_E_TYPEMISMATCH); } // // Let Convert handle all possible conversions - this include // 1. string - which desktop code accidentally allowed // 2. object (IInspectable) // try { switch (unboxType) { case PropertyType.UInt8: return System.Convert.ToByte(value); case PropertyType.Int16: return System.Convert.ToInt16(value); case PropertyType.UInt16: return System.Convert.ToUInt16(value); case PropertyType.Int32: return System.Convert.ToInt32(value); case PropertyType.UInt32: return System.Convert.ToUInt32(value); case PropertyType.Int64: return System.Convert.ToInt64(value); case PropertyType.UInt64: return System.Convert.ToUInt64(value); case PropertyType.Single: return System.Convert.ToSingle(value); case PropertyType.Double: return System.Convert.ToDouble(value); default: break; } } catch (System.FormatException) { throw CreateExceptionForInvalidCoersion(type, value, unboxType, Interop.COM.TYPE_E_TYPEMISMATCH); } catch (System.InvalidCastException) { throw CreateExceptionForInvalidCoersion(type, value, unboxType, Interop.COM.TYPE_E_TYPEMISMATCH); } catch (System.OverflowException) { throw CreateExceptionForInvalidCoersion(type, value, unboxType, Interop.COM.DISP_E_OVERFLOW); } throw CreateExceptionForInvalidCast(type, unboxType); } private static bool IsNumericScalarImpl(PropertyType type, object data) { switch (type) { case PropertyType.UInt8: case PropertyType.Int16: case PropertyType.UInt16: case PropertyType.Int32: case PropertyType.UInt32: case PropertyType.Int64: case PropertyType.UInt64: case PropertyType.Single: case PropertyType.Double: return true; default: return McgMarshal.IsEnum(data); } } private void CheckType(PropertyType unboxType) { if (this.get_Type() != unboxType) { throw CreateExceptionForInvalidCast(this.get_Type(), unboxType); } } private static System.InvalidCastException CreateExceptionForInvalidCast( PropertyType type, PropertyType unboxType) { return new System.InvalidCastException(SR.Format(SR.PropertyValue_InvalidCast, type, unboxType), Interop.COM.TYPE_E_TYPEMISMATCH); } private static System.InvalidCastException CreateExceptionForInvalidCoersion( PropertyType type, object value, PropertyType unboxType, int hr) { return new InvalidCastException(SR.Format(SR.PropertyValue_InvalidCoersion, type, value, unboxType), hr); } } internal class ReferenceUtility { internal static object GetWellKnownScalar(IPropertyValue ipv, PropertyType type) { switch (type) { case PropertyType.UInt8: return ipv.GetUInt8(); case PropertyType.Int16: return ipv.GetInt16(); case PropertyType.UInt16: return ipv.GetUInt16(); case PropertyType.Int32: return ipv.GetInt32(); case PropertyType.UInt32: return ipv.GetUInt32(); case PropertyType.Int64: return ipv.GetInt64(); case PropertyType.UInt64: return ipv.GetUInt64(); case PropertyType.Single: return ipv.GetSingle(); case PropertyType.Double: return ipv.GetDouble(); } Debug.Assert(false); return null; } } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. namespace SixLabors.Fonts.Unicode { /// <summary> /// Unicode Script classes <see href="http://www.unicode.org/reports/tr24/#Script"/> /// </summary> public enum ScriptClass { /// <summary> /// Shortcode: Zzzz /// </summary> Unknown, /// <summary> /// Shortcode: Zyyy /// </summary> Common, /// <summary> /// Shortcode: Zinh, Qaai /// </summary> Inherited, /// <summary> /// Shortcode: Adlm /// </summary> Adlam, /// <summary> /// Shortcode: Aghb /// </summary> CaucasianAlbanian, /// <summary> /// Shortcode: Ahom /// </summary> Ahom, /// <summary> /// Shortcode: Arab /// </summary> Arabic, /// <summary> /// Shortcode: Armi /// </summary> ImperialAramaic, /// <summary> /// Shortcode: Armn /// </summary> Armenian, /// <summary> /// Shortcode: Avst /// </summary> Avestan, /// <summary> /// Shortcode: Bali /// </summary> Balinese, /// <summary> /// Shortcode: Bamu /// </summary> Bamum, /// <summary> /// Shortcode: Bass /// </summary> BassaVah, /// <summary> /// Shortcode: Batk /// </summary> Batak, /// <summary> /// Shortcode: Beng /// </summary> Bengali, /// <summary> /// Shortcode: Bhks /// </summary> Bhaiksuki, /// <summary> /// Shortcode: Bopo /// </summary> Bopomofo, /// <summary> /// Shortcode: Brah /// </summary> Brahmi, /// <summary> /// Shortcode: Brai /// </summary> Braille, /// <summary> /// Shortcode: Bugi /// </summary> Buginese, /// <summary> /// Shortcode: Buhd /// </summary> Buhid, /// <summary> /// Shortcode: Cakm /// </summary> Chakma, /// <summary> /// Shortcode: Cans /// </summary> CanadianAboriginal, /// <summary> /// Shortcode: Cari /// </summary> Carian, /// <summary> /// Shortcode: Cham /// </summary> Cham, /// <summary> /// Shortcode: Cher /// </summary> Cherokee, /// <summary> /// Shortcode: Chrs /// </summary> Chorasmian, /// <summary> /// Shortcode: Copt, Qaac /// </summary> Coptic, /// <summary> /// Shortcode: Cpmn /// </summary> CyproMinoan, /// <summary> /// Shortcode: Cprt /// </summary> Cypriot, /// <summary> /// Shortcode: Cyrl /// </summary> Cyrillic, /// <summary> /// Shortcode: Deva /// </summary> Devanagari, /// <summary> /// Shortcode: Diak /// </summary> DivesAkuru, /// <summary> /// Shortcode: Dogr /// </summary> Dogra, /// <summary> /// Shortcode: Dsrt /// </summary> Deseret, /// <summary> /// Shortcode: Dupl /// </summary> Duployan, /// <summary> /// Shortcode: Egyp /// </summary> EgyptianHieroglyphs, /// <summary> /// Shortcode: Elba /// </summary> Elbasan, /// <summary> /// Shortcode: Elym /// </summary> Elymaic, /// <summary> /// Shortcode: Ethi /// </summary> Ethiopic, /// <summary> /// Shortcode: Geor /// </summary> Georgian, /// <summary> /// Shortcode: Glag /// </summary> Glagolitic, /// <summary> /// Shortcode: Gong /// </summary> GunjalaGondi, /// <summary> /// Shortcode: Gonm /// </summary> MasaramGondi, /// <summary> /// Shortcode: Goth /// </summary> Gothic, /// <summary> /// Shortcode: Gran /// </summary> Grantha, /// <summary> /// Shortcode: Grek /// </summary> Greek, /// <summary> /// Shortcode: Gujr /// </summary> Gujarati, /// <summary> /// Shortcode: Guru /// </summary> Gurmukhi, /// <summary> /// Shortcode: Hang /// </summary> Hangul, /// <summary> /// Shortcode: Hani /// </summary> Han, /// <summary> /// Shortcode: Hano /// </summary> Hanunoo, /// <summary> /// Shortcode: Hatr /// </summary> Hatran, /// <summary> /// Shortcode: Hebr /// </summary> Hebrew, /// <summary> /// Shortcode: Hira /// </summary> Hiragana, /// <summary> /// Shortcode: Hluw /// </summary> AnatolianHieroglyphs, /// <summary> /// Shortcode: Hmng /// </summary> PahawhHmong, /// <summary> /// Shortcode: Hmnp /// </summary> NyiakengPuachueHmong, /// <summary> /// Shortcode: Hrkt /// </summary> KatakanaOrHiragana, /// <summary> /// Shortcode: Hung /// </summary> OldHungarian, /// <summary> /// Shortcode: Ital /// </summary> OldItalic, /// <summary> /// Shortcode: Java /// </summary> Javanese, /// <summary> /// Shortcode: Kali /// </summary> KayahLi, /// <summary> /// Shortcode: Kana /// </summary> Katakana, /// <summary> /// Shortcode: Khar /// </summary> Kharoshthi, /// <summary> /// Shortcode: Khmr /// </summary> Khmer, /// <summary> /// Shortcode: Khoj /// </summary> Khojki, /// <summary> /// Shortcode: Kits /// </summary> KhitanSmallScript, /// <summary> /// Shortcode: Knda /// </summary> Kannada, /// <summary> /// Shortcode: Kthi /// </summary> Kaithi, /// <summary> /// Shortcode: Lana /// </summary> TaiTham, /// <summary> /// Shortcode: Laoo /// </summary> Lao, /// <summary> /// Shortcode: Latn /// </summary> Latin, /// <summary> /// Shortcode: Lepc /// </summary> Lepcha, /// <summary> /// Shortcode: Limb /// </summary> Limbu, /// <summary> /// Shortcode: Lina /// </summary> LinearA, /// <summary> /// Shortcode: Linb /// </summary> LinearB, /// <summary> /// Shortcode: Lisu /// </summary> Lisu, /// <summary> /// Shortcode: Lyci /// </summary> Lycian, /// <summary> /// Shortcode: Lydi /// </summary> Lydian, /// <summary> /// Shortcode: Mahj /// </summary> Mahajani, /// <summary> /// Shortcode: Maka /// </summary> Makasar, /// <summary> /// Shortcode: Mand /// </summary> Mandaic, /// <summary> /// Shortcode: Mani /// </summary> Manichaean, /// <summary> /// Shortcode: Marc /// </summary> Marchen, /// <summary> /// Shortcode: Medf /// </summary> Medefaidrin, /// <summary> /// Shortcode: Mend /// </summary> MendeKikakui, /// <summary> /// Shortcode: Merc /// </summary> MeroiticCursive, /// <summary> /// Shortcode: Mero /// </summary> MeroiticHieroglyphs, /// <summary> /// Shortcode: Mlym /// </summary> Malayalam, /// <summary> /// Shortcode: Modi /// </summary> Modi, /// <summary> /// Shortcode: Mong /// </summary> Mongolian, /// <summary> /// Shortcode: Mroo /// </summary> Mro, /// <summary> /// Shortcode: Mtei /// </summary> MeeteiMayek, /// <summary> /// Shortcode: Mult /// </summary> Multani, /// <summary> /// Shortcode: Mymr /// </summary> Myanmar, /// <summary> /// Shortcode: Nand /// </summary> Nandinagari, /// <summary> /// Shortcode: Narb /// </summary> OldNorthArabian, /// <summary> /// Shortcode: Nbat /// </summary> Nabataean, /// <summary> /// Shortcode: Newa /// </summary> Newa, /// <summary> /// Shortcode: Nkoo /// </summary> Nko, /// <summary> /// Shortcode: Nshu /// </summary> Nushu, /// <summary> /// Shortcode: Ogam /// </summary> Ogham, /// <summary> /// Shortcode: Olck /// </summary> OlChiki, /// <summary> /// Shortcode: Orkh /// </summary> OldTurkic, /// <summary> /// Shortcode: Orya /// </summary> Oriya, /// <summary> /// Shortcode: Osge /// </summary> Osage, /// <summary> /// Shortcode: Osma /// </summary> Osmanya, /// <summary> /// Shortcode: Ougr /// </summary> OldUyghur, /// <summary> /// Shortcode: Palm /// </summary> Palmyrene, /// <summary> /// Shortcode: Pauc /// </summary> PauCinHau, /// <summary> /// Shortcode: Perm /// </summary> OldPermic, /// <summary> /// Shortcode: Phag /// </summary> PhagsPa, /// <summary> /// Shortcode: Phli /// </summary> InscriptionalPahlavi, /// <summary> /// Shortcode: Phlp /// </summary> PsalterPahlavi, /// <summary> /// Shortcode: Phnx /// </summary> Phoenician, /// <summary> /// Shortcode: Plrd /// </summary> Miao, /// <summary> /// Shortcode: Prti /// </summary> InscriptionalParthian, /// <summary> /// Shortcode: Rjng /// </summary> Rejang, /// <summary> /// Shortcode: Rohg /// </summary> HanifiRohingya, /// <summary> /// Shortcode: Runr /// </summary> Runic, /// <summary> /// Shortcode: Samr /// </summary> Samaritan, /// <summary> /// Shortcode: Sarb /// </summary> OldSouthArabian, /// <summary> /// Shortcode: Saur /// </summary> Saurashtra, /// <summary> /// Shortcode: Sgnw /// </summary> SignWriting, /// <summary> /// Shortcode: Shaw /// </summary> Shavian, /// <summary> /// Shortcode: Shrd /// </summary> Sharada, /// <summary> /// Shortcode: Sidd /// </summary> Siddham, /// <summary> /// Shortcode: Sind /// </summary> Khudawadi, /// <summary> /// Shortcode: Sinh /// </summary> Sinhala, /// <summary> /// Shortcode: Sogd /// </summary> Sogdian, /// <summary> /// Shortcode: Sogo /// </summary> OldSogdian, /// <summary> /// Shortcode: Sora /// </summary> SoraSompeng, /// <summary> /// Shortcode: Soyo /// </summary> Soyombo, /// <summary> /// Shortcode: Sund /// </summary> Sundanese, /// <summary> /// Shortcode: Sylo /// </summary> SylotiNagri, /// <summary> /// Shortcode: Syrc /// </summary> Syriac, /// <summary> /// Shortcode: Tagb /// </summary> Tagbanwa, /// <summary> /// Shortcode: Takr /// </summary> Takri, /// <summary> /// Shortcode: Tale /// </summary> TaiLe, /// <summary> /// Shortcode: Talu /// </summary> NewTaiLue, /// <summary> /// Shortcode: Taml /// </summary> Tamil, /// <summary> /// Shortcode: Tang /// </summary> Tangut, /// <summary> /// Shortcode: Tavt /// </summary> TaiViet, /// <summary> /// Shortcode: Telu /// </summary> Telugu, /// <summary> /// Shortcode: Tfng /// </summary> Tifinagh, /// <summary> /// Shortcode: Tglg /// </summary> Tagalog, /// <summary> /// Shortcode: Thaa /// </summary> Thaana, /// <summary> /// Shortcode: Thai /// </summary> Thai, /// <summary> /// Shortcode: Tibt /// </summary> Tibetan, /// <summary> /// Shortcode: Tirh /// </summary> Tirhuta, /// <summary> /// Shortcode: Tnsa /// </summary> Tangsa, /// <summary> /// Shortcode: Toto /// </summary> Toto, /// <summary> /// Shortcode: Ugar /// </summary> Ugaritic, /// <summary> /// Shortcode: Vaii /// </summary> Vai, /// <summary> /// Shortcode: Vith /// </summary> Vithkuqi, /// <summary> /// Shortcode: Wara /// </summary> WarangCiti, /// <summary> /// Shortcode: Wcho /// </summary> Wancho, /// <summary> /// Shortcode: Xpeo /// </summary> OldPersian, /// <summary> /// Shortcode: Xsux /// </summary> Cuneiform, /// <summary> /// Shortcode: Yezi /// </summary> Yezidi, /// <summary> /// Shortcode: Yiii /// </summary> Yi, /// <summary> /// Shortcode: Zanb /// </summary> ZanabazarSquare, } }
// 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.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.CodeAnalysis.Sarif.Readers; namespace Microsoft.CodeAnalysis.Sarif { /// <summary> /// Defines methods to support the comparison of objects of type StackFrame for equality. /// </summary> [GeneratedCode("Microsoft.Json.Schema.ToDotNet", "0.42.0.0")] internal sealed class StackFrameEqualityComparer : IEqualityComparer<StackFrame> { internal static readonly StackFrameEqualityComparer Instance = new StackFrameEqualityComparer(); public bool Equals(StackFrame left, StackFrame right) { if (ReferenceEquals(left, right)) { return true; } if (ReferenceEquals(left, null) || ReferenceEquals(right, null)) { return false; } if (left.Message != right.Message) { return false; } if (left.Uri != right.Uri) { return false; } if (left.UriBaseId != right.UriBaseId) { return false; } if (left.Line != right.Line) { return false; } if (left.Column != right.Column) { return false; } if (left.Module != right.Module) { return false; } if (left.ThreadId != right.ThreadId) { return false; } if (left.FullyQualifiedLogicalName != right.FullyQualifiedLogicalName) { return false; } if (left.LogicalLocationKey != right.LogicalLocationKey) { return false; } if (left.Address != right.Address) { return false; } if (left.Offset != right.Offset) { return false; } if (!object.ReferenceEquals(left.Parameters, right.Parameters)) { if (left.Parameters == null || right.Parameters == null) { return false; } if (left.Parameters.Count != right.Parameters.Count) { return false; } for (int index_0 = 0; index_0 < left.Parameters.Count; ++index_0) { if (left.Parameters[index_0] != right.Parameters[index_0]) { return false; } } } if (!object.ReferenceEquals(left.Properties, right.Properties)) { if (left.Properties == null || right.Properties == null || left.Properties.Count != right.Properties.Count) { return false; } foreach (var value_0 in left.Properties) { SerializedPropertyInfo value_1; if (!right.Properties.TryGetValue(value_0.Key, out value_1)) { return false; } if (!object.Equals(value_0.Value, value_1)) { return false; } } } return true; } public int GetHashCode(StackFrame obj) { if (ReferenceEquals(obj, null)) { return 0; } int result = 17; unchecked { if (obj.Message != null) { result = (result * 31) + obj.Message.GetHashCode(); } if (obj.Uri != null) { result = (result * 31) + obj.Uri.GetHashCode(); } if (obj.UriBaseId != null) { result = (result * 31) + obj.UriBaseId.GetHashCode(); } result = (result * 31) + obj.Line.GetHashCode(); result = (result * 31) + obj.Column.GetHashCode(); if (obj.Module != null) { result = (result * 31) + obj.Module.GetHashCode(); } result = (result * 31) + obj.ThreadId.GetHashCode(); if (obj.FullyQualifiedLogicalName != null) { result = (result * 31) + obj.FullyQualifiedLogicalName.GetHashCode(); } if (obj.LogicalLocationKey != null) { result = (result * 31) + obj.LogicalLocationKey.GetHashCode(); } result = (result * 31) + obj.Address.GetHashCode(); result = (result * 31) + obj.Offset.GetHashCode(); if (obj.Parameters != null) { foreach (var value_2 in obj.Parameters) { result = result * 31; if (value_2 != null) { result = (result * 31) + value_2.GetHashCode(); } } } if (obj.Properties != null) { // Use xor for dictionaries to be order-independent. int xor_0 = 0; foreach (var value_3 in obj.Properties) { xor_0 ^= value_3.Key.GetHashCode(); if (value_3.Value != null) { xor_0 ^= value_3.Value.GetHashCode(); } } result = (result * 31) + xor_0; } } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Data.Common; using System.Data.SqlClient.Resources; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Data.SqlClient { static internal class AsyncHelper { internal static Task CreateContinuationTask(Task task, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) { if (task == null) { onSuccess(); return null; } else { TaskCompletionSource<object> completion = new TaskCompletionSource<object>(); ContinueTask(task, completion, () => { onSuccess(); completion.SetResult(null); }, connectionToDoom, onFailure); return completion.Task; } } internal static Task CreateContinuationTask<T1, T2>(Task task, Action<T1, T2> onSuccess, T1 arg1, T2 arg2, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null) { return CreateContinuationTask(task, () => onSuccess(arg1, arg2), connectionToDoom, onFailure); } internal static void ContinueTask(Task task, TaskCompletionSource<object> completion, Action onSuccess, SqlInternalConnectionTds connectionToDoom = null, Action<Exception> onFailure = null, Action onCancellation = null, Func<Exception, Exception> exceptionConverter = null, SqlConnection connectionToAbort = null ) { Debug.Assert((connectionToAbort == null) || (connectionToDoom == null), "Should not specify both connectionToDoom and connectionToAbort"); task.ContinueWith( tsk => { if (tsk.Exception != null) { Exception exc = tsk.Exception.InnerException; if (exceptionConverter != null) { exc = exceptionConverter(exc); } try { if (onFailure != null) { onFailure(exc); } } finally { completion.TrySetException(exc); } } else if (tsk.IsCanceled) { try { if (onCancellation != null) { onCancellation(); } } finally { completion.TrySetCanceled(); } } else { try { onSuccess(); } catch (Exception e) { completion.SetException(e); } } }, TaskScheduler.Default ); } internal static void WaitForCompletion(Task task, int timeout, Action onTimeout = null, bool rethrowExceptions = true) { try { task.Wait(timeout > 0 ? (1000 * timeout) : Timeout.Infinite); } catch (AggregateException ae) { if (rethrowExceptions) { Debug.Assert(ae.InnerExceptions.Count == 1, "There is more than one exception in AggregateException"); ExceptionDispatchInfo.Capture(ae.InnerException).Throw(); } } if (!task.IsCompleted) { if (onTimeout != null) { onTimeout(); } } } internal static void SetTimeoutException(TaskCompletionSource<object> completion, int timeout, Func<Exception> exc, CancellationToken ctoken) { if (timeout > 0) { Task.Delay(timeout * 1000, ctoken).ContinueWith((tsk) => { if (!tsk.IsCanceled && !completion.Task.IsCompleted) { completion.TrySetException(exc()); } }); } } } static internal class SQL { // The class SQL defines the exceptions that are specific to the SQL Adapter. // The class contains functions that take the proper informational variables and then construct // the appropriate exception with an error string obtained from the resource Framework.txt. // The exception is then returned to the caller, so that the caller may then throw from its // location so that the catcher of the exception will have the appropriate call stack. // This class is used so that there will be compile time checking of error // messages. The resource Framework.txt will ensure proper string text based on the appropriate // locale. // // SQL specific exceptions // // // SQL.Connection // static internal Exception InvalidInternalPacketSize(string str) { return ADP.ArgumentOutOfRange(str); } static internal Exception InvalidPacketSize() { return ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_InvalidTDSPacketSize)); } static internal Exception InvalidPacketSizeValue() { return ADP.Argument(Res.GetString(Res.SQL_InvalidPacketSizeValue)); } static internal Exception InvalidSSPIPacketSize() { return ADP.Argument(Res.GetString(Res.SQL_InvalidSSPIPacketSize)); } static internal Exception NullEmptyTransactionName() { return ADP.Argument(Res.GetString(Res.SQL_NullEmptyTransactionName)); } static internal Exception UserInstanceFailoverNotCompatible() { return ADP.Argument(Res.GetString(Res.SQL_UserInstanceFailoverNotCompatible)); } static internal Exception InvalidSQLServerVersionUnknown() { return ADP.DataAdapter(Res.GetString(Res.SQL_InvalidSQLServerVersionUnknown)); } static internal Exception SynchronousCallMayNotPend() { return new Exception(Res.GetString(Res.Sql_InternalError)); } static internal Exception ConnectionLockedForBcpEvent() { return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionLockedForBcpEvent)); } static internal Exception InstanceFailure() { return ADP.InvalidOperation(Res.GetString(Res.SQL_InstanceFailure)); } static internal Exception InvalidPartnerConfiguration(string server, string database) { return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidPartnerConfiguration, server, database)); } static internal Exception MARSUnspportedOnConnection() { return ADP.InvalidOperation(Res.GetString(Res.SQL_MarsUnsupportedOnConnection)); } static internal Exception CannotModifyPropertyAsyncOperationInProgress([CallerMemberName] string property = "") { return ADP.InvalidOperation(Res.GetString(Res.SQL_CannotModifyPropertyAsyncOperationInProgress, property)); } static internal Exception NonLocalSSEInstance() { return ADP.NotSupported(Res.GetString(Res.SQL_NonLocalSSEInstance)); } // // SQL.DataCommand // static internal ArgumentOutOfRangeException NotSupportedEnumerationValue(Type type, int value) { return ADP.ArgumentOutOfRange(Res.GetString(Res.SQL_NotSupportedEnumerationValue, type.Name, value.ToString(System.Globalization.CultureInfo.InvariantCulture)), type.Name); } static internal ArgumentOutOfRangeException NotSupportedCommandType(CommandType value) { #if DEBUG switch (value) { case CommandType.Text: case CommandType.StoredProcedure: Debug.Assert(false, "valid CommandType " + value.ToString()); break; case CommandType.TableDirect: break; default: Debug.Assert(false, "invalid CommandType " + value.ToString()); break; } #endif return NotSupportedEnumerationValue(typeof(CommandType), (int)value); } static internal ArgumentOutOfRangeException NotSupportedIsolationLevel(IsolationLevel value) { #if DEBUG switch (value) { case IsolationLevel.Unspecified: case IsolationLevel.ReadCommitted: case IsolationLevel.ReadUncommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: Debug.Assert(false, "valid IsolationLevel " + value.ToString()); break; case IsolationLevel.Chaos: break; default: Debug.Assert(false, "invalid IsolationLevel " + value.ToString()); break; } #endif return NotSupportedEnumerationValue(typeof(IsolationLevel), (int)value); } static internal Exception OperationCancelled() { Exception exception = ADP.InvalidOperation(Res.GetString(Res.SQL_OperationCancelled)); return exception; } static internal Exception PendingBeginXXXExists() { return ADP.InvalidOperation(Res.GetString(Res.SQL_PendingBeginXXXExists)); } static internal Exception NonXmlResult() { return ADP.InvalidOperation(Res.GetString(Res.SQL_NonXmlResult)); } // // SQL.DataParameter // static internal Exception InvalidParameterTypeNameFormat() { return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterTypeNameFormat)); } static internal Exception InvalidParameterNameLength(string value) { return ADP.Argument(Res.GetString(Res.SQL_InvalidParameterNameLength, value)); } static internal Exception PrecisionValueOutOfRange(byte precision) { return ADP.Argument(Res.GetString(Res.SQL_PrecisionValueOutOfRange, precision.ToString(CultureInfo.InvariantCulture))); } static internal Exception ScaleValueOutOfRange(byte scale) { return ADP.Argument(Res.GetString(Res.SQL_ScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } static internal Exception TimeScaleValueOutOfRange(byte scale) { return ADP.Argument(Res.GetString(Res.SQL_TimeScaleValueOutOfRange, scale.ToString(CultureInfo.InvariantCulture))); } static internal Exception InvalidSqlDbType(SqlDbType value) { return ADP.InvalidEnumerationValue(typeof(SqlDbType), (int)value); } static internal Exception UnsupportedTVPOutputParameter(ParameterDirection direction, string paramName) { return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnsupportedTVPOutputParameter, direction.ToString(), paramName)); } static internal Exception DBNullNotSupportedForTVPValues(string paramName) { return ADP.NotSupported(Res.GetString(Res.SqlParameter_DBNullNotSupportedForTVP, paramName)); } static internal Exception UnexpectedTypeNameForNonStructParams(string paramName) { return ADP.NotSupported(Res.GetString(Res.SqlParameter_UnexpectedTypeNameForNonStruct, paramName)); } static internal Exception ParameterInvalidVariant(string paramName) { return ADP.InvalidOperation(Res.GetString(Res.SQL_ParameterInvalidVariant, paramName)); } static internal Exception MustSetTypeNameForParam(string paramType, string paramName) { return ADP.Argument(Res.GetString(Res.SQL_ParameterTypeNameRequired, paramType, paramName)); } static internal Exception EnumeratedRecordMetaDataChanged(string fieldName, int recordNumber) { return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordMetaDataChanged, fieldName, recordNumber)); } static internal Exception EnumeratedRecordFieldCountChanged(int recordNumber) { return ADP.Argument(Res.GetString(Res.SQL_EnumeratedRecordFieldCountChanged, recordNumber)); } // // SQL.SqlDataAdapter // // // SQL.TDSParser // static internal Exception InvalidTDSVersion() { return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidTDSVersion)); } static internal Exception ParsingError() { return ADP.InvalidOperation(Res.GetString(Res.SQL_ParsingError)); } static internal Exception MoneyOverflow(string moneyValue) { return ADP.Overflow(Res.GetString(Res.SQL_MoneyOverflow, moneyValue)); } static internal Exception SmallDateTimeOverflow(string datetime) { return ADP.Overflow(Res.GetString(Res.SQL_SmallDateTimeOverflow, datetime)); } static internal Exception SNIPacketAllocationFailure() { return ADP.InvalidOperation(Res.GetString(Res.SQL_SNIPacketAllocationFailure)); } static internal Exception TimeOverflow(string time) { return ADP.Overflow(Res.GetString(Res.SQL_TimeOverflow, time)); } // // SQL.SqlDataReader // static internal Exception InvalidRead() { return ADP.InvalidOperation(Res.GetString(Res.SQL_InvalidRead)); } static internal Exception NonBlobColumn(string columnName) { return ADP.InvalidCast(Res.GetString(Res.SQL_NonBlobColumn, columnName)); } static internal Exception NonCharColumn(string columnName) { return ADP.InvalidCast(Res.GetString(Res.SQL_NonCharColumn, columnName)); } static internal Exception StreamNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(Res.GetString(Res.SQL_StreamNotSupportOnColumnType, columnName)); } static internal Exception TextReaderNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(Res.GetString(Res.SQL_TextReaderNotSupportOnColumnType, columnName)); } static internal Exception XmlReaderNotSupportOnColumnType(string columnName) { return ADP.InvalidCast(Res.GetString(Res.SQL_XmlReaderNotSupportOnColumnType, columnName)); } static internal Exception InvalidSqlDbTypeForConstructor(SqlDbType type) { return ADP.Argument(Res.GetString(Res.SqlMetaData_InvalidSqlDbTypeForConstructorFormat, type.ToString())); } static internal Exception NameTooLong(string parameterName) { return ADP.Argument(Res.GetString(Res.SqlMetaData_NameTooLong), parameterName); } static internal Exception InvalidSortOrder(SortOrder order) { return ADP.InvalidEnumerationValue(typeof(SortOrder), (int)order); } static internal Exception MustSpecifyBothSortOrderAndOrdinal(SortOrder order, int ordinal) { return ADP.InvalidOperation(Res.GetString(Res.SqlMetaData_SpecifyBothSortOrderAndOrdinal, order.ToString(), ordinal)); } static internal Exception UnsupportedColumnTypeForSqlProvider(string columnName, string typeName) { return ADP.Argument(Res.GetString(Res.SqlProvider_InvalidDataColumnType, columnName, typeName)); } static internal Exception NotEnoughColumnsInStructuredType() { return ADP.Argument(Res.GetString(Res.SqlProvider_NotEnoughColumnsInStructuredType)); } static internal Exception DuplicateSortOrdinal(int sortOrdinal) { return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_DuplicateSortOrdinal, sortOrdinal)); } static internal Exception MissingSortOrdinal(int sortOrdinal) { return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_MissingSortOrdinal, sortOrdinal)); } static internal Exception SortOrdinalGreaterThanFieldCount(int columnOrdinal, int sortOrdinal) { return ADP.InvalidOperation(Res.GetString(Res.SqlProvider_SortOrdinalGreaterThanFieldCount, sortOrdinal, columnOrdinal)); } static internal Exception IEnumerableOfSqlDataRecordHasNoRows() { return ADP.Argument(Res.GetString(Res.IEnumerableOfSqlDataRecordHasNoRows)); } // // SQL.BulkLoad // static internal Exception BulkLoadMappingInaccessible() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingInaccessible)); } static internal Exception BulkLoadMappingsNamesOrOrdinalsOnly() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMappingsNamesOrOrdinalsOnly)); } static internal Exception BulkLoadCannotConvertValue(Type sourcetype, MetaType metatype, Exception e) { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadCannotConvertValue, sourcetype.Name, metatype.TypeName), e); } static internal Exception BulkLoadNonMatchingColumnMapping() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnMapping)); } static internal Exception BulkLoadNonMatchingColumnName(string columnName) { return BulkLoadNonMatchingColumnName(columnName, null); } static internal Exception BulkLoadNonMatchingColumnName(string columnName, Exception e) { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNonMatchingColumnName, columnName), e); } static internal Exception BulkLoadStringTooLong() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadStringTooLong)); } static internal Exception BulkLoadInvalidVariantValue() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidVariantValue)); } static internal Exception BulkLoadInvalidTimeout(int timeout) { return ADP.Argument(Res.GetString(Res.SQL_BulkLoadInvalidTimeout, timeout.ToString(CultureInfo.InvariantCulture))); } static internal Exception BulkLoadExistingTransaction() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadExistingTransaction)); } static internal Exception BulkLoadNoCollation() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNoCollation)); } static internal Exception BulkLoadConflictingTransactionOption() { return ADP.Argument(Res.GetString(Res.SQL_BulkLoadConflictingTransactionOption)); } static internal Exception BulkLoadLcidMismatch(int sourceLcid, string sourceColumnName, int destinationLcid, string destinationColumnName) { return ADP.InvalidOperation(Res.GetString(Res.Sql_BulkLoadLcidMismatch, sourceLcid, sourceColumnName, destinationLcid, destinationColumnName)); } static internal Exception InvalidOperationInsideEvent() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidOperationInsideEvent)); } static internal Exception BulkLoadMissingDestinationTable() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadMissingDestinationTable)); } static internal Exception BulkLoadInvalidDestinationTable(string tableName, Exception inner) { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadInvalidDestinationTable, tableName), inner); } static internal Exception BulkLoadBulkLoadNotAllowDBNull(string columnName) { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadNotAllowDBNull, columnName)); } static internal Exception BulkLoadPendingOperation() { return ADP.InvalidOperation(Res.GetString(Res.SQL_BulkLoadPendingOperation)); } // // transactions. // static internal Exception ConnectionDoomed() { return ADP.InvalidOperation(Res.GetString(Res.SQL_ConnectionDoomed)); } static internal Exception OpenResultCountExceeded() { return ADP.InvalidOperation(Res.GetString(Res.SQL_OpenResultCountExceeded)); } static internal readonly byte[] AttentionHeader = new byte[] { TdsEnums.MT_ATTN, // Message Type TdsEnums.ST_EOM, // Status TdsEnums.HEADER_LEN >> 8, // length - upper byte TdsEnums.HEADER_LEN & 0xff, // length - lower byte 0, // spid 0, // spid 0, // packet (out of band) 0 // window }; // // MultiSubnetFailover // /// <summary> /// used to block two scenarios if MultiSubnetFailover is true: /// * server-provided failover partner - raising SqlException in this case /// * connection string with failover partner and MultiSubnetFailover=true - raising argument one in this case with the same message /// </summary> static internal Exception MultiSubnetFailoverWithFailoverPartner(bool serverProvidedFailoverPartner, SqlInternalConnectionTds internalConnection) { string msg = Res.GetString(Res.SQLMSF_FailoverPartnerNotSupported); if (serverProvidedFailoverPartner) { // Replacing InvalidOperation with SQL exception SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, msg, "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; // disable open retry logic on this error return exc; } else { return ADP.Argument(msg); } } static internal Exception MultiSubnetFailoverWithMoreThan64IPs() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithMoreThan64IPs); return ADP.InvalidOperation(msg); } static internal Exception MultiSubnetFailoverWithInstanceSpecified() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithInstanceSpecified); return ADP.Argument(msg); } static internal Exception MultiSubnetFailoverWithNonTcpProtocol() { string msg = GetSNIErrorMessage((int)SNINativeMethodWrapper.SniSpecialErrors.MultiSubnetFailoverWithNonTcpProtocol); return ADP.Argument(msg); } // // Read-only routing // static internal Exception ROR_FailoverNotSupportedConnString() { return ADP.Argument(Res.GetString(Res.SQLROR_FailoverNotSupported)); } static internal Exception ROR_FailoverNotSupportedServer(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_FailoverNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } static internal Exception ROR_RecursiveRoutingNotSupported(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_RecursiveRoutingNotSupported)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } static internal Exception ROR_UnexpectedRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_UnexpectedRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } static internal Exception ROR_InvalidRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_InvalidRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } static internal Exception ROR_TimeoutAfterRoutingInfo(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, null, (Res.GetString(Res.SQLROR_TimeoutAfterRoutingInfo)), "", 0)); SqlException exc = SqlException.CreateException(errors, null, internalConnection); exc._doNotReconnect = true; return exc; } // // Connection resiliency // static internal SqlException CR_ReconnectTimeout() { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(TdsEnums.TIMEOUT_EXPIRED, (byte)0x00, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.Timeout(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT)); SqlException exc = SqlException.CreateException(errors, ""); return exc; } static internal SqlException CR_ReconnectionCancelled() { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, SQLMessage.OperationCancelled(), "", 0)); SqlException exc = SqlException.CreateException(errors, ""); return exc; } static internal Exception CR_NextAttemptWillExceedQueryTimeout(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NextAttemptWillExceedQueryTimeout), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } static internal Exception CR_EncryptionChanged(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_EncryptionChanged), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } static internal SqlException CR_AllAttemptsFailed(SqlException innerException, Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.MIN_ERROR_CLASS, null, Res.GetString(Res.SQLCR_AllAttemptsFailed), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId, innerException); return exc; } static internal SqlException CR_NoCRAckAtReconnection(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_NoCRAckAtReconnection), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } static internal SqlException CR_TDSVersionNotPreserved(SqlInternalConnectionTds internalConnection) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_TDSVestionNotPreserved), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection); return exc; } static internal SqlException CR_UnrecoverableServer(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableServer), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } static internal SqlException CR_UnrecoverableClient(Guid connectionId) { SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQLCR_UnrecoverableClient), "", 0)); SqlException exc = SqlException.CreateException(errors, "", connectionId); return exc; } static internal Exception StreamWriteNotSupported() { return ADP.NotSupported(Res.GetString(Res.SQL_StreamWriteNotSupported)); } static internal Exception StreamReadNotSupported() { return ADP.NotSupported(Res.GetString(Res.SQL_StreamReadNotSupported)); } static internal Exception StreamSeekNotSupported() { return ADP.NotSupported(Res.GetString(Res.SQL_StreamSeekNotSupported)); } static internal System.Data.SqlTypes.SqlNullValueException SqlNullValue() { System.Data.SqlTypes.SqlNullValueException e = new System.Data.SqlTypes.SqlNullValueException(); return e; } static internal Exception SubclassMustOverride() { return ADP.InvalidOperation(Res.GetString(Res.SqlMisc_SubclassMustOverride)); } // ProjectK\CoreCLR specific errors static internal Exception UnsupportedKeyword(string keyword) { return ADP.NotSupported(Res.GetString(Res.SQL_UnsupportedKeyword, keyword)); } static internal Exception NetworkLibraryKeywordNotSupported() { return ADP.NotSupported(Res.GetString(Res.SQL_NetworkLibraryNotSupported)); } static internal Exception UnsupportedFeatureAndToken(SqlInternalConnectionTds internalConnection, string token) { var innerException = ADP.NotSupported(Res.GetString(Res.SQL_UnsupportedToken, token)); SqlErrorCollection errors = new SqlErrorCollection(); errors.Add(new SqlError(0, 0, TdsEnums.FATAL_ERROR_CLASS, null, Res.GetString(Res.SQL_UnsupportedFeature), "", 0)); SqlException exc = SqlException.CreateException(errors, "", internalConnection, innerException); return exc; } /// <summary> /// gets a message for SNI error (sniError must be valid, non-zero error code) /// </summary> static internal string GetSNIErrorMessage(int sniError) { Debug.Assert(sniError > 0 && sniError <= (int)SNINativeMethodWrapper.SniSpecialErrors.MaxErrorValue, "SNI error is out of range"); string errorMessageId = String.Format((IFormatProvider)null, "SNI_ERROR_{0}", sniError); return Res.GetResourceString(errorMessageId); } } sealed internal class SQLMessage { private SQLMessage() { /* prevent utility class from being instantiated*/ } // The class SQLMessage defines the error messages that are specific to the SqlDataAdapter // that are caused by a netlib error. The functions will be called and then return the // appropriate error message from the resource Framework.txt. The SqlDataAdapter will then // take the error message and then create a SqlError for the message and then place // that into a SqlException that is either thrown to the user or cached for throwing at // a later time. This class is used so that there will be compile time checking of error // messages. The resource Framework.txt will ensure proper string text based on the appropriate // locale. static internal string CultureIdError() { return Res.GetString(Res.SQL_CultureIdError); } static internal string EncryptionNotSupportedByClient() { return Res.GetString(Res.SQL_EncryptionNotSupportedByClient); } static internal string EncryptionNotSupportedByServer() { return Res.GetString(Res.SQL_EncryptionNotSupportedByServer); } static internal string OperationCancelled() { return Res.GetString(Res.SQL_OperationCancelled); } static internal string SevereError() { return Res.GetString(Res.SQL_SevereError); } static internal string SSPIInitializeError() { return Res.GetString(Res.SQL_SSPIInitializeError); } static internal string SSPIGenerateError() { return Res.GetString(Res.SQL_SSPIGenerateError); } static internal string Timeout() { return Res.GetString(Res.SQL_Timeout); } static internal string Timeout_PreLogin_Begin() { return Res.GetString(Res.SQL_Timeout_PreLogin_Begin); } static internal string Timeout_PreLogin_InitializeConnection() { return Res.GetString(Res.SQL_Timeout_PreLogin_InitializeConnection); } static internal string Timeout_PreLogin_SendHandshake() { return Res.GetString(Res.SQL_Timeout_PreLogin_SendHandshake); } static internal string Timeout_PreLogin_ConsumeHandshake() { return Res.GetString(Res.SQL_Timeout_PreLogin_ConsumeHandshake); } static internal string Timeout_Login_Begin() { return Res.GetString(Res.SQL_Timeout_Login_Begin); } static internal string Timeout_Login_ProcessConnectionAuth() { return Res.GetString(Res.SQL_Timeout_Login_ProcessConnectionAuth); } static internal string Timeout_PostLogin() { return Res.GetString(Res.SQL_Timeout_PostLogin); } static internal string Timeout_FailoverInfo() { return Res.GetString(Res.SQL_Timeout_FailoverInfo); } static internal string Timeout_RoutingDestination() { return Res.GetString(Res.SQL_Timeout_RoutingDestinationInfo); } static internal string Duration_PreLogin_Begin(long PreLoginBeginDuration) { return Res.GetString(Res.SQL_Duration_PreLogin_Begin, PreLoginBeginDuration); } static internal string Duration_PreLoginHandshake(long PreLoginBeginDuration, long PreLoginHandshakeDuration) { return Res.GetString(Res.SQL_Duration_PreLoginHandshake, PreLoginBeginDuration, PreLoginHandshakeDuration); } static internal string Duration_Login_Begin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration) { return Res.GetString(Res.SQL_Duration_Login_Begin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration); } static internal string Duration_Login_ProcessConnectionAuth(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration) { return Res.GetString(Res.SQL_Duration_Login_ProcessConnectionAuth, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration); } static internal string Duration_PostLogin(long PreLoginBeginDuration, long PreLoginHandshakeDuration, long LoginBeginDuration, long LoginAuthDuration, long PostLoginDuration) { return Res.GetString(Res.SQL_Duration_PostLogin, PreLoginBeginDuration, PreLoginHandshakeDuration, LoginBeginDuration, LoginAuthDuration, PostLoginDuration); } static internal string UserInstanceFailure() { return Res.GetString(Res.SQL_UserInstanceFailure); } static internal string PreloginError() { return Res.GetString(Res.Snix_PreLogin); } static internal string ExClientConnectionId() { return Res.GetString(Res.SQL_ExClientConnectionId); } static internal string ExErrorNumberStateClass() { return Res.GetString(Res.SQL_ExErrorNumberStateClass); } static internal string ExOriginalClientConnectionId() { return Res.GetString(Res.SQL_ExOriginalClientConnectionId); } static internal string ExRoutingDestination() { return Res.GetString(Res.SQL_ExRoutingDestination); } } /// <summary> /// This class holds helper methods to escape Microsoft SQL Server identifiers, such as table, schema, database or other names /// </summary> static internal class SqlServerEscapeHelper { /// <summary> /// Escapes the identifier with square brackets. The input has to be in unescaped form, like the parts received from MultipartIdentifier.ParseMultipartIdentifier. /// </summary> /// <param name="name">name of the identifier, in unescaped form</param> /// <returns>escapes the name with [], also escapes the last close bracket with double-bracket</returns> static internal string EscapeIdentifier(string name) { Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed"); return "[" + name.Replace("]", "]]") + "]"; } /// <summary> /// Same as above EscapeIdentifier, except that output is written into StringBuilder /// </summary> static internal void EscapeIdentifier(StringBuilder builder, string name) { Debug.Assert(builder != null, "builder cannot be null"); Debug.Assert(!string.IsNullOrEmpty(name), "null or empty identifiers are not allowed"); builder.Append("["); builder.Append(name.Replace("]", "]]")); builder.Append("]"); } /// <summary> /// Escape a string to be used inside TSQL literal, such as N'somename' or 'somename' /// </summary> static internal string EscapeStringAsLiteral(string input) { Debug.Assert(input != null, "input string cannot be null"); return input.Replace("'", "''"); } } }//namespace
// 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.Text; using System.Diagnostics; using System.Runtime.InteropServices; using Internal.Cryptography; using static Interop; namespace Internal.NativeCrypto { internal static partial class BCryptNative { /// <summary> /// Well known algorithm names /// </summary> internal static class AlgorithmName { public const string ECDHP256 = "ECDH_P256"; // BCRYPT_ECDH_P256_ALGORITHM public const string ECDHP384 = "ECDH_P384"; // BCRYPT_ECDH_P384_ALGORITHM public const string ECDHP521 = "ECDH_P521"; // BCRYPT_ECDH_P521_ALGORITHM public const string ECDsaP256 = "ECDSA_P256"; // BCRYPT_ECDSA_P256_ALGORITHM public const string ECDsaP384 = "ECDSA_P384"; // BCRYPT_ECDSA_P384_ALGORITHM public const string ECDsaP521 = "ECDSA_P521"; // BCRYPT_ECDSA_P521_ALGORITHM public const string MD5 = "MD5"; // BCRYPT_MD5_ALGORITHM public const string Sha1 = "SHA1"; // BCRYPT_SHA1_ALGORITHM public const string Sha256 = "SHA256"; // BCRYPT_SHA256_ALGORITHM public const string Sha384 = "SHA384"; // BCRYPT_SHA384_ALGORITHM public const string Sha512 = "SHA512"; // BCRYPT_SHA512_ALGORITHM } /// <summary> /// Magic numbers identifying blob types /// </summary> internal enum KeyBlobMagicNumber { ECDHPublicP256 = 0x314B4345, // BCRYPT_ECDH_PUBLIC_P256_MAGIC ECDHPublicP384 = 0x334B4345, // BCRYPT_ECDH_PUBLIC_P384_MAGIC ECDHPublicP521 = 0x354B4345, // BCRYPT_ECDH_PUBLIC_P521_MAGIC ECDsaPublicP256 = 0x31534345, // BCRYPT_ECDSA_PUBLIC_P256_MAGIC ECDsaPublicP384 = 0x33534345, // BCRYPT_ECDSA_PUBLIC_P384_MAGIC ECDsaPublicP521 = 0x35534345 // BCRYPT_ECDSA_PUBLIC_P521_MAGIC } internal static class KeyDerivationFunction { public const string Hash = "HASH"; // BCRYPT_KDF_HASH public const string Hmac = "HMAC"; // BCRYPT_KDF_HMAC public const string Tls = "TLS_PRF"; // BCRYPT_KDF_TLS_PRF } } // // Interop layer around Windows CNG api. // internal static partial class Cng { [Flags] public enum OpenAlgorithmProviderFlags : int { NONE = 0x00000000, BCRYPT_ALG_HANDLE_HMAC_FLAG = 0x00000008, } public const string BCRYPT_3DES_ALGORITHM = "3DES"; public const string BCRYPT_AES_ALGORITHM = "AES"; public const string BCRYPT_CHAIN_MODE_CBC = "ChainingModeCBC"; public const string BCRYPT_CHAIN_MODE_ECB = "ChainingModeECB"; public static SafeAlgorithmHandle BCryptOpenAlgorithmProvider(String pszAlgId, String pszImplementation, OpenAlgorithmProviderFlags dwFlags) { SafeAlgorithmHandle hAlgorithm = null; NTSTATUS ntStatus = Interop.BCryptOpenAlgorithmProvider(out hAlgorithm, pszAlgId, pszImplementation, (int)dwFlags); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hAlgorithm; } public static SafeKeyHandle BCryptImportKey(this SafeAlgorithmHandle hAlg, byte[] key) { unsafe { const String BCRYPT_KEY_DATA_BLOB = "KeyDataBlob"; int keySize = key.Length; int blobSize = sizeof(BCRYPT_KEY_DATA_BLOB_HEADER) + keySize; byte[] blob = new byte[blobSize]; fixed (byte* pbBlob = blob) { BCRYPT_KEY_DATA_BLOB_HEADER* pBlob = (BCRYPT_KEY_DATA_BLOB_HEADER*)pbBlob; pBlob->dwMagic = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_MAGIC; pBlob->dwVersion = BCRYPT_KEY_DATA_BLOB_HEADER.BCRYPT_KEY_DATA_BLOB_VERSION1; pBlob->cbKeyData = (uint)keySize; } Buffer.BlockCopy(key, 0, blob, sizeof(BCRYPT_KEY_DATA_BLOB_HEADER), keySize); SafeKeyHandle hKey; NTSTATUS ntStatus = Interop.BCryptImportKey(hAlg, IntPtr.Zero, BCRYPT_KEY_DATA_BLOB, out hKey, IntPtr.Zero, 0, blob, blobSize, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return hKey; } } [StructLayout(LayoutKind.Sequential)] private struct BCRYPT_KEY_DATA_BLOB_HEADER { public UInt32 dwMagic; public UInt32 dwVersion; public UInt32 cbKeyData; public const UInt32 BCRYPT_KEY_DATA_BLOB_MAGIC = 0x4d42444b; public const UInt32 BCRYPT_KEY_DATA_BLOB_VERSION1 = 0x1; } public static void SetCipherMode(this SafeAlgorithmHandle hAlg, string cipherMode) { NTSTATUS ntStatus = Interop.BCryptSetProperty(hAlg, "ChainingMode", cipherMode, (cipherMode.Length + 1) * 2, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) { throw CreateCryptographicException(ntStatus); } } // Note: input and output are allowed to be the same buffer. BCryptEncrypt will correctly do the encryption in place according to CNG documentation. public static int BCryptEncrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount) { Debug.Assert(input != null); Debug.Assert(inputOffset >= 0); Debug.Assert(inputCount >= 0); Debug.Assert(inputCount <= input.Length - inputOffset); Debug.Assert(output != null); Debug.Assert(outputOffset >= 0); Debug.Assert(outputCount >= 0); Debug.Assert(outputCount <= output.Length - outputOffset); unsafe { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS ntStatus = Interop.BCryptEncrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return cbResult; } } } } // Note: input and output are allowed to be the same buffer. BCryptDecrypt will correctly do the decryption in place according to CNG documentation. public static int BCryptDecrypt(this SafeKeyHandle hKey, byte[] input, int inputOffset, int inputCount, byte[] iv, byte[] output, int outputOffset, int outputCount) { Debug.Assert(input != null); Debug.Assert(inputOffset >= 0); Debug.Assert(inputCount >= 0); Debug.Assert(inputCount <= input.Length - inputOffset); Debug.Assert(output != null); Debug.Assert(outputOffset >= 0); Debug.Assert(outputCount >= 0); Debug.Assert(outputCount <= output.Length - outputOffset); unsafe { fixed (byte* pbInput = input) { fixed (byte* pbOutput = output) { int cbResult; NTSTATUS ntStatus = Interop.BCryptDecrypt(hKey, pbInput + inputOffset, inputCount, IntPtr.Zero, iv, iv == null ? 0 : iv.Length, pbOutput + outputOffset, outputCount, out cbResult, 0); if (ntStatus != NTSTATUS.STATUS_SUCCESS) throw CreateCryptographicException(ntStatus); return cbResult; } } } } private static class BCryptGetPropertyStrings { public const String BCRYPT_HASH_LENGTH = "HashDigestLength"; } public static String CryptFormatObject(String oidValue, byte[] rawData, bool multiLine) { const int X509_ASN_ENCODING = 0x00000001; const int CRYPT_FORMAT_STR_MULTI_LINE = 0x00000001; int dwFormatStrType = multiLine ? CRYPT_FORMAT_STR_MULTI_LINE : 0; int cbFormat = 0; if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, null, ref cbFormat)) return null; StringBuilder sb = new StringBuilder((cbFormat + 1) / 2); if (!Interop.CryptFormatObject(X509_ASN_ENCODING, 0, dwFormatStrType, IntPtr.Zero, oidValue, rawData, rawData.Length, sb, ref cbFormat)) return null; return sb.ToString(); } private enum NTSTATUS : uint { STATUS_SUCCESS = 0x0, STATUS_NOT_FOUND = 0xc0000225, STATUS_INVALID_PARAMETER = 0xc000000d, STATUS_NO_MEMORY = 0xc0000017, } private static Exception CreateCryptographicException(NTSTATUS ntStatus) { int hr = ((int)ntStatus) | 0x01000000; return hr.ToCryptographicException(); } } internal static partial class Cng { private static class Interop { [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptOpenAlgorithmProvider(out SafeAlgorithmHandle phAlgorithm, String pszAlgId, String pszImplementation, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptSetProperty(SafeAlgorithmHandle hObject, String pszProperty, String pbInput, int cbInput, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] public static extern NTSTATUS BCryptImportKey(SafeAlgorithmHandle hAlgorithm, IntPtr hImportKey, String pszBlobType, out SafeKeyHandle hKey, IntPtr pbKeyObject, int cbKeyObject, byte[] pbInput, int cbInput, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptEncrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In,Out] byte [] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); [DllImport(Libraries.BCrypt, CharSet = CharSet.Unicode)] public static extern unsafe NTSTATUS BCryptDecrypt(SafeKeyHandle hKey, byte* pbInput, int cbInput, IntPtr paddingInfo, [In, Out] byte[] pbIV, int cbIV, byte* pbOutput, int cbOutput, out int cbResult, int dwFlags); [DllImport(Libraries.Crypt32, CharSet = CharSet.Ansi, SetLastError = true, BestFitMapping = false)] public static extern bool CryptFormatObject( [In] int dwCertEncodingType, // only valid value is X509_ASN_ENCODING [In] int dwFormatType, // unused - pass 0. [In] int dwFormatStrType, // select multiline [In] IntPtr pFormatStruct, // unused - pass IntPtr.Zero [MarshalAs(UnmanagedType.LPStr)] [In] String lpszStructType, // OID value [In] byte[] pbEncoded, // Data to be formatted [In] int cbEncoded, // Length of data to be formatted [MarshalAs(UnmanagedType.LPWStr)] [Out] StringBuilder pbFormat, // Receives formatted string. [In, Out] ref int pcbFormat); // Sends/receives length of formatted String. } } internal abstract class SafeBCryptHandle : SafeHandle { public SafeBCryptHandle() : base(IntPtr.Zero, true) { } public sealed override bool IsInvalid { get { return handle == IntPtr.Zero; } } } internal sealed class SafeAlgorithmHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptCloseAlgorithmProvider(handle, 0); return ntStatus == 0; } [DllImport(Libraries.BCrypt)] private static extern uint BCryptCloseAlgorithmProvider(IntPtr hAlgorithm, int dwFlags); } internal sealed class SafeHashHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptDestroyHash(handle); return ntStatus == 0; } [DllImport(Libraries.BCrypt)] private static extern uint BCryptDestroyHash(IntPtr hHash); } internal sealed class SafeKeyHandle : SafeBCryptHandle { protected sealed override bool ReleaseHandle() { uint ntStatus = BCryptDestroyKey(handle); return ntStatus == 0; } [DllImport(Libraries.BCrypt)] private static extern uint BCryptDestroyKey(IntPtr hKey); } }
using System; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Drawing; using System.IO; #if MACOS using MonoMac.CoreGraphics; using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreText; using MonoMac.ImageIO; #else using MonoTouch.CoreGraphics; using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreText; using MonoTouch.ImageIO; #endif namespace Cocos2D { internal static partial class CCLabelUtilities { static CCVerticalTextAlignment vertical; static CCTextAlignment horizontal; // Used for debuggin purposes internal static void SaveToFile (string fileName, CGBitmapContext bitmap) { if (bitmap == null) throw new ObjectDisposedException ("cgimage"); // With MonoTouch we can use UTType from CoreMobileServices but since // MonoMac does not have that yet (or at least can not find it) I will // use the string version of those for now. I did not want to add another // #if #else in here. // for now we will just default this to png var typeIdentifier = "public.png"; // * NOTE * we only support one image for right now. //NSMutableData imgData = new NSMutableData(); NSUrl url = NSUrl.FromFilename (fileName); // Create an image destination that saves into the imgData CGImageDestination dest = CGImageDestination.FromUrl (url, typeIdentifier, 1); // Add an image to the destination dest.AddImage(bitmap.GetImage(), null); // Finish the export bool success = dest.Close (); // if (success == false) // Console.WriteLine("did not work"); // else // Console.WriteLine("did work: " + path); dest.Dispose(); dest = null; } internal static IntPtr bitmapBlock; internal static CCSize imageSize = CCSize.Zero; internal static CGBitmapContext CreateBitmap (int width, int height) //, PixelFormat format) { int bitsPerComponent, bytesPerRow; CGColorSpace colorSpace; CGBitmapFlags bitmapInfo; // bool premultiplied = false; int bitsPerPixel = 0; // Don't forget to set the Image width and height for size. imageSize.Width = width; imageSize.Height = height; colorSpace = CGColorSpace.CreateDeviceRGB (); bitsPerComponent = 8; bitsPerPixel = 32; bitmapInfo = CGBitmapFlags.PremultipliedLast; bytesPerRow = width * bitsPerPixel/bitsPerComponent; int size = bytesPerRow * height; bitmapBlock = Marshal.AllocHGlobal (size); var bitmapContext = new CGBitmapContext (bitmapBlock, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); // This works for now but we need to look into initializing the memory area itself bitmapContext.ClearRect (new RectangleF (0,0,width,height)); return bitmapContext; } internal static CGImage GetImage (this CGBitmapContext bitmapContext) { var provider = new CGDataProvider (bitmapContext.Data, bitmapContext.BytesPerRow * bitmapContext.Height, true); var NativeCGImage = new CGImage (bitmapContext.Width, bitmapContext.Height, bitmapContext.BitsPerComponent, bitmapContext.BitsPerPixel, bitmapContext.BytesPerRow, bitmapContext.ColorSpace, (CGBitmapFlags)bitmapContext.BitmapInfo, provider, null, false, CGColorRenderingIntent.Default); return NativeCGImage; } internal static void NativeDrawString (CGBitmapContext bitmapContext, string s, CTFont font, CCColor4B brush, RectangleF layoutRectangle) { if (font == null) throw new ArgumentNullException ("font"); if (s == null || s.Length == 0) return; bitmapContext.ConcatCTM (bitmapContext.GetCTM().Invert()); // This is not needed here since the color is set in the attributed string. //bitmapContext.SetFillColor(brush.R/255f, brush.G/255f, brush.B/255f, brush.A/255f); // I think we only Fill the text with no Stroke surrounding //bitmapContext.SetTextDrawingMode(CGTextDrawingMode.Fill); var attributedString = buildAttributedString(s, font, brush); // Work out the geometry RectangleF insetBounds = layoutRectangle; PointF textPosition = new PointF(insetBounds.X, insetBounds.Y); float boundsWidth = insetBounds.Width; // Calculate the lines int start = 0; int length = attributedString.Length; var typesetter = new CTTypesetter(attributedString); float baselineOffset = 0; // First we need to calculate the offset for Vertical Alignment if we // are using anything but Top if (vertical != CCVerticalTextAlignment.Top) { while (start < length) { int count = typesetter.SuggestLineBreak (start, boundsWidth); var line = typesetter.GetLine (new NSRange(start, count)); // Create and initialize some values from the bounds. float ascent; float descent; float leading; line.GetTypographicBounds (out ascent, out descent, out leading); baselineOffset += (float)Math.Ceiling (ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior line.Dispose (); start += count; } } start = 0; while (start < length && textPosition.Y < insetBounds.Bottom) { // Now we ask the typesetter to break off a line for us. // This also will take into account line feeds embedded in the text. // Example: "This is text \n with a line feed embedded inside it" int count = typesetter.SuggestLineBreak(start, boundsWidth); var line = typesetter.GetLine(new NSRange(start, count)); // Create and initialize some values from the bounds. float ascent; float descent; float leading; line.GetTypographicBounds(out ascent, out descent, out leading); // Calculate the string format if need be var penFlushness = 0.0f; if (horizontal == CCTextAlignment.Right) penFlushness = (float)line.GetPenOffsetForFlush(1.0f, boundsWidth); else if (horizontal == CCTextAlignment.Center) penFlushness = (float)line.GetPenOffsetForFlush(0.5f, boundsWidth); // initialize our Text Matrix or we could get trash in here var textMatrix = CGAffineTransform.MakeIdentity(); if (vertical == CCVerticalTextAlignment.Top) textMatrix.Translate(penFlushness, insetBounds.Height - textPosition.Y -(float)Math.Floor(ascent - 1)); if (vertical == CCVerticalTextAlignment.Center) textMatrix.Translate(penFlushness, ((insetBounds.Height / 2) + (baselineOffset / 2)) - textPosition.Y -(float)Math.Floor(ascent - 1)); if (vertical == CCVerticalTextAlignment.Bottom) textMatrix.Translate(penFlushness, baselineOffset - textPosition.Y -(float)Math.Floor(ascent - 1)); // Set our matrix bitmapContext.TextMatrix = textMatrix; // and draw the line line.Draw(bitmapContext); // Move the index beyond the line break. start += count; textPosition.Y += (float)Math.Ceiling(ascent + descent + leading + 1); // +1 matches best to CTFramesetter's behavior line.Dispose(); } } [StructLayout(LayoutKind.Sequential)] internal struct ABCFloat { /// <summary>Specifies the A spacing of the character. The A spacing is the distance to add to the current /// position before drawing the character glyph.</summary> public float abcfA; /// <summary>Specifies the B spacing of the character. The B spacing is the width of the drawn portion of /// the character glyph.</summary> public float abcfB; /// <summary>Specifies the C spacing of the character. The C spacing is the distance to add to the current /// position to provide white space to the right of the character glyph.</summary> public float abcfC; } // This only handles one character for right now internal static void GetCharABCWidthsFloat (char characters, CTFont font, out ABCFloat[] abc) { var atts = buildAttributedString(characters.ToString(), font); // for now just a line not sure if this is going to work CTLine line = new CTLine(atts); float ascent; float descent; float leading; abc = new ABCFloat[1]; abc[0].abcfB = (float)line.GetTypographicBounds(out ascent, out descent, out leading); abc [0].abcfB += leading; } internal static CCSize MeasureString (string textg, CTFont font, CCRect rect) { var atts = buildAttributedString(textg, font); // for now just a line not sure if this is going to work CTLine line = new CTLine(atts); // Create and initialize some values from the bounds. float ascent; float descent; float leading; double lineWidth = line.GetTypographicBounds(out ascent, out descent, out leading); var measure = new CCSize((float)lineWidth + leading, ascent + descent); return measure; } internal static CCSize MeasureString (string textg, CTFont font, CCSize layoutArea) { return MeasureString (textg, font, new CCRect (0, 0, layoutArea.Width, layoutArea.Height)); } internal static CCSize MeasureString (string textg, CTFont font) { return MeasureString (textg, font, CCSize.Zero); } private static NSMutableAttributedString buildAttributedString(string text, CTFont font, CCColor4B? fontColor=null) { // Create a new attributed string definition var ctAttributes = new CTStringAttributes (); // Font attribute ctAttributes.Font = font; // -- end font if (fontColor.HasValue) { // Font color var fc = fontColor.Value; var cgColor = new CGColor(fc.R / 255f, fc.G / 255f, fc.B / 255f, fc.A / 255f); ctAttributes.ForegroundColor = cgColor; ctAttributes.ForegroundColorFromContext = false; // -- end font Color } if (underLine) { // Underline #if MACOS int single = (int)MonoMac.AppKit.NSUnderlineStyle.Single; int solid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid; var attss = single | solid; ctAttributes.UnderlineStyleValue = attss; #else ctAttributes.UnderlineStyleValue = 1; #endif // --- end underline } if (strikeThrough) { // StrikeThrough // NSColor bcolor = NSColor.Blue; // NSObject bcolorObject = new NSObject(bcolor.Handle); // attsDic.Add(NSAttributedString.StrikethroughColorAttributeName, bcolorObject); // #if MACOS // int stsingle = (int)MonoMac.AppKit.NSUnderlineStyle.Single; // int stsolid = (int)MonoMac.AppKit.NSUnderlinePattern.Solid; // var stattss = stsingle | stsolid; // var stunderlineObject = NSNumber.FromInt32(stattss); // #else // var stunderlineObject = NSNumber.FromInt32 (1); // #endif // // attsDic.Add(StrikethroughStyleAttributeName, stunderlineObject); // --- end underline } // Text alignment var alignment = CTTextAlignment.Left; var alignmentSettings = new CTParagraphStyleSettings(); alignmentSettings.Alignment = alignment; var paragraphStyle = new CTParagraphStyle(alignmentSettings); ctAttributes.ParagraphStyle = paragraphStyle; // end text alignment NSMutableAttributedString atts = new NSMutableAttributedString(text,ctAttributes.Dictionary); return atts; } const byte DefaultCharSet = 1; //static CTFont nativeFont; static bool underLine = false; static bool strikeThrough = false; static float dpiScale = 96f / 72f; static internal CTFont CreateFont (string familyName, float emSize) { return CreateFont (familyName, emSize, FontStyle.Regular, DefaultCharSet, false); } static internal CTFont CreateFont (string familyName, float emSize, FontStyle style) { return CreateFont (familyName, emSize, style, DefaultCharSet, false); } static internal CTFont CreateFont (string familyName, float emSize, FontStyle style, byte gdiCharSet) { return CreateFont (familyName, emSize, style, gdiCharSet, false); } static internal CTFont CreateFont (string familyName, float emSize, FontStyle style, byte gdiCharSet, bool gdiVerticalFont ) { if (emSize <= 0) throw new ArgumentException("emSize is less than or equal to 0, evaluates to infinity, or is not a valid number.","emSize"); CTFont nativeFont; // convert to 96 Dpi to be consistent with Windows var dpiSize = emSize * dpiScale; var ext = System.IO.Path.GetExtension(familyName); if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf") { var fontName = familyName.Substring (0, familyName.Length - ext.Length); var path = CCApplication.SharedApplication.Game.Content.RootDirectory + Path.DirectorySeparatorChar + fontName; var pathForResource = NSBundle.MainBundle.PathForResource (path, ext.Substring(1)); try { var dataProvider = new CGDataProvider (pathForResource); var cgFont = CGFont.CreateFromProvider (dataProvider); try { nativeFont = new CTFont(cgFont, dpiSize, null); } catch { nativeFont = new CTFont("Helvetica",dpiSize); } } catch (Exception) { try { nativeFont = new CTFont(Path.GetFileNameWithoutExtension(familyName),dpiSize); } catch { nativeFont = new CTFont("Helvetica",dpiSize); } CCLog.Log (string.Format ("Could not load font: {0} so will use default {1}.", familyName, nativeFont.DisplayName)); } } else { try { nativeFont = new CTFont(familyName,dpiSize); } catch { nativeFont = new CTFont("Helvetica",dpiSize); } } CTFontSymbolicTraits tMask = CTFontSymbolicTraits.None; if ((style & FontStyle.Bold) == FontStyle.Bold) tMask |= CTFontSymbolicTraits.Bold; if ((style & FontStyle.Italic) == FontStyle.Italic) tMask |= CTFontSymbolicTraits.Italic; strikeThrough = (style & FontStyle.Strikeout) == FontStyle.Strikeout; underLine = (style & FontStyle.Underline) == FontStyle.Underline; var nativeFont2 = nativeFont.WithSymbolicTraits(dpiSize,tMask,tMask); if (nativeFont2 != null) nativeFont = nativeFont2; return nativeFont; } internal static float GetHeight(this CTFont font) { float lineHeight = 0; if (font == null) return 0; // Get the ascent from the font, already scaled for the font's size lineHeight += font.AscentMetric; // Get the descent from the font, already scaled for the font's size lineHeight += font.DescentMetric; // Get the leading from the font, already scaled for the font's size //lineHeight += font.LeadingMetric; return lineHeight; } } } namespace Cocos2D { [Flags] internal enum FontStyle { Regular = 0, Bold = 1, Italic = 2, Underline = 4, Strikeout = 8 } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.Collections; using System.IO; using NUnit.Framework; using NPOI.POIFS.FileSystem; using NPOI.Util; using NPOI.POIFS.Storage; using NPOI.POIFS.Properties; using TestCases.POIFS.FileSystem; namespace TestCases.POIFS.FileSystem { /** * Class to Test POIFSDocument functionality * * @author Marc Johnson */ [TestFixture] public class TestDocument { /** * Constructor TestDocument * * @param name */ public TestDocument() { } /** * Integration Test -- really about all we can do * * @exception IOException */ [Test] public void TestOPOIFSDocument() { // Verify correct number of blocks Get Created for document // that is exact multituple of block size OPOIFSDocument document; byte[] array = new byte[4096]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new OPOIFSDocument("foo", new SlowInputStream(new MemoryStream(array))); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is not an exact multiple of block size array = new byte[4097]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new OPOIFSDocument("bar", new MemoryStream(array)); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is small array = new byte[4095]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new OPOIFSDocument("_bar", new MemoryStream(array)); checkDocument(document, array); // Verify correct number of blocks Get Created for document // that is rather small array = new byte[199]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new OPOIFSDocument("_bar2", new MemoryStream(array)); checkDocument(document, array); // Verify that output is correct array = new byte[4097]; for (int j = 0; j < array.Length; j++) { array[j] = (byte)j; } document = new OPOIFSDocument("foobar", new MemoryStream(array)); checkDocument(document, array); document.StartBlock=0x12345678; // what a big file!! DocumentProperty property = document.DocumentProperty; MemoryStream stream = new MemoryStream(); property.WriteData(stream); byte[] output = stream.ToArray(); byte[] array2 = { ( byte ) 'f', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'o', ( byte ) 0, ( byte ) 'b', ( byte ) 0, ( byte ) 'a', ( byte ) 0, ( byte ) 'r', ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 14, ( byte ) 0, ( byte ) 2, ( byte ) 1, unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), unchecked(( byte ) -1), ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0x78, ( byte ) 0x56, ( byte ) 0x34, ( byte ) 0x12, ( byte ) 1, ( byte ) 16, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0, ( byte ) 0 }; Assert.AreEqual(array2.Length, output.Length); for (int j = 0; j < output.Length; j++) { Assert.AreEqual(array2[j], output[j], "Checking property offset " + j); } } private OPOIFSDocument makeCopy(OPOIFSDocument document, byte[] input, byte[] data) { OPOIFSDocument copy = null; if (input.Length >= 4096) { RawDataBlock[] blocks = new RawDataBlock[(input.Length + 511) / 512]; MemoryStream stream = new MemoryStream(data); int index = 0; while (true) { RawDataBlock block = new RawDataBlock(stream); if (block.EOF) { break; } blocks[index++] = block; } copy = new OPOIFSDocument("test" + input.Length, blocks, input.Length); } else { copy = new OPOIFSDocument( "test" + input.Length, (SmallDocumentBlock[])document.SmallBlocks, input.Length); } return copy; } private void checkDocument(OPOIFSDocument document, byte[] input) { int big_blocks = 0; int small_blocks = 0; int total_output = 0; if (input.Length >= 4096) { big_blocks = (input.Length + 511) / 512; total_output = big_blocks * 512; } else { small_blocks = (input.Length + 63) / 64; total_output = 0; } checkValues( big_blocks, small_blocks, total_output, makeCopy( document, input, checkValues( big_blocks, small_blocks, total_output, document, input)), input); } private byte[] checkValues(int big_blocks, int small_blocks, int total_output, OPOIFSDocument document, byte[] input) { Assert.AreEqual(document, document.DocumentProperty.Document); int increment = (int)Math.Sqrt(input.Length); for (int j = 1; j <= input.Length; j += increment) { byte[] buffer = new byte[j]; int offset = 0; for (int k = 0; k < (input.Length / j); k++) { document.Read(buffer, offset); for (int n = 0; n < buffer.Length; n++) { Assert.AreEqual(input[(k * j) + n], buffer[n] , "checking byte " + (k * j) + n); } offset += j; } } Assert.AreEqual(big_blocks, document.CountBlocks); Assert.AreEqual(small_blocks, document.SmallBlocks.Length); MemoryStream stream = new MemoryStream(); document.WriteBlocks(stream); byte[] output = stream.ToArray(); Assert.AreEqual(total_output, output.Length); int limit = Math.Min(total_output, input.Length); for (int j = 0; j < limit; j++) { Assert.AreEqual(input[j], output[j], "Checking document offset " + j); } for (int j = limit; j < output.Length; j++) { Assert.AreEqual(unchecked((byte)-1), output[j], "Checking document offset " + j); } return output; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // All code in this file requires .NET Framework 2.0 or later. #if !NET_1_1 && !NET_1_0 [assembly: Elmah.Scc("$Id: SqlCompactErrorLog.cs 776 2011-01-12 21:09:24Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Data; using System.Data.SqlServerCe; using System.IO; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An Elmah <see cref="ErrorLog"/> implementation that uses SQL Server Compact 4 as its backing store. /// </summary> public class SqlCompactErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SqlCompactErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SqlCompactErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); string connectionString = ConnectionStringHelper.GetConnectionString(config); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new Elmah.ApplicationException("Connection string is missing for the SQL Server Compact error log."); _connectionString = connectionString; InitializeDatabase(); if (config.Contains("applicationName") && !string.IsNullOrEmpty(config["applicationName"].ToString())) { ApplicationName = config["applicationName"].ToString(); } } /// <summary> /// Initializes a new instance of the <see cref="SqlCompactErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SqlCompactErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = connectionString; InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { string connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); string dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; using (SqlCeEngine engine = new SqlCeEngine(ConnectionString)) { engine.CreateDatabase(); } const string sql1 = @" CREATE TABLE ELMAH_Error ( [ErrorId] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY DEFAULT newid(), [Application] NVARCHAR(60) NOT NULL, [Host] NVARCHAR(50) NOT NULL, [Type] NVARCHAR(100) NOT NULL, [Source] NVARCHAR(60) NOT NULL, [Message] NVARCHAR(500) NOT NULL, [User] NVARCHAR(50) NOT NULL, [StatusCode] INT NOT NULL, [TimeUtc] DATETIME NOT NULL, [Sequence] INT IDENTITY (1, 1) NOT NULL, [AllXml] NTEXT NOT NULL )"; const string sql2 = @" CREATE NONCLUSTERED INDEX [IX_Error_App_Time_Seq] ON [ELMAH_Error] ( [Application] ASC, [TimeUtc] DESC, [Sequence] DESC )"; using (SqlCeConnection conn = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand cmd = new SqlCeCommand()) { conn.Open(); cmd.Connection = conn; cmd.CommandText = sql1; cmd.ExecuteNonQuery(); cmd.CommandText = sql2; cmd.ExecuteNonQuery(); } } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQL Server Compact 4 Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); string errorXml = ErrorXml.EncodeString(error); Guid id = Guid.NewGuid(); const string query = @" INSERT INTO ELMAH_Error ( [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc], [AllXml] ) VALUES ( @ErrorId, @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml);"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(query, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = id; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; parameters.Add("@Host", SqlDbType.NVarChar, 30).Value = error.HostName; parameters.Add("@Type", SqlDbType.NVarChar, 100).Value = error.Type; parameters.Add("@Source", SqlDbType.NVarChar, 60).Value = error.Source; parameters.Add("@Message", SqlDbType.NVarChar, 500).Value = error.Message; parameters.Add("@User", SqlDbType.NVarChar, 50).Value = error.User; parameters.Add("@StatusCode", SqlDbType.Int).Value = error.StatusCode; parameters.Add("@TimeUtc", SqlDbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", SqlDbType.NText).Value = errorXml; command.Connection = connection; connection.Open(); command.ExecuteNonQuery(); return id.ToString(); } } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> /// public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT [ErrorId], [Application], [Host], [Type], [Source], [Message], [User], [StatusCode], [TimeUtc] FROM [ELMAH_Error] WHERE [Application] = @Application ORDER BY [TimeUtc] DESC, [Sequence] DESC OFFSET @PageSize * @PageIndex ROWS FETCH NEXT @PageSize ROWS ONLY; "; const string getCount = @" SELECT COUNT(*) FROM [ELMAH_Error]"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { connection.Open(); using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { SqlCeParameterCollection parameters = command.Parameters; parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex; parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize; parameters.Add("@Application", SqlDbType.NVarChar, 60).Value = ApplicationName; using (SqlCeDataReader reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { string id = reader["ErrorId"].ToString(); Elmah.Error error = new Elmah.Error(); error.ApplicationName = reader["Application"].ToString(); error.HostName = reader["Host"].ToString(); error.Type = reader["Type"].ToString(); error.Source = reader["Source"].ToString(); error.Message = reader["Message"].ToString(); error.User = reader["User"].ToString(); error.StatusCode = Convert.ToInt32(reader["StatusCode"]); error.Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime(); errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } } } using (SqlCeCommand command = new SqlCeCommand(getCount, connection)) { return (int)command.ExecuteScalar(); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); Guid errorGuid; try { errorGuid = new Guid(id); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT [AllXml] FROM [ELMAH_Error] WHERE [ErrorId] = @ErrorId"; using (SqlCeConnection connection = new SqlCeConnection(ConnectionString)) { using (SqlCeCommand command = new SqlCeCommand(sql, connection)) { command.Parameters.Add("@ErrorId", SqlDbType.UniqueIdentifier).Value = errorGuid; connection.Open(); string errorXml = (string)command.ExecuteScalar(); if (errorXml == null) return null; Error error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } } } #endif // !NET_1_1 && !NET_1_0
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Management.VirtualNetworks; using Microsoft.WindowsAzure.Management.VirtualNetworks.Models; namespace Microsoft.WindowsAzure.Management.VirtualNetworks { public static partial class ReservedIPOperationsExtensions { /// <summary> /// Preview Only. The Create Reserved IP operation creates a reserved /// IP from your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static VirtualNetworkOperationStatusResponse BeginCreating(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { try { return operations.BeginCreatingAsync(parameters).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// Preview Only. The Create Reserved IP operation creates a reserved /// IP from your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<VirtualNetworkOperationStatusResponse> BeginCreatingAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.BeginCreatingAsync(parameters, CancellationToken.None); } /// <summary> /// Preview Only. The Delete Reserved IP operation removes a reserved /// IP from your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse BeginDeleting(this IReservedIPOperations operations, string ipName) { try { return operations.BeginDeletingAsync(ipName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// Preview Only. The Delete Reserved IP operation removes a reserved /// IP from your the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <returns> /// A standard storage response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> BeginDeletingAsync(this IReservedIPOperations operations, string ipName) { return operations.BeginDeletingAsync(ipName, CancellationToken.None); } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static VirtualNetworkOperationStatusResponse Create(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { try { return operations.CreateAsync(parameters).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Create Reserved IP operation creates a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Image operation. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<VirtualNetworkOperationStatusResponse> CreateAsync(this IReservedIPOperations operations, NetworkReservedIPCreateParameters parameters) { return operations.CreateAsync(parameters, CancellationToken.None); } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static VirtualNetworkOperationStatusResponse Delete(this IReservedIPOperations operations, string ipName) { try { return operations.DeleteAsync(ipName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// The Delete Reserved IP operation removes a reserved IP from your /// the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public static Task<VirtualNetworkOperationStatusResponse> DeleteAsync(this IReservedIPOperations operations, string ipName) { return operations.DeleteAsync(ipName, CancellationToken.None); } /// <summary> /// Preview Only. The Get Reserved IP operation retrieves the details /// for virtual IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP to retrieve. /// </param> /// <returns> /// Preview Only. A reserved IP associated with your subscription. /// </returns> public static NetworkReservedIPGetResponse Get(this IReservedIPOperations operations, string ipName) { try { return operations.GetAsync(ipName).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// Preview Only. The Get Reserved IP operation retrieves the details /// for virtual IP reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <param name='ipName'> /// The name of the reserved IP to retrieve. /// </param> /// <returns> /// Preview Only. A reserved IP associated with your subscription. /// </returns> public static Task<NetworkReservedIPGetResponse> GetAsync(this IReservedIPOperations operations, string ipName) { return operations.GetAsync(ipName, CancellationToken.None); } /// <summary> /// Preview Only. The List Reserved IP operation retrieves the virtual /// IPs reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <returns> /// Preview Only. The response structure for the Server List operation /// </returns> public static NetworkReservedIPListResponse List(this IReservedIPOperations operations) { try { return operations.ListAsync().Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) { throw; } else { throw ex.InnerException; } } } /// <summary> /// Preview Only. The List Reserved IP operation retrieves the virtual /// IPs reserved for the subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.Management.VirtualNetworks.IReservedIPOperations. /// </param> /// <returns> /// Preview Only. The response structure for the Server List operation /// </returns> public static Task<NetworkReservedIPListResponse> ListAsync(this IReservedIPOperations operations) { return operations.ListAsync(CancellationToken.None); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Configuration.GenericEnumConverterTest.cs - Unit tests // for System.Configuration.GenericEnumConverter. // // Author: // Chris Toshok <[email protected]> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Configuration; using Xunit; namespace MonoTests.System.Configuration { public class GenericEnumConverterTest { enum FooEnum { Foo = 1, Bar = 2 } [Fact] public void Ctor_Null() { Assert.Throws<ArgumentNullException>(() => new GenericEnumConverter(null)); } [Fact] public void Ctor_TypeError() { GenericEnumConverter cv = new GenericEnumConverter(typeof(object)); } [Fact] public void CanConvertFrom() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.True(cv.CanConvertFrom(null, typeof(string)), "A1"); Assert.False(cv.CanConvertFrom(null, typeof(TimeSpan)), "A2"); Assert.False(cv.CanConvertFrom(null, typeof(int)), "A3"); Assert.False(cv.CanConvertFrom(null, typeof(object)), "A4"); } [Fact] public void CanConvertTo() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.True(cv.CanConvertTo(null, typeof(string)), "A1"); Assert.False(cv.CanConvertTo(null, typeof(TimeSpan)), "A2"); Assert.False(cv.CanConvertTo(null, typeof(int)), "A3"); Assert.False(cv.CanConvertTo(null, typeof(object)), "A4"); } [Fact] public void ConvertFrom() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.Equal(FooEnum.Foo, cv.ConvertFrom(null, null, "Foo")); Assert.Equal(FooEnum.Bar, cv.ConvertFrom(null, null, "Bar")); } [Fact] public void ConvertFrom_Case() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); AssertExtensions.Throws<ArgumentException>(null, () => cv.ConvertFrom(null, null, "foo")); } [Fact] public void ConvertFrom_InvalidString() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, "baz")); Assert.Null(o); } [Fact] public void ConvertFrom_InvalidString_WhiteSpaceAtTheBeginning() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, " Foo")); Assert.Null(o); } [Fact] public void ConvertFrom_InvalidString_WhiteSpaceAtTheEnd() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, "Foo ")); Assert.Null(o); } [Fact] public void ConvertFrom_InvalidString_DigitAtTheBeginning() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, "1Foo")); Assert.Null(o); } [Fact] public void ConvertFrom_InvalidString_PlusSignAtTheBeginning() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, "+Foo")); Assert.Null(o); } [Fact] public void ConvertFrom_InvalidString_MinusSignAtTheBeginning() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, "-Foo")); Assert.Null(o); } [Fact] public void ConvertFrom_Null() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, null)); Assert.Null(o); } [Fact] public void ConvertFrom_EmptyString() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); object o = null; AssertExtensions.Throws<ArgumentException>(null, () => o = cv.ConvertFrom(null, null, string.Empty)); Assert.Null(o); } [Fact] public void ConvertTo() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.Equal("Foo", cv.ConvertTo(null, null, FooEnum.Foo, typeof(string))); Assert.Equal("Bar", cv.ConvertTo(null, null, FooEnum.Bar, typeof(string))); } [Fact] public void ConvertTo_NullError() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.Throws<NullReferenceException>(() => cv.ConvertTo(null, null, null, typeof(string))); } [Fact] public void ConvertTo_TypeError1() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.Equal("0", cv.ConvertTo(null, null, 0, typeof(string))); } [Fact] public void ConvertTo_TypeError2() { GenericEnumConverter cv = new GenericEnumConverter(typeof(FooEnum)); Assert.Equal("", cv.ConvertTo(null, null, "", typeof(string))); } } }
using System; using System.Data; using System.Collections.Generic; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo.WebAppLib; namespace Vevo { /// <summary> /// Summary description for AdminAdvancedBaseListControl /// </summary> public abstract class AdminAdvancedBaseListControl : AdminAdvancedBaseUserControl { // Delegates public delegate void BrowseHistoryAddEventHandler( object sender, BrowseHistoryAddEventArgs e ); private UrlQuery _browseHistoryQuery; private GridView _grid; private string _defaultSortExpression; private IPagingControl _pagingControl; private ISearchFilter _searchFilter; private ILanguageControl _languageControl; private ICategoryFilterDrop _categoryFilterDrop; private IStoreFilterDrop _storeFilterDrop; private ICurrencyControl _currencyFilterDrop; private List<IAdvancedPostbackControl> _postbackControls = new List<IAdvancedPostbackControl>(); private void OnBrowseHistoryAdding( BrowseHistoryAddEventArgs e ) { if (BrowseHistoryAdding != null) { BrowseHistoryAdding( this, e ); } } protected event BrowseHistoryAddEventHandler BrowseHistoryAdding; protected abstract void RefreshGrid(); protected GridViewHelper GridHelper { get { if (ViewState["GridHelper"] == null && _grid != null) { GridViewHelper helper = new GridViewHelper( _grid, _defaultSortExpression ); if (MainContext.QueryString["Sort"] != null) { helper.SetFullSortText( MainContext.QueryString["Sort"] ); } ViewState["GridHelper"] = helper; } return (GridViewHelper) ViewState["GridHelper"]; } } protected void uxGrid_Sorting( object sender, GridViewSortEventArgs e ) { GridHelper.SelectSorting( e.SortExpression ); RefreshGrid(); AddBrowseHistory(); } protected virtual void uxLanguageControl_BubbleEvent( object sender, EventArgs e ) { if (_categoryFilterDrop != null) _categoryFilterDrop.CultureID = _languageControl.CurrentCultureID; // Do not keep search filter while switching language if (_pagingControl != null) _pagingControl.CurrentPage = 1; if (_searchFilter != null) _searchFilter.ClearFilter(); RefreshGrid(); AddBrowseHistory(); } protected virtual void uxSearchFilter_BubbleEvent( object sender, EventArgs e ) { if (_pagingControl != null) _pagingControl.CurrentPage = 1; RefreshGrid(); AddBrowseHistory(); } protected virtual void uxPagingControl_BubbleEvent( object sender, EventArgs e ) { RefreshGrid(); AddBrowseHistory(); } protected virtual void uxCategoryFilterDrop_BubbleEvent( object sender, EventArgs e ) { if (_pagingControl != null) _pagingControl.CurrentPage = 1; RefreshGrid(); AddBrowseHistory(); } protected virtual void uxStoreFilterDrop_BubbleEvent( object sender, EventArgs e ) { if (_pagingControl != null) _pagingControl.CurrentPage = 1; RefreshGrid(); AddBrowseHistory(); } protected virtual void uxCurrencyControl_BubbleEvent( object sender, EventArgs e ) { if (_pagingControl != null) _pagingControl.CurrentPage = 1; RefreshGrid(); AddBrowseHistory(); } protected void AddBrowseHistory() { // First, begin with current MainContext query string and apply the query string from // other controls (e.g. page number, search). _browseHistoryQuery.AddQuery( MainContext.QueryString ); OnBrowseHistoryAdding( new BrowseHistoryAddEventArgs( _browseHistoryQuery ) ); foreach (IAdvancedPostbackControl control in _postbackControls) { control.UpdateBrowseQuery( _browseHistoryQuery ); } if (GridHelper != null) _browseHistoryQuery.AddQuery( "Sort", GridHelper.GetFullSortText() ); MainContext.AddBrowseHistory( MainContext.LastControl, _browseHistoryQuery.RawQueryString ); } protected void RegisterGridView( GridView grid, string defaultSortExpression ) { _grid = grid; _defaultSortExpression = defaultSortExpression; } protected void RegisterLanguageControl( ILanguageControl languageControl ) { _languageControl = languageControl; _postbackControls.Add( languageControl ); } protected void RegisterSearchFilter( ISearchFilter searchFilter ) { _searchFilter = searchFilter; _postbackControls.Add( searchFilter ); } protected void RegisterPagingControl( IPagingControl pagingContorl ) { _pagingControl = pagingContorl; _postbackControls.Add( pagingContorl ); } protected void RegisterCategoryFilterDrop( ICategoryFilterDrop categoryFilterDrop ) { _categoryFilterDrop = categoryFilterDrop; _postbackControls.Add( categoryFilterDrop ); } protected void RegisterStoreFilterDrop( IStoreFilterDrop storeFilterDrop ) { _storeFilterDrop = storeFilterDrop; _postbackControls.Add( storeFilterDrop ); } protected void RegisterCurrencyFilterDrop( ICurrencyControl currencyFilterDrop ) { _currencyFilterDrop = currencyFilterDrop; _postbackControls.Add( currencyFilterDrop ); } protected void RegisterCustomControl( IAdvancedPostbackControl control ) { _postbackControls.Add( control ); } public AdminAdvancedBaseListControl() { _browseHistoryQuery = new UrlQuery(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; namespace System.Collections.Specialized.Tests { public class CopyToTests { private string _strErr = "Error"; [Fact] public void Test01() { MyNameObjectCollection noc = new MyNameObjectCollection(); Array array = null; ArrayList ArrayValues = new ArrayList(); Random rand = new Random(-55); int n = 0; String key1 = "key1"; String key2 = "key2"; Foo val1 = new Foo(); Foo val2 = new Foo(); // [] Copy a collection to middle of target array. // Set up initial collection n = rand.Next(10, 1000); for (int i = 0; i < n; i++) { noc.Add("key_" + i.ToString(), new Foo()); } // Set up initial array n = noc.Count + rand.Next(20, 100); array = Array.CreateInstance(typeof(String), n); ArrayValues.Clear(); for (int i = 0; i < n; i++) { String v = "arrayvalue_" + i.ToString(); array.SetValue(v, i); ArrayValues.Add(v); } // Copy the collection int offset = 10; ((ICollection)noc).CopyTo(array, offset); for (int i = 0; i < noc.Count; i++) { ArrayValues[i + offset] = noc.GetKey(i); } // Check array CheckArray(array, ArrayValues); // [] Verify copy is distinct from original collection. // Clear initial collection noc.Clear(); // Verify copy is not cleared CheckArray(array, ArrayValues); // [] Fill whole array (index=0) // Set up initial collection noc = new MyNameObjectCollection(); n = rand.Next(10, 1000); for (int i = 0; i < n; i++) { noc.Add("key_" + i.ToString(), new Foo()); } // Set up initial array n = noc.Count; array = Array.CreateInstance(typeof(String), n); ArrayValues.Clear(); for (int i = 0; i < n; i++) { String v = "arrayvalue_" + i.ToString(); array.SetValue(v, i); ArrayValues.Add(v); } // Copy the collection ((ICollection)noc).CopyTo(array, 0); for (int i = 0; i < noc.Count; i++) { ArrayValues[i] = noc.GetKey(i); } // Check array CheckArray(array, ArrayValues); // [] index = max index in array // Set up initial collection noc.Clear(); noc.Add("key1", new Foo()); // Set up initial array n = noc.Count + rand.Next(1, 100); array = Array.CreateInstance(typeof(String), n); ArrayValues.Clear(); for (int i = 0; i < n; i++) { String v = "arrayvalue_" + i.ToString(); array.SetValue(v, i); ArrayValues.Add(v); } // Copy the collection offset = ArrayValues.Count - 1; ((ICollection)noc).CopyTo(array, offset); ArrayValues[offset] = noc.GetKey(0); // Retrieve values CheckArray(array, ArrayValues); // [] Target array is zero-length. array = Array.CreateInstance(typeof(String), 0); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, 0); }); // [] Call on an empty collection (to zero-length array). noc = new MyNameObjectCollection(); array = Array.CreateInstance(typeof(String), 0); // Copy the collection ((ICollection)noc).CopyTo(array, 0); // [] Call on an empty collection. noc = new MyNameObjectCollection(); array = Array.CreateInstance(typeof(String), 16); // Copy the collection ((ICollection)noc).CopyTo(array, 0); // Retrieve elements foreach (String v in array) { if (v != null) { Assert.False(true, _strErr + "Value is incorrect. array should be null"); } } // [] Call with array = null noc = new MyNameObjectCollection(); Assert.Throws<ArgumentNullException>(() => { ((ICollection)noc).CopyTo(null, 0); }); // [] Target array is multidimensional. array = new string[20, 2]; noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, 16); }); // [] Target array is of incompatible type. array = Array.CreateInstance(typeof(Foo), 10); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<InvalidCastException>(() => { ((ICollection)noc).CopyTo(array, 1); }); // [] index = array length n = rand.Next(10, 100); array = Array.CreateInstance(typeof(String), n); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, n); }); // [] index > array length n = rand.Next(10, 100); array = Array.CreateInstance(typeof(String), n); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, n + 1); }); // [] index = Int32.MaxValue array = Array.CreateInstance(typeof(String), 10); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, Int32.MaxValue); }); // [] index < 0 array = Array.CreateInstance(typeof(String), 10); noc = new MyNameObjectCollection(); noc.Add(key1, val1); noc.Add(key2, val2); Assert.Throws<ArgumentOutOfRangeException>(() => { ((ICollection)noc).CopyTo(array, -1); }); // [] index is valid but collection doesn't fit in available space noc = new MyNameObjectCollection(); // Set up initial collection n = rand.Next(10, 1000); for (int i = 0; i < n; i++) { noc.Add("key_" + i.ToString(), new Foo()); } // Set up initial array n = noc.Count + 20; array = Array.CreateInstance(typeof(Foo), n); Assert.Throws<ArgumentException>(() => { ((ICollection)noc).CopyTo(array, 30); }); // array is only 20 bigger than collection // [] index is negative noc = new MyNameObjectCollection(); // Set up initial collection n = rand.Next(10, 1000); for (int i = 0; i < n; i++) { noc.Add("key_" + i.ToString(), new Foo()); } // Set up initial array n = noc.Count + 20; array = Array.CreateInstance(typeof(Foo), n); Assert.Throws<ArgumentOutOfRangeException>(() => { ((ICollection)noc).CopyTo(array, -1); }); } void CheckArray(Array array, ArrayList expected) { if (array.Length != expected.Count) { Assert.False(true, string.Format(_strErr + "Array length != {0}. Length == {1}", expected.Count, array.Length)); } for (int i = 0; i < expected.Count; i++) { if (((String[])array)[i] != (String)expected[i]) { Assert.False(true, string.Format("Value {0} is incorrect. array[{0}]={1}, should be {2}", i, ((String[])array)[i], (String)expected[i])); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. private const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; private const int DontCopyOnWriteLineThreshold = 512; // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, UTF8NoBOM, MinBufferSize, true); private Stream _stream; private Encoding _encoding; private Encoder _encoder; private byte[] _byteBuffer; private char[] _charBuffer; private int _charPos; private int _charLen; private bool _autoFlush; private bool _haveWrittenPreamble; private bool _closable; // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(SR.InvalidOperation_AsyncIOInProgress); } // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static Encoding UTF8NoBOM => EncodingCache.UTF8NoBOM; internal StreamWriter() : base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) { throw new ArgumentNullException(stream == null ? nameof(stream) : nameof(encoding)); } if (!stream.CanWrite) { throw new ArgumentException(SR.Argument_StreamNotWritable); } if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); } Init(stream, encoding, bufferSize, leaveOpen); } public StreamWriter(string path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } public StreamWriter(string path, bool append, Encoding encoding, int bufferSize) { if (path == null) throw new ArgumentNullException(nameof(path)); if (encoding == null) throw new ArgumentNullException(nameof(encoding)); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); Stream stream = new FileStream(path, append ? FileMode.Append : FileMode.Create, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan); Init(stream, encoding, bufferSize, shouldLeaveOpen: false); } private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { _stream = streamArg; _encoding = encodingArg; _encoder = _encoding.GetEncoder(); if (bufferSize < MinBufferSize) { bufferSize = MinBufferSize; } _charBuffer = new char[bufferSize]; _byteBuffer = new byte[_encoding.GetMaxByteCount(bufferSize)]; _charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (_stream.CanSeek && _stream.Position > 0) { _haveWrittenPreamble = true; } _closable = !shouldLeaveOpen; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (_stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */) { CheckAsyncTaskInProgress(); Flush(true, true); } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && _stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) { _stream.Close(); } } finally { _stream = null; _byteBuffer = null; _charBuffer = null; _encoding = null; _encoder = null; _charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { CheckAsyncTaskInProgress(); Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } // Perf boost for Flush on non-dirty writers. if (_charPos == 0 && !flushStream && !flushEncoder) { return; } if (!_haveWrittenPreamble) { _haveWrittenPreamble = true; ReadOnlySpan<byte> preamble = _encoding.Preamble; if (preamble.Length > 0) { _stream.Write(preamble); } } int count = _encoder.GetBytes(_charBuffer, 0, _charPos, _byteBuffer, 0, flushEncoder); _charPos = 0; if (count > 0) { _stream.Write(_byteBuffer, 0, count); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { _stream.Flush(); } } public virtual bool AutoFlush { get { return _autoFlush; } set { CheckAsyncTaskInProgress(); _autoFlush = value; if (value) { Flush(true, false); } } } public virtual Stream BaseStream { get { return _stream; } } internal bool LeaveOpen { get { return !_closable; } } internal bool HaveWrittenPreamble { set { _haveWrittenPreamble = value; } } public override Encoding Encoding { get { return _encoding; } } public override void Write(char value) { CheckAsyncTaskInProgress(); if (_charPos == _charLen) { Flush(false, false); } _charBuffer[_charPos] = value; _charPos++; if (_autoFlush) { Flush(true, false); } } public override void Write(char[] buffer) { if (buffer != null) { WriteCore(buffer, _autoFlush); } } public override void Write(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } WriteCore(new ReadOnlySpan<char>(buffer, index, count), _autoFlush); } public override void Write(ReadOnlySpan<char> buffer) { if (GetType() == typeof(StreamWriter)) { WriteCore(buffer, _autoFlush); } else { // If a derived class may have overridden existing Write behavior, // we need to make sure we use it. base.Write(buffer); } } private unsafe void WriteCore(ReadOnlySpan<char> buffer, bool autoFlush) { CheckAsyncTaskInProgress(); if (buffer.Length <= 4 && // Threshold of 4 chosen based on perf experimentation buffer.Length <= _charLen - _charPos) { // For very short buffers and when we don't need to worry about running out of space // in the char buffer, just copy the chars individually. for (int i = 0; i < buffer.Length; i++) { _charBuffer[_charPos++] = buffer[i]; } } else { // For larger buffers or when we may run out of room in the internal char buffer, copy in chunks. // Use unsafe code until https://github.com/dotnet/coreclr/issues/13827 is addressed, as spans are // resulting in significant overhead (even when the if branch above is taken rather than this // else) due to temporaries that need to be cleared. Given the use of unsafe code, we also // make local copies of instance state to protect against potential concurrent misuse. char[] charBuffer = _charBuffer; if (charBuffer == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } fixed (char* bufferPtr = &MemoryMarshal.GetReference(buffer)) fixed (char* dstPtr = &charBuffer[0]) { char* srcPtr = bufferPtr; int count = buffer.Length; int dstPos = _charPos; // use a local copy of _charPos for safety while (count > 0) { if (dstPos == charBuffer.Length) { Flush(false, false); dstPos = 0; } int n = Math.Min(charBuffer.Length - dstPos, count); int bytesToCopy = n * sizeof(char); Buffer.MemoryCopy(srcPtr, dstPtr + dstPos, bytesToCopy, bytesToCopy); _charPos += n; dstPos += n; srcPtr += n; count -= n; } } } if (autoFlush) { Flush(true, false); } } public override void Write(string value) { if (value != null) { WriteCore(value.AsReadOnlySpan(), _autoFlush); } } // // Optimize the most commonly used WriteLine overload. This optimization is important for System.Console in particular // because of it will make one WriteLine equal to one call to the OS instead of two in the common case. // public override void WriteLine(string value) { CheckAsyncTaskInProgress(); if (value != null) { WriteCore(value.AsReadOnlySpan(), autoFlush: false); } WriteCore(new ReadOnlySpan<char>(CoreNewLine), autoFlush: true); } public override void WriteLine(ReadOnlySpan<char> value) { if (GetType() == typeof(StreamWriter)) { CheckAsyncTaskInProgress(); WriteCore(value, autoFlush: false); WriteCore(new ReadOnlySpan<char>(CoreNewLine), autoFlush: true); } else { // If a derived class may have overridden existing WriteLine behavior, // we need to make sure we use it. base.WriteLine(value); } } #region Task based Async APIs public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, char value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(string value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(value); } if (value != null) { if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, string value, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine) { Debug.Assert(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) { n = count; } Debug.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, new ReadOnlyMemory<char>(buffer, index, count), _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (GetType() != typeof(StreamWriter)) { // If a derived type may have overridden existing WriteASync(char[], ...) behavior, make sure we use it. return base.WriteAsync(buffer, cancellationToken); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Task task = WriteAsyncInternal(this, buffer, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: false, cancellationToken: cancellationToken); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, ReadOnlyMemory<char> source, char[] charBuffer, int charPos, int charLen, char[] coreNewLine, bool autoFlush, bool appendNewLine, CancellationToken cancellationToken) { int copied = 0; while (copied < source.Length) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } int n = Math.Min(charLen - charPos, source.Length - copied); Debug.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); source.Span.Slice(copied, n).CopyTo(new Span<char>(charBuffer, charPos, n)); charPos += n; copied += n; } if (appendNewLine) { for (int i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos, cancellationToken).ConfigureAwait(false); Debug.Assert(_this._charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, ReadOnlyMemory<char>.Empty, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(string value) { if (value == null) { return WriteLineAsync(); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(value); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); } if (buffer.Length - index < count) { throw new ArgumentException(SR.Argument_InvalidOffLen); } // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, index, count); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, new ReadOnlyMemory<char>(buffer, index, count), _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: default); _asyncWriteTask = task; return task; } public override Task WriteLineAsync(ReadOnlyMemory<char> buffer, CancellationToken cancellationToken = default) { if (GetType() != typeof(StreamWriter)) { return base.WriteLineAsync(buffer, cancellationToken); } if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } Task task = WriteAsyncInternal(this, buffer, _charBuffer, _charPos, _charLen, CoreNewLine, _autoFlush, appendNewLine: true, cancellationToken: cancellationToken); _asyncWriteTask = task; return task; } public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(StreamWriter)) { return base.FlushAsync(); } // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (_stream == null) { throw new ObjectDisposedException(null, SR.ObjectDisposed_WriterClosed); } CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, _charBuffer, _charPos); _asyncWriteTask = task; return task; } private int CharPos_Prop { set { _charPos = value; } } private bool HaveWrittenPreamble_Prop { set { _haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, char[] sCharBuffer, int sCharPos, CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) { return Task.CompletedTask; } Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, _haveWrittenPreamble, _encoding, _encoder, _byteBuffer, _stream, cancellationToken); _charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, char[] charBuffer, int charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream, CancellationToken cancellationToken) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) { await stream.WriteAsync(preamble, 0, preamble.Length, cancellationToken).ConfigureAwait(false); } } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) { await stream.WriteAsync(byteBuffer, 0, count, cancellationToken).ConfigureAwait(false); } // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) { await stream.FlushAsync(cancellationToken).ConfigureAwait(false); } } #endregion } // class StreamWriter } // namespace
using System; using System.Collections; using System.IO; using System.Reflection; using AppUtil; using Vim25Api; namespace MobStartPage { /// <summary> /// Browse for contents in Vim - Hostd or Vpxd /// </summary> public class MobStartPage { private static AppUtil.AppUtil cb = null; static VimService _service; static ServiceContent _sic; /// <summary> /// Array of typename + all its properties /// </summary> private string[][] typeInfo = new string[][] { new string[] { "ManagedEntity", "parent", "name" }, }; class MeNode { public ManagedObjectReference parent; public ManagedObjectReference node; public String name; public ArrayList children = new ArrayList(); public MeNode(ManagedObjectReference parent, ManagedObjectReference node, String name) { this.parent = parent; this.node = node; this.name = name; } }; public class MeNodeCompare : IComparer { int IComparer.Compare(Object l, Object r) { String lName = ((MeNode)l).name; String rName = ((MeNode)r).name; return ( (new CaseInsensitiveComparer()).Compare(lName, rName) ); } }; /// <summary> /// Retrieve inventory from the given root /// </summary> private void PrintInventory() { try { // Retrieve Contents recursively starting at the root folder // and using the default property collector. ObjectContent[] ocary = cb.getServiceUtil().GetContentsRecursively(null, null, typeInfo, true); Hashtable nodes = new Hashtable(); MeNode root = null; for (int oci = 0; oci < ocary.Length; oci++) { ObjectContent oc = ocary[oci]; ManagedObjectReference mor = oc.obj; DynamicProperty[] pcary = oc.propSet; if (pcary != null) { ManagedObjectReference parent = null; String name = null; for (int pci = 0; pci < pcary.Length; pci++) { DynamicProperty pc = pcary[pci]; if (pc != null) { if("name" == pc.name) { name = pc.val as String; } if("parent" == pc.name) { parent = pc.val as ManagedObjectReference; } } } MeNode node = new MeNode(parent, mor, name); if(parent == null) { root = node; } nodes.Add(node.node.Value, node); } } // Organize the nodes into a 'tree' foreach (String key in nodes.Keys) { MeNode meNode = nodes[key] as MeNode; if(meNode.parent != null) { ((MeNode)nodes[meNode.parent.Value]).children.Add(meNode); } } String mobUrl = cb.getServiceUrl(); mobUrl = mobUrl.Replace("/sdk", "/mob"); if(mobUrl.IndexOf("mob") == -1) { mobUrl += "/mob"; } mobUrl += "/?moid="; // Map of ManagedEntity to doc file Hashtable typeToDoc = new Hashtable(); typeToDoc["ComputeResource"] = "/vim.ComputeResource.html"; typeToDoc["ClusterComputeResource"] = "/vim.ClusterComputeResource.html"; typeToDoc["Datacenter"] = "/vim.Datacenter.html"; typeToDoc["Folder"] = "/vim.Folder.html"; typeToDoc["HostSystem"] = "/vim.HostSystem.html"; typeToDoc["ResourcePool"] = "/vim.ResourcePool.html"; typeToDoc["VirtualMachine"] = "/vim.VirtualMachine.html"; Hashtable typeToImage = new Hashtable(); typeToImage["ComputeResource"] = "compute-resource.png"; typeToImage["ClusterComputeResource"] = "compute-resource.png"; typeToImage["Datacenter"] = "datacenter.png"; typeToImage["Folder"] = "folder-open.png"; typeToImage["HostSystem"] = "host.png"; typeToImage["ResourcePool"] = "resourcePool.png"; typeToImage["VirtualMachine"] = "virtualMachine.png"; String docRoot = cb.get_option("docref"); if (docRoot != null) { // Try to determine where we are in sample tree // SDK/samples_2_0/DotNet/cs/MobStartPage/bin/Debug String cDir = Directory.GetCurrentDirectory(); if (cDir.EndsWith("Debug") || cDir.EndsWith("Release")) { docRoot = "../../../../../../doc/ReferenceGuide"; } else if (cDir.EndsWith("MobStartPage")) { docRoot = "../../../../doc/ReferenceGuide"; } else if (cDir.EndsWith("cs")) { docRoot = "../../../doc/ReferenceGuide"; } bool docsFound = docRoot != null; // Not Url? if (docsFound && docRoot.IndexOf("http") == -1) { String testFile = docRoot.Replace("/", "\\") + "\\index.html"; docsFound = File.Exists(testFile); } if (!docsFound) { //log.LogLine("Warning: Can't find docs at: " + docRoot); docRoot = null; } // Write out as html into string StringWriter nodeHtml = new StringWriter(); PrintNode(root, nodeHtml, mobUrl, docRoot, typeToDoc, typeToImage); nodeHtml.Close(); Assembly assembly = Assembly.GetExecutingAssembly(); CopyFileFromResource(assembly, "MobStartPage.index.html", "index.html"); CopyFileFromResource(assembly, "MobStartPage.compute-resource.png", "compute-resource.png"); CopyFileFromResource(assembly, "MobStartPage.datacenter.png", "datacenter.png"); CopyFileFromResource(assembly, "MobStartPage.folder.png", "folder.png"); CopyFileFromResource(assembly, "MobStartPage.folder-open.png", "folder-open.png"); CopyFileFromResource(assembly, "MobStartPage.host.png", "host.png"); CopyFileFromResource(assembly, "MobStartPage.resourcePool.png", "resourcePool.png"); CopyFileFromResource(assembly, "MobStartPage.virtualMachine.png", "virtualMachine.png"); // Get and write inventory.html Stream stream = assembly.GetManifestResourceStream("MobStartPage.inventory.html"); StreamReader reader = new StreamReader(stream); String fileData = reader.ReadToEnd(); using (StreamWriter file = new StreamWriter("inventory.html")) { String serverName = cb.getServiceUrl(); int lastCharacter = serverName.LastIndexOfAny(":/".ToCharArray()); if (lastCharacter != -1) { serverName = serverName.Substring(0, lastCharacter); } int firstCharacter = serverName.LastIndexOf('/'); if (firstCharacter != -1) { serverName = serverName.Substring(firstCharacter + 1); } String output = String.Format(fileData, serverName, nodeHtml.ToString()); file.WriteLine(output); } System.Diagnostics.Process.Start("index.html"); cb.log.LogLine("Done Printing Inventory"); } else { System.Console.WriteLine("Please provide the valid reference-doc-location."); } } catch (Exception e) { cb.log.LogLine("MobStartPage : Failed Getting Contents"); throw e; } } void CopyFileFromResource(Assembly assembly, String resourceName, String filename) { // Get and write index.html Stream stream = assembly.GetManifestResourceStream(resourceName); BinaryReader reader = new BinaryReader(stream); using(FileStream file = new FileStream(filename, FileMode.Create)) { do { byte[] buffer = reader.ReadBytes(10240); if(buffer.Length <= 0) break; file.Write(buffer, 0, buffer.Length); } while (true); } } void PrintNode(MeNode node, TextWriter file, String mobUrl, String docRoot, Hashtable typeToDoc, Hashtable typeToImage) { String mobLink = mobUrl + System.Web.HttpUtility.UrlEncode(node.node.Value); String page = typeToDoc[node.node.type] as String; String image = typeToImage[node.node.type] as String; String link = null; if(page != null && docRoot != null) { link = docRoot + page; } if(node.children.Count > 0) { node.children.Sort(new MeNodeCompare()); file.WriteLine("<li style=\"list-style-image:url("+image+")\"><a target=\"mob\" href=\""+mobLink+"\">"+node.name+"</a></li>"); if(link != null) { file.WriteLine("<a target=\"mob\" href=\""+link+"\">?</a>"); } file.WriteLine("<ul>"); foreach (MeNode lNode in node.children) { PrintNode(lNode, file, mobUrl, docRoot, typeToDoc, typeToImage); } file.WriteLine("</ul>"); } else { file.WriteLine("<li style=\"list-style-image:url("+image+")\"><a target=\"mob\" href=\""+mobLink+"\">"+node.name+"</a></li>"); if(link != null) { file.WriteLine("<a target=\"mob\" href=\""+link+"\">?</a>"); } } } public static OptionSpec[] constructOptions() { OptionSpec[] useroptions = new OptionSpec[1]; useroptions[0] = new OptionSpec("docref", "String", 1 , "Document Reference" , null); return useroptions; } /// <summary> /// The main entry point for the application. /// </summary> public static void Main(String[] args) { MobStartPage obj = new MobStartPage(); cb = AppUtil.AppUtil.initialize("MobStartPage", MobStartPage.constructOptions() , args); cb.connect(); obj.PrintInventory(); cb.disConnect(); } } }
using System.Runtime.InteropServices; namespace Avalonia.Media.Transformation { /// <summary> /// Represents a single primitive transform (like translation, rotation, scale, etc.). /// </summary> public struct TransformOperation { public OperationType Type; public Matrix Matrix; public DataLayout Data; public enum OperationType { Translate, Rotate, Scale, Skew, Matrix, Identity } /// <summary> /// Returns whether operation produces the identity matrix. /// </summary> public bool IsIdentity => Matrix.IsIdentity; /// <summary> /// Bakes this operation to a transform matrix. /// </summary> public void Bake() { Matrix = Matrix.Identity; switch (Type) { case OperationType.Translate: { Matrix = Matrix.CreateTranslation(Data.Translate.X, Data.Translate.Y); break; } case OperationType.Rotate: { Matrix = Matrix.CreateRotation(Data.Rotate.Angle); break; } case OperationType.Scale: { Matrix = Matrix.CreateScale(Data.Scale.X, Data.Scale.Y); break; } case OperationType.Skew: { Matrix = Matrix.CreateSkew(Data.Skew.X, Data.Skew.Y); break; } } } /// <summary> /// Returns new identity transform operation. /// </summary> public static TransformOperation Identity => new TransformOperation { Matrix = Matrix.Identity, Type = OperationType.Identity }; /// <summary> /// Attempts to interpolate between two transform operations. /// </summary> /// <param name="from">Source operation.</param> /// <param name="to">Target operation.</param> /// <param name="progress">Interpolation progress.</param> /// <param name="result">Interpolation result that will be filled in when operation was successful.</param> /// <remarks> /// Based upon https://www.w3.org/TR/css-transforms-1/#interpolation-of-transform-functions. /// </remarks> public static bool TryInterpolate(TransformOperation? from, TransformOperation? to, double progress, ref TransformOperation result) { bool fromIdentity = IsOperationIdentity(ref from); bool toIdentity = IsOperationIdentity(ref to); if (fromIdentity && toIdentity) { result.Matrix = Matrix.Identity; return true; } // ReSharper disable PossibleInvalidOperationException TransformOperation fromValue = fromIdentity ? Identity : from.Value; TransformOperation toValue = toIdentity ? Identity : to.Value; // ReSharper restore PossibleInvalidOperationException var interpolationType = toIdentity ? fromValue.Type : toValue.Type; result.Type = interpolationType; switch (interpolationType) { case OperationType.Translate: { double fromX = fromIdentity ? 0 : fromValue.Data.Translate.X; double fromY = fromIdentity ? 0 : fromValue.Data.Translate.Y; double toX = toIdentity ? 0 : toValue.Data.Translate.X; double toY = toIdentity ? 0 : toValue.Data.Translate.Y; result.Data.Translate.X = InterpolationUtilities.InterpolateScalars(fromX, toX, progress); result.Data.Translate.Y = InterpolationUtilities.InterpolateScalars(fromY, toY, progress); result.Bake(); break; } case OperationType.Rotate: { double fromAngle = fromIdentity ? 0 : fromValue.Data.Rotate.Angle; double toAngle = toIdentity ? 0 : toValue.Data.Rotate.Angle; result.Data.Rotate.Angle = InterpolationUtilities.InterpolateScalars(fromAngle, toAngle, progress); result.Bake(); break; } case OperationType.Scale: { double fromX = fromIdentity ? 1 : fromValue.Data.Scale.X; double fromY = fromIdentity ? 1 : fromValue.Data.Scale.Y; double toX = toIdentity ? 1 : toValue.Data.Scale.X; double toY = toIdentity ? 1 : toValue.Data.Scale.Y; result.Data.Scale.X = InterpolationUtilities.InterpolateScalars(fromX, toX, progress); result.Data.Scale.Y = InterpolationUtilities.InterpolateScalars(fromY, toY, progress); result.Bake(); break; } case OperationType.Skew: { double fromX = fromIdentity ? 0 : fromValue.Data.Skew.X; double fromY = fromIdentity ? 0 : fromValue.Data.Skew.Y; double toX = toIdentity ? 0 : toValue.Data.Skew.X; double toY = toIdentity ? 0 : toValue.Data.Skew.Y; result.Data.Skew.X = InterpolationUtilities.InterpolateScalars(fromX, toX, progress); result.Data.Skew.Y = InterpolationUtilities.InterpolateScalars(fromY, toY, progress); result.Bake(); break; } case OperationType.Matrix: { var fromMatrix = fromIdentity ? Matrix.Identity : fromValue.Matrix; var toMatrix = toIdentity ? Matrix.Identity : toValue.Matrix; if (!Matrix.TryDecomposeTransform(fromMatrix, out Matrix.Decomposed fromDecomposed) || !Matrix.TryDecomposeTransform(toMatrix, out Matrix.Decomposed toDecomposed)) { return false; } var interpolated = InterpolationUtilities.InterpolateDecomposedTransforms( ref fromDecomposed, ref toDecomposed, progress); result.Matrix = InterpolationUtilities.ComposeTransform(interpolated); break; } case OperationType.Identity: { result.Matrix = Matrix.Identity; break; } } return true; } private static bool IsOperationIdentity(ref TransformOperation? operation) { return !operation.HasValue || operation.Value.IsIdentity; } [StructLayout(LayoutKind.Explicit)] public struct DataLayout { [FieldOffset(0)] public SkewLayout Skew; [FieldOffset(0)] public ScaleLayout Scale; [FieldOffset(0)] public TranslateLayout Translate; [FieldOffset(0)] public RotateLayout Rotate; public struct SkewLayout { public double X; public double Y; } public struct ScaleLayout { public double X; public double Y; } public struct TranslateLayout { public double X; public double Y; } public struct RotateLayout { public double Angle; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using System.Security.Policy; using System.Text; using System.Threading; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Amib.Threading; using OpenSim.Framework; using OpenSim.Region.CoreModules; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using OpenSim.Region.ScriptEngine.Shared.Api.Runtime; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; using OpenSim.Region.ScriptEngine.Interfaces; namespace OpenSim.Region.ScriptEngine.Shared.Instance { public class ScriptInstance : MarshalByRefObject, IScriptInstance { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool StatePersistedHere { get { return m_AttachedAvatar == UUID.Zero; } } /// <summary> /// The current work item if an event for this script is running or waiting to run, /// </summary> /// <remarks> /// Null if there is no running or waiting to run event. Must be changed only under an EventQueue lock. /// </remarks> private IScriptWorkItem m_CurrentWorkItem; private IScript m_Script; private DetectParams[] m_DetectParams; private bool m_TimerQueued; private DateTime m_EventStart; private bool m_InEvent; private string m_assemblyPath; private string m_dataPath; private string m_CurrentEvent = String.Empty; private bool m_InSelfDelete; private int m_MaxScriptQueue; private bool m_SaveState; private int m_ControlEventsInQueue; private int m_LastControlLevel; private bool m_CollisionInQueue; private bool m_StateChangeInProgress; // The following is for setting a minimum delay between events private double m_minEventDelay; private long m_eventDelayTicks; private long m_nextEventTimeTicks; private bool m_startOnInit = true; private UUID m_AttachedAvatar; private StateSource m_stateSource; private bool m_postOnRez; private bool m_startedFromSavedState; private UUID m_CurrentStateHash; private UUID m_RegionID; public int DebugLevel { get; set; } public Dictionary<KeyValuePair<int, int>, KeyValuePair<int, int>> LineMap { get; set; } private Dictionary<string,IScriptApi> m_Apis = new Dictionary<string,IScriptApi>(); public Object[] PluginData = new Object[0]; /// <summary> /// Used by llMinEventDelay to suppress events happening any faster than this speed. /// This currently restricts all events in one go. Not sure if each event type has /// its own check so take the simple route first. /// </summary> public double MinEventDelay { get { return m_minEventDelay; } set { if (value > 0.001) m_minEventDelay = value; else m_minEventDelay = 0.0; m_eventDelayTicks = (long)(m_minEventDelay * 10000000L); m_nextEventTimeTicks = DateTime.Now.Ticks; } } public bool Running { get; set; } public bool Suspended { get { return m_Suspended; } set { // Need to do this inside a lock in order to avoid races with EventProcessor() lock (m_Script) { bool wasSuspended = m_Suspended; m_Suspended = value; if (wasSuspended && !m_Suspended) { lock (EventQueue) { // Need to place ourselves back in a work item if there are events to process if (EventQueue.Count > 0 && Running && !ShuttingDown) m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } } } private bool m_Suspended; public bool ShuttingDown { get; set; } public string State { get; set; } public IScriptEngine Engine { get; private set; } public UUID AppDomain { get; set; } public SceneObjectPart Part { get; private set; } public string PrimName { get; private set; } public string ScriptName { get; private set; } public UUID ItemID { get; private set; } public UUID ObjectID { get { return Part.UUID; } } public uint LocalID { get { return Part.LocalId; } } public UUID RootObjectID { get { return Part.ParentGroup.UUID; } } public uint RootLocalID { get { return Part.ParentGroup.LocalId; } } public UUID AssetID { get; private set; } public Queue EventQueue { get; private set; } public long EventsQueued { get { lock (EventQueue) return EventQueue.Count; } } public long EventsProcessed { get; private set; } public int StartParam { get; set; } public TaskInventoryItem ScriptTask { get; private set; } public DateTime TimeStarted { get; private set; } public long MeasurementPeriodTickStart { get; private set; } public long MeasurementPeriodExecutionTime { get; private set; } public static readonly long MaxMeasurementPeriod = 30 * TimeSpan.TicksPerMinute; private bool m_coopTermination; private EventWaitHandle m_coopSleepHandle; public void ClearQueue() { m_TimerQueued = false; m_StateChangeInProgress = false; EventQueue.Clear(); } public ScriptInstance( IScriptEngine engine, SceneObjectPart part, TaskInventoryItem item, int startParam, bool postOnRez, int maxScriptQueue) { State = "default"; EventQueue = new Queue(32); Engine = engine; Part = part; ScriptTask = item; // This is currently only here to allow regression tests to get away without specifying any inventory // item when they are testing script logic that doesn't require an item. if (ScriptTask != null) { ScriptName = ScriptTask.Name; ItemID = ScriptTask.ItemID; AssetID = ScriptTask.AssetID; } PrimName = part.ParentGroup.Name; StartParam = startParam; m_MaxScriptQueue = maxScriptQueue; m_postOnRez = postOnRez; m_AttachedAvatar = Part.ParentGroup.AttachedAvatar; m_RegionID = Part.ParentGroup.Scene.RegionInfo.RegionID; m_SaveState = StatePersistedHere; // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Instantiated script instance {0} (id {1}) in part {2} (id {3}) in object {4} attached avatar {5} in {6}", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, m_AttachedAvatar, Engine.World.Name); } /// <summary> /// Load the script from an assembly into an AppDomain. /// </summary> /// <param name='dom'></param> /// <param name='assembly'></param> /// <param name='dataPath'> /// Path for all script associated data (state, etc.). In a multi-region set up /// with all scripts loading into the same AppDomain this may not be the same place as the DLL itself. /// </param> /// <param name='stateSource'></param> /// <returns>false if load failed, true if suceeded</returns> public bool Load( IScript script, EventWaitHandle coopSleepHandle, string assemblyPath, string dataPath, StateSource stateSource, bool coopTermination) { m_Script = script; m_coopSleepHandle = coopSleepHandle; m_assemblyPath = assemblyPath; m_dataPath = dataPath; m_stateSource = stateSource; m_coopTermination = coopTermination; ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle); } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace); return false; } // For attachments, XEngine saves the state into a .state file when XEngine.SetXMLState() is called. string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state"); if (File.Exists(savedState)) { // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Found state for script {0} for {1} ({2}) at {3} in {4}", // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name); string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = Encoding.UTF8.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (!Running) m_startOnInit = false; Running = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } // If this script is in an attachment then we no longer need the state file. if (!StatePersistedHere) RemoveState(); } // else // { // m_log.WarnFormat( // "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState); // } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace); } } // else // { // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Did not find state for script {0} for {1} ({2}) at {3} in {4}", // ItemID, savedState, Part.Name, Part.ParentGroup.Name, Part.ParentGroup.Scene.Name); // } return true; } public void Init() { if (ShuttingDown) return; if (m_startedFromSavedState) { if (m_startOnInit) Start(); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } else if (m_stateSource == StateSource.RegionStart) { //m_log.Debug("[Script] Posted changed(CHANGED_REGION_RESTART) to script"); PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION_RESTART) }, new DetectParams[0])); } else if (m_stateSource == StateSource.PrimCrossing || m_stateSource == StateSource.Teleporting) { // CHANGED_REGION PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.REGION) }, new DetectParams[0])); // CHANGED_TELEPORT if (m_stateSource == StateSource.Teleporting) PostEvent(new EventParams("changed", new Object[] { new LSL_Types.LSLInteger((int)Changed.TELEPORT) }, new DetectParams[0])); } } else { if (m_startOnInit) Start(); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); if (m_postOnRez) { PostEvent(new EventParams("on_rez", new Object[] {new LSL_Types.LSLInteger(StartParam)}, new DetectParams[0])); } if (m_stateSource == StateSource.AttachedRez) { PostEvent(new EventParams("attach", new object[] { new LSL_Types.LSLString(m_AttachedAvatar.ToString()) }, new DetectParams[0])); } } } private void ReleaseControls() { int permsMask; UUID permsGranter; lock (Part.TaskInventory) { if (!Part.TaskInventory.ContainsKey(ItemID)) return; permsGranter = Part.TaskInventory[ItemID].PermsGranter; permsMask = Part.TaskInventory[ItemID].PermsMask; } if ((permsMask & ScriptBaseClass.PERMISSION_TAKE_CONTROLS) != 0) { ScenePresence presence = Engine.World.GetScenePresence(permsGranter); if (presence != null) presence.UnRegisterControlEventsToScript(LocalID, ItemID); } } public void DestroyScriptInstance() { ReleaseControls(); AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); } public void RemoveState() { string savedState = Path.Combine(m_dataPath, ItemID.ToString() + ".state"); // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Deleting state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}.", // savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name); try { File.Delete(savedState); } catch (Exception e) { m_log.Warn( string.Format( "[SCRIPT INSTANCE]: Could not delete script state {0} for script {1} (id {2}) in part {3} (id {4}) in object {5} in {6}. Exception ", savedState, ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name), e); } } public void VarDump(Dictionary<string, object> vars) { // m_log.Info("Variable dump for script "+ ItemID.ToString()); // foreach (KeyValuePair<string, object> v in vars) // { // m_log.Info("Variable: "+v.Key+" = "+v.Value.ToString()); // } } public void Start() { lock (EventQueue) { if (Running) return; Running = true; TimeStarted = DateTime.Now; MeasurementPeriodTickStart = Util.EnvironmentTickCount(); MeasurementPeriodExecutionTime = 0; if (EventQueue.Count > 0) { if (m_CurrentWorkItem == null) m_CurrentWorkItem = Engine.QueueEventHandler(this); // else // m_log.Error("[Script] Tried to start a script that was already queued"); } } } public bool Stop(int timeout, bool clearEventQueue = false) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Stopping script {0} {1} in {2} {3} with timeout {4} {5} {6}", ScriptName, ItemID, PrimName, ObjectID, timeout, m_InSelfDelete, DateTime.Now.Ticks); IScriptWorkItem workItem; lock (EventQueue) { if (clearEventQueue) ClearQueue(); if (!Running) return true; // If we're not running or waiting to run an event then we can safely stop. if (m_CurrentWorkItem == null) { Running = false; return true; } // If we are waiting to run an event then we can try to cancel it. if (m_CurrentWorkItem.Cancel()) { m_CurrentWorkItem = null; Running = false; return true; } workItem = m_CurrentWorkItem; Running = false; } // Wait for the current event to complete. if (!m_InSelfDelete) { if (!m_coopTermination) { // If we're not co-operative terminating then try and wait for the event to complete before stopping if (workItem.Wait(timeout)) return true; } else { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopping script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); // This will terminate the event on next handle check by the script. m_coopSleepHandle.Set(); // For now, we will wait forever since the event should always cleanly terminate once LSL loop // checking is implemented. May want to allow a shorter timeout option later. if (workItem.Wait(Timeout.Infinite)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Co-operatively stopped script {0} {1} in {2} {3}", ScriptName, ItemID, PrimName, ObjectID); return true; } } } lock (EventQueue) { workItem = m_CurrentWorkItem; } if (workItem == null) return true; // If the event still hasn't stopped and we the stop isn't the result of script or object removal, then // forcibly abort the work item (this aborts the underlying thread). // Co-operative termination should never reach this point. if (!m_InSelfDelete) { m_log.DebugFormat( "[SCRIPT INSTANCE]: Aborting unstopped script {0} {1} in prim {2}, localID {3}, timeout was {4} ms", ScriptName, ItemID, PrimName, LocalID, timeout); workItem.Abort(); } lock (EventQueue) { m_CurrentWorkItem = null; } return true; } public void SetState(string state) { if (state == State) return; EventParams lastTimerEv = null; lock (EventQueue) { // Remove all queued events, remembering the last timer event while (EventQueue.Count > 0) { EventParams tempv = (EventParams)EventQueue.Dequeue(); if (tempv.EventName == "timer") lastTimerEv = tempv; } // Post events PostEvent(new EventParams("state_exit", new Object[0], new DetectParams[0])); PostEvent(new EventParams("state", new Object[] { state }, new DetectParams[0])); PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); // Requeue the timer event after the state changing events if (lastTimerEv != null) EventQueue.Enqueue(lastTimerEv); // This will stop events from being queued and processed // until the new state is started m_StateChangeInProgress = true; } throw new EventAbortException(); } /// <summary> /// Post an event to this script instance. /// </summary> /// <remarks> /// The request to run the event is sent /// </remarks> /// <param name="data"></param> public void PostEvent(EventParams data) { // m_log.DebugFormat("[Script] Posted event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); if (!Running) return; // If min event delay is set then ignore any events untill the time has expired // This currently only allows 1 event of any type in the given time period. // This may need extending to allow for a time for each individual event type. if (m_eventDelayTicks != 0) { if (DateTime.Now.Ticks < m_nextEventTimeTicks) return; m_nextEventTimeTicks = DateTime.Now.Ticks + m_eventDelayTicks; } lock (EventQueue) { // The only events that persist across state changes are timers if (m_StateChangeInProgress && data.EventName != "timer") return; if (EventQueue.Count >= m_MaxScriptQueue) return; if (data.EventName == "timer") { if (m_TimerQueued) return; m_TimerQueued = true; } if (data.EventName == "control") { int held = ((LSL_Types.LSLInteger)data.Params[1]).value; // int changed = ((LSL_Types.LSLInteger)data.Params[2]).value; // If the last message was a 0 (nothing held) // and this one is also nothing held, drop it // if (m_LastControlLevel == held && held == 0) return; // If there is one or more queued, then queue // only changed ones, else queue unconditionally // if (m_ControlEventsInQueue > 0) { if (m_LastControlLevel == held) return; } m_LastControlLevel = held; m_ControlEventsInQueue++; } if (data.EventName == "collision") { if (m_CollisionInQueue) return; if (data.DetectParams == null) return; m_CollisionInQueue = true; } EventQueue.Enqueue(data); if (m_CurrentWorkItem == null) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } } } /// <summary> /// Process the next event queued for this script /// </summary> /// <returns></returns> public object EventProcessor() { // We check here as the thread stopping this instance from running may itself hold the m_Script lock. if (!Running) return 0; lock (m_Script) { // m_log.DebugFormat("[XEngine]: EventProcessor() invoked for {0}.{1}", PrimName, ScriptName); if (Suspended) return 0; EventParams data = null; lock (EventQueue) { data = (EventParams)EventQueue.Dequeue(); if (data == null) // Shouldn't happen { if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } return 0; } if (data.EventName == "timer") m_TimerQueued = false; if (data.EventName == "control") { if (m_ControlEventsInQueue > 0) m_ControlEventsInQueue--; } if (data.EventName == "collision") m_CollisionInQueue = false; } if (DebugLevel >= 2) m_log.DebugFormat( "[SCRIPT INSTANCE]: Processing event {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", data.EventName, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); m_DetectParams = data.DetectParams; if (data.EventName == "state") // Hardcoded state change { State = data.Params[0].ToString(); if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Changing state to {0} for {1}/{2}({3})/{4}({5}) @ {6}/{7}", State, ScriptName, Part.Name, Part.LocalId, Part.ParentGroup.Name, Part.ParentGroup.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name); AsyncCommandManager.StateChange(Engine, LocalID, ItemID); // we are effectively in the new state now, so we can resume queueing // and processing other non-timer events m_StateChangeInProgress = false; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } else { if (Engine.World.PipeEventsForScript(LocalID) || data.EventName == "control") // Don't freeze avies! { // m_log.DebugFormat("[Script] Delivered event {2} in state {3} to {0}.{1}", // PrimName, ScriptName, data.EventName, State); try { m_CurrentEvent = data.EventName; m_EventStart = DateTime.Now; m_InEvent = true; int start = Util.EnvironmentTickCount(); // Reset the measurement period when we reach the end of the current one. if (start - MeasurementPeriodTickStart > MaxMeasurementPeriod) MeasurementPeriodTickStart = start; m_Script.ExecuteEvent(State, data.EventName, data.Params); MeasurementPeriodExecutionTime += Util.EnvironmentTickCount() - start; m_InEvent = false; m_CurrentEvent = String.Empty; if (m_SaveState) { // This will be the very first event we deliver // (state_entry) in default state // SaveState(); m_SaveState = false; } } catch (Exception e) { // m_log.DebugFormat( // "[SCRIPT] Exception in script {0} {1}: {2}{3}", // ScriptName, ItemID, e.Message, e.StackTrace); m_InEvent = false; m_CurrentEvent = String.Empty; if ((!(e is TargetInvocationException) || (!(e.InnerException is SelfDeleteException) && !(e.InnerException is ScriptDeleteException) && !(e.InnerException is ScriptCoopStopException))) && !(e is ThreadAbortException)) { try { // DISPLAY ERROR INWORLD string text = FormatException(e); if (text.Length > 1000) text = text.Substring(0, 1000); Engine.World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, Part.AbsolutePosition, Part.Name, Part.UUID, false); m_log.Debug(string.Format( "[SCRIPT INSTANCE]: Runtime error in script {0} (event {1}), part {2} {3} at {4} in {5} ", ScriptName, data.EventName, PrimName, Part.UUID, Part.AbsolutePosition, Part.ParentGroup.Scene.Name), e); } catch (Exception) { } // catch (Exception e2) // LEGIT: User Scripting // { // m_log.Error("[SCRIPT]: "+ // "Error displaying error in-world: " + // e2.ToString()); // m_log.Error("[SCRIPT]: " + // "Errormessage: Error compiling script:\r\n" + // e.ToString()); // } } else if ((e is TargetInvocationException) && (e.InnerException is SelfDeleteException)) { m_InSelfDelete = true; Engine.World.DeleteSceneObject(Part.ParentGroup, false); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptDeleteException)) { m_InSelfDelete = true; Part.Inventory.RemoveInventoryItem(ItemID); } else if ((e is TargetInvocationException) && (e.InnerException is ScriptCoopStopException)) { if (DebugLevel >= 1) m_log.DebugFormat( "[SCRIPT INSTANCE]: Script {0}.{1} in event {2}, state {3} stopped co-operatively.", PrimName, ScriptName, data.EventName, State); } } } } // If there are more events and we are currently running and not shutting down, then ask the // script engine to run the next event. lock (EventQueue) { EventsProcessed++; if (EventQueue.Count > 0 && Running && !ShuttingDown) { m_CurrentWorkItem = Engine.QueueEventHandler(this); } else { m_CurrentWorkItem = null; } } m_DetectParams = null; return 0; } } public int EventTime() { if (!m_InEvent) return 0; return (DateTime.Now - m_EventStart).Seconds; } public void ResetScript(int timeout) { if (m_Script == null) return; bool running = Running; RemoveState(); ReleaseControls(); Stop(timeout); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); StartParam = 0; State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (running) Start(); m_SaveState = StatePersistedHere; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); } public void ApiResetScript() { // bool running = Running; RemoveState(); ReleaseControls(); m_Script.ResetVars(); Part.Inventory.GetInventoryItem(ItemID).PermsMask = 0; Part.Inventory.GetInventoryItem(ItemID).PermsGranter = UUID.Zero; AsyncCommandManager.RemoveScript(Engine, LocalID, ItemID); EventQueue.Clear(); m_Script.ResetVars(); string oldState = State; StartParam = 0; State = "default"; Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (m_CurrentEvent != "state_entry" || oldState != "default") { m_SaveState = StatePersistedHere; PostEvent(new EventParams("state_entry", new Object[0], new DetectParams[0])); throw new EventAbortException(); } } public Dictionary<string, object> GetVars() { if (m_Script != null) return m_Script.GetVars(); else return new Dictionary<string, object>(); } public void SetVars(Dictionary<string, object> vars) { // foreach (KeyValuePair<string, object> kvp in vars) // m_log.DebugFormat("[SCRIPT INSTANCE]: Setting var {0}={1}", kvp.Key, kvp.Value); m_Script.SetVars(vars); } public DetectParams GetDetectParams(int idx) { if (m_DetectParams == null) return null; if (idx < 0 || idx >= m_DetectParams.Length) return null; return m_DetectParams[idx]; } public UUID GetDetectID(int idx) { if (m_DetectParams == null) return UUID.Zero; if (idx < 0 || idx >= m_DetectParams.Length) return UUID.Zero; return m_DetectParams[idx].Key; } public void SaveState() { if (!Running) return; // We cannot call this inside the EventQueue lock since it will currently take AsyncCommandManager.staticLock. // This may already be held by AsyncCommandManager.DoOneCmdHandlerPass() which in turn can take EventQueue // lock via ScriptInstance.PostEvent(). PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); // We need to lock here to avoid any race with a thread that is removing this script. lock (EventQueue) { // Check again to avoid a race with a thread in Stop() if (!Running) return; // If we're currently in an event, just tell it to save upon return // if (m_InEvent) { m_SaveState = true; return; } // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Saving state for script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}", // ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name); string xml = ScriptSerializer.Serialize(this); // Compare hash of the state we just just created with the state last written to disk // If the state is different, update the disk file. UUID hash = UUID.Parse(Utils.MD5String(xml)); if (hash != m_CurrentStateHash) { try { using (FileStream fs = File.Create(Path.Combine(m_dataPath, ItemID.ToString() + ".state"))) { Byte[] buf = Util.UTF8NoBomEncoding.GetBytes(xml); fs.Write(buf, 0, buf.Length); } } catch(Exception) { // m_log.Error("Unable to save xml\n"+e.ToString()); } //if (!File.Exists(Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"))) //{ // throw new Exception("Completed persistence save, but no file was created"); //} m_CurrentStateHash = hash; } } } public IScriptApi GetApi(string name) { if (m_Apis.ContainsKey(name)) { // m_log.DebugFormat("[SCRIPT INSTANCE]: Found api {0} in {1}@{2}", name, ScriptName, PrimName); return m_Apis[name]; } // m_log.DebugFormat("[SCRIPT INSTANCE]: Did not find api {0} in {1}@{2}", name, ScriptName, PrimName); return null; } public override string ToString() { return String.Format("{0} {1} on {2}", ScriptName, ItemID, PrimName); } string FormatException(Exception e) { if (e.InnerException == null) // Not a normal runtime error return e.ToString(); string message = "Runtime error:\n" + e.InnerException.StackTrace; string[] lines = message.Split(new char[] {'\n'}); foreach (string line in lines) { if (line.Contains("SecondLife.Script")) { int idx = line.IndexOf(':'); if (idx != -1) { string val = line.Substring(idx+1); int lineNum = 0; if (int.TryParse(val, out lineNum)) { KeyValuePair<int, int> pos = Compiler.FindErrorPosition( lineNum, 0, LineMap); int scriptLine = pos.Key; int col = pos.Value; if (scriptLine == 0) scriptLine++; if (col == 0) col++; message = string.Format("Runtime error:\n" + "({0}): {1}", scriptLine - 1, e.InnerException.Message); return message; } } } } // m_log.ErrorFormat("Scripting exception:"); // m_log.ErrorFormat(e.ToString()); return e.ToString(); } public string GetAssemblyName() { return m_assemblyPath; } public string GetXMLState() { bool run = Running; Stop(100); Running = run; // We should not be doing this, but since we are about to // dispose this, it really doesn't make a difference // This is meant to work around a Windows only race // m_InEvent = false; // Force an update of the in-memory plugin data // PluginData = AsyncCommandManager.GetSerializationData(Engine, ItemID); return ScriptSerializer.Serialize(this); } public UUID RegionID { get { return m_RegionID; } } public void Suspend() { Suspended = true; } public void Resume() { Suspended = false; } } /// <summary> /// Xengine event wait handle. /// </summary> /// <remarks> /// This class exists becase XEngineScriptBase gets a reference to this wait handle. We need to make sure that /// when scripts are running in different AppDomains the lease does not expire. /// FIXME: Like LSL_Api, etc., this effectively leaks memory since the GC will never collect it. To avoid this, /// proper remoting sponsorship needs to be implemented across the board. /// </remarks> public class XEngineEventWaitHandle : EventWaitHandle { public XEngineEventWaitHandle(bool initialState, EventResetMode mode) : base(initialState, mode) {} public override Object InitializeLifetimeService() { return null; } } }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace Lucene.Net.Util { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// A pool for <see cref="int"/> blocks similar to <see cref="ByteBlockPool"/>. /// <para/> /// NOTE: This was IntBlockPool in Lucene /// <para/> /// @lucene.internal /// </summary> public sealed class Int32BlockPool { /// <summary> /// NOTE: This was INT_BLOCK_SHIFT in Lucene /// </summary> public static readonly int INT32_BLOCK_SHIFT = 13; /// <summary> /// NOTE: This was INT_BLOCK_SIZE in Lucene /// </summary> public static readonly int INT32_BLOCK_SIZE = 1 << INT32_BLOCK_SHIFT; /// <summary> /// NOTE: This was INT_BLOCK_MASK in Lucene /// </summary> public static readonly int INT32_BLOCK_MASK = INT32_BLOCK_SIZE - 1; /// <summary> /// Abstract class for allocating and freeing <see cref="int"/> /// blocks. /// </summary> public abstract class Allocator { protected readonly int m_blockSize; public Allocator(int blockSize) { this.m_blockSize = blockSize; } /// <summary> /// NOTE: This was recycleIntBlocks() in Lucene /// </summary> public abstract void RecycleInt32Blocks(int[][] blocks, int start, int end); /// <summary> /// NOTE: This was getIntBlock() in Lucene /// </summary> public virtual int[] GetInt32Block() { return new int[m_blockSize]; } } /// <summary> /// A simple <see cref="Allocator"/> that never recycles. </summary> public sealed class DirectAllocator : Allocator { /// <summary> /// Creates a new <see cref="DirectAllocator"/> with a default block size /// </summary> public DirectAllocator() : base(INT32_BLOCK_SIZE) { } /// <summary> /// NOTE: This was recycleIntBlocks() in Lucene /// </summary> public override void RecycleInt32Blocks(int[][] blocks, int start, int end) { } } /// <summary> /// Array of buffers currently used in the pool. Buffers are allocated if needed don't modify this outside of this class. </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public int[][] Buffers { get { return buffers; } set { buffers = value; } } private int[][] buffers = new int[10][]; /// <summary> /// Index into the buffers array pointing to the current buffer used as the head. </summary> private int bufferUpto = -1; /// <summary> /// Pointer to the current position in head buffer /// <para/> /// NOTE: This was intUpto in Lucene /// </summary> public int Int32Upto { get; set; } /// <summary> /// Current head buffer. </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public int[] Buffer { get { return buffer; } set { buffer = value; } } private int[] buffer; /// <summary> /// Current head offset. /// <para/> /// NOTE: This was intOffset in Lucene /// </summary> public int Int32Offset { get; set; } private readonly Allocator allocator; /// <summary> /// Creates a new <see cref="Int32BlockPool"/> with a default <see cref="Allocator"/>. </summary> /// <seealso cref="Int32BlockPool.NextBuffer()"/> public Int32BlockPool() : this(new DirectAllocator()) { } /// <summary> /// Creates a new <see cref="Int32BlockPool"/> with the given <see cref="Allocator"/>. </summary> /// <seealso cref="Int32BlockPool.NextBuffer()"/> public Int32BlockPool(Allocator allocator) { // set defaults Int32Upto = INT32_BLOCK_SIZE; Int32Offset = -INT32_BLOCK_SIZE; this.allocator = allocator; } /// <summary> /// Resets the pool to its initial state reusing the first buffer. Calling /// <see cref="Int32BlockPool.NextBuffer()"/> is not needed after reset. /// </summary> public void Reset() { this.Reset(true, true); } /// <summary> /// Expert: Resets the pool to its initial state reusing the first buffer. </summary> /// <param name="zeroFillBuffers"> If <c>true</c> the buffers are filled with <c>0</c>. /// this should be set to <c>true</c> if this pool is used with /// <see cref="SliceWriter"/>. </param> /// <param name="reuseFirst"> If <c>true</c> the first buffer will be reused and calling /// <see cref="Int32BlockPool.NextBuffer()"/> is not needed after reset if the /// block pool was used before ie. <see cref="Int32BlockPool.NextBuffer()"/> was called before. </param> public void Reset(bool zeroFillBuffers, bool reuseFirst) { if (bufferUpto != -1) { // We allocated at least one buffer if (zeroFillBuffers) { for (int i = 0; i < bufferUpto; i++) { // Fully zero fill buffers that we fully used Arrays.Fill(buffers[i], 0); } // Partial zero fill the final buffer Arrays.Fill(buffers[bufferUpto], 0, Int32Upto, 0); } if (bufferUpto > 0 || !reuseFirst) { int offset = reuseFirst ? 1 : 0; // Recycle all but the first buffer allocator.RecycleInt32Blocks(buffers, offset, 1 + bufferUpto); Arrays.Fill(buffers, offset, bufferUpto + 1, null); } if (reuseFirst) { // Re-use the first buffer bufferUpto = 0; Int32Upto = 0; Int32Offset = 0; buffer = buffers[0]; } else { bufferUpto = -1; Int32Upto = INT32_BLOCK_SIZE; Int32Offset = -INT32_BLOCK_SIZE; buffer = null; } } } /// <summary> /// Advances the pool to its next buffer. This method should be called once /// after the constructor to initialize the pool. In contrast to the /// constructor a <see cref="Int32BlockPool.Reset()"/> call will advance the pool to /// its first buffer immediately. /// </summary> public void NextBuffer() { if (1 + bufferUpto == buffers.Length) { int[][] newBuffers = new int[(int)(buffers.Length * 1.5)][]; Array.Copy(buffers, 0, newBuffers, 0, buffers.Length); buffers = newBuffers; } buffer = buffers[1 + bufferUpto] = allocator.GetInt32Block(); bufferUpto++; Int32Upto = 0; Int32Offset += INT32_BLOCK_SIZE; } /// <summary> /// Creates a new <see cref="int"/> slice with the given starting size and returns the slices offset in the pool. </summary> /// <seealso cref="SliceReader"/> private int NewSlice(int size) { if (Int32Upto > INT32_BLOCK_SIZE - size) { NextBuffer(); Debug.Assert(AssertSliceBuffer(buffer)); } int upto = Int32Upto; Int32Upto += size; buffer[Int32Upto - 1] = 1; return upto; } private static bool AssertSliceBuffer(int[] buffer) { int count = 0; for (int i = 0; i < buffer.Length; i++) { count += buffer[i]; // for slices the buffer must only have 0 values } return count == 0; } // no need to make this public unless we support different sizes // TODO make the levels and the sizes configurable /// <summary> /// An array holding the offset into the <see cref="Int32BlockPool.LEVEL_SIZE_ARRAY"/> /// to quickly navigate to the next slice level. /// </summary> private static readonly int[] NEXT_LEVEL_ARRAY = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 }; /// <summary> /// An array holding the level sizes for <see cref="int"/> slices. /// </summary> private static readonly int[] LEVEL_SIZE_ARRAY = new int[] { 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024 }; /// <summary> /// The first level size for new slices. /// </summary> private static readonly int FIRST_LEVEL_SIZE = LEVEL_SIZE_ARRAY[0]; /// <summary> /// Allocates a new slice from the given offset. /// </summary> private int AllocSlice(int[] slice, int sliceOffset) { int level = slice[sliceOffset]; int newLevel = NEXT_LEVEL_ARRAY[level - 1]; int newSize = LEVEL_SIZE_ARRAY[newLevel]; // Maybe allocate another block if (Int32Upto > INT32_BLOCK_SIZE - newSize) { NextBuffer(); Debug.Assert(AssertSliceBuffer(buffer)); } int newUpto = Int32Upto; int offset = newUpto + Int32Offset; Int32Upto += newSize; // Write forwarding address at end of last slice: slice[sliceOffset] = offset; // Write new level: buffer[Int32Upto - 1] = newLevel; return newUpto; } /// <summary> /// A <see cref="SliceWriter"/> that allows to write multiple integer slices into a given <see cref="Int32BlockPool"/>. /// <para/> /// @lucene.internal /// </summary> /// <seealso cref="SliceReader"/> public class SliceWriter { private int offset; private readonly Int32BlockPool pool; public SliceWriter(Int32BlockPool pool) { this.pool = pool; } /// public virtual void Reset(int sliceOffset) { this.offset = sliceOffset; } /// <summary> /// Writes the given value into the slice and resizes the slice if needed /// <para/> /// NOTE: This was writeInt() in Lucene /// </summary> public virtual void WriteInt32(int value) { int[] ints = pool.buffers[offset >> INT32_BLOCK_SHIFT]; Debug.Assert(ints != null); int relativeOffset = offset & INT32_BLOCK_MASK; if (ints[relativeOffset] != 0) { // End of slice; allocate a new one relativeOffset = pool.AllocSlice(ints, relativeOffset); ints = pool.buffer; offset = relativeOffset + pool.Int32Offset; } ints[relativeOffset] = value; offset++; } /// <summary> /// Starts a new slice and returns the start offset. The returned value /// should be used as the start offset to initialize a <see cref="SliceReader"/>. /// </summary> public virtual int StartNewSlice() { return offset = pool.NewSlice(FIRST_LEVEL_SIZE) + pool.Int32Offset; } /// <summary> /// Returns the offset of the currently written slice. The returned value /// should be used as the end offset to initialize a <see cref="SliceReader"/> once /// this slice is fully written or to reset the this writer if another slice /// needs to be written. /// </summary> public virtual int CurrentOffset { get { return offset; } } } /// <summary> /// A <see cref="SliceReader"/> that can read <see cref="int"/> slices written by a <see cref="SliceWriter"/>. /// <para/> /// @lucene.internal /// </summary> public sealed class SliceReader { private readonly Int32BlockPool pool; private int upto; private int bufferUpto; private int bufferOffset; private int[] buffer; private int limit; private int level; private int end; /// <summary> /// Creates a new <see cref="SliceReader"/> on the given pool. /// </summary> public SliceReader(Int32BlockPool pool) { this.pool = pool; } /// <summary> /// Resets the reader to a slice give the slices absolute start and end offset in the pool. /// </summary> public void Reset(int startOffset, int endOffset) { bufferUpto = startOffset / INT32_BLOCK_SIZE; bufferOffset = bufferUpto * INT32_BLOCK_SIZE; this.end = endOffset; upto = startOffset; level = 1; buffer = pool.buffers[bufferUpto]; upto = startOffset & INT32_BLOCK_MASK; int firstSize = Int32BlockPool.LEVEL_SIZE_ARRAY[0]; if (startOffset + firstSize >= endOffset) { // There is only this one slice to read limit = endOffset & INT32_BLOCK_MASK; } else { limit = upto + firstSize - 1; } } /// <summary> /// Returns <c>true</c> if the current slice is fully read. If this /// method returns <c>true</c> <seealso cref="SliceReader.ReadInt32()"/> should not /// be called again on this slice. /// </summary> public bool IsEndOfSlice { get { Debug.Assert(upto + bufferOffset <= end); return upto + bufferOffset == end; } } /// <summary> /// Reads the next <see cref="int"/> from the current slice and returns it. /// <para/> /// NOTE: This was readInt() in Lucene /// </summary> /// <seealso cref="SliceReader.IsEndOfSlice"/> public int ReadInt32() { Debug.Assert(!IsEndOfSlice); Debug.Assert(upto <= limit); if (upto == limit) { NextSlice(); } return buffer[upto++]; } private void NextSlice() { // Skip to our next slice int nextIndex = buffer[limit]; level = NEXT_LEVEL_ARRAY[level - 1]; int newSize = LEVEL_SIZE_ARRAY[level]; bufferUpto = nextIndex / INT32_BLOCK_SIZE; bufferOffset = bufferUpto * INT32_BLOCK_SIZE; buffer = pool.Buffers[bufferUpto]; upto = nextIndex & INT32_BLOCK_MASK; if (nextIndex + newSize >= end) { // We are advancing to the final slice Debug.Assert(end - nextIndex > 0); limit = end - bufferOffset; } else { // this is not the final slice (subtract 4 for the // forwarding address at the end of this new slice) limit = upto + newSize - 1; } } } } }
// Copyright (C) 2014 dot42 // // Original filename: WebRequest.cs // // 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 System.IO; using System.Net.Cache; using System.Net.Security; using System.Security.Principal; namespace System.Net { /// <summary> /// Makes a request to a Uniform Resource Identifier (URI). This is an abstract class. /// </summary> public abstract class WebRequest : MarshalByRefObject { private static readonly Dictionary<string, IWebRequestCreate> webRequestCreators = new Dictionary<string, IWebRequestCreate>(); static WebRequest() { IWebRequestCreate http = new HttpWebRequestCreator(); RegisterPrefix("http", http); RegisterPrefix("https", http); //TODO: ftp, file } /// <summary> /// Initializes a new instance of the System.Net.WebRequest class. /// </summary> protected WebRequest() { } /// <summary> /// Gets or sets values indicating the level of authentication and impersonation used for this request. /// </summary> public AuthenticationLevel AuthenticationLevel { get; set; } /// <summary> /// Gets or sets the cache policy for this request. /// </summary> public virtual RequestCachePolicy CachePolicy { get; set; } /// <summary> /// When overridden in a descendant class, gets or sets the name of the connection group for the request. /// </summary> public virtual string ConnectionGroupName { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, gets or sets the content length of the request data being sent. /// </summary> public virtual long ContentLength { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, gets or sets the content type of the request data being sent. /// </summary> public virtual string ContentType { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with the Internet resource. /// </summary> public virtual ICredentials Credentials { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the default cache policy for this request. /// </summary> public static RequestCachePolicy DefaultCachePolicy { get; set; } /// <summary> /// Gets or sets the global HTTP proxy. /// </summary> public static IWebProxy DefaultWebProxy { get; set; } /// <summary> /// When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the request. /// </summary> public virtual WebHeaderCollection Headers { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the impersonation level for the current request. /// </summary> public TokenImpersonationLevel ImpersonationLevel { get; set; } /// <summary> /// When overridden in a descendant class, gets or sets the protocol method to use in this request. /// </summary> public virtual string Method { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, indicates whether to pre-authenticate the request. /// </summary> public virtual bool PreAuthenticate { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource. /// </summary> public virtual IWebProxy Proxy { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, gets the URI of the Internet resource associated with the request. /// </summary> public virtual Uri RequestUri { get { throw new NotImplementedException(); } } /// <summary> /// Gets or sets the length of time, in milliseconds, before the request times out. /// </summary> public virtual int Timeout { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// When overridden in a descendant class, controls whether DefaultCredentials are sent with requests. /// </summary> public virtual bool UseDefaultCredentials { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// Aborts the Request /// </summary> public virtual void Abort() { throw new NotImplementedException(); } /// <summary> /// When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method. /// </summary> public virtual IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state) { throw new NotImplementedException(); } /// <summary> /// When overridden in a descendant class, begins an asynchronous request for an Internet resource. /// </summary> public virtual IAsyncResult BeginGetResponse(AsyncCallback callback, object state) { throw new NotImplementedException(); } /// <summary> /// Initializes a new WebRequest instance for the specified URI scheme. /// </summary> public static WebRequest Create(string requestUriString) { return Create(new Uri(requestUriString)); } /// <summary> /// Initializes a new WebRequest instance for the specified URI scheme. /// </summary> public static WebRequest Create(Uri requestUri) { return CreateDefault(requestUri); } /// <summary> /// Initializes a new HttpWebRequest instance for the specified URI scheme. /// </summary> public static HttpWebRequest CreateHttp(string requestUriString) { return CreateHttp(new Uri(requestUriString)); } /// <summary> /// Initializes a new HttpWebRequest instance for the specified URI scheme. /// </summary> public static HttpWebRequest CreateHttp(Uri requestUri) { return (HttpWebRequest)CreateDefault(requestUri); } /// <summary> /// Initializes a new System.Net.WebRequest instance for the specified URI scheme. /// </summary> /// <remarks> /// Only the scheme portion of the URI will be taken into account. /// </remarks> public static WebRequest CreateDefault(Uri requestUri) { var scheme = requestUri.Scheme.ToLower(); IWebRequestCreate creator; if (webRequestCreators.TryGetValue(scheme, out creator)) { return creator.Create(requestUri); } throw new NotSupportedException("The requested scheme is not registered"); } /// <summary> /// When overridden in a descendant class, returns a System.IO.Stream for writing data to the Internet resource. /// </summary> public virtual Stream EndGetRequestStream(IAsyncResult asyncResult) { throw new NotImplementedException(); } /// <summary> /// When overridden in a descendant class, returns a WebResponse. /// </summary> /// <param name="asyncResult"></param> /// <returns></returns> public virtual WebResponse EndGetResponse(IAsyncResult asyncResult) { throw new NotImplementedException(); } /// <summary> /// When overridden in a descendant class, returns a System.IO.Stream for writing data to the Internet resource. /// </summary> /// <returns></returns> public virtual Stream GetRequestStream() { throw new NotImplementedException(); } /// <summary> /// When overridden in a descendant class, returns a response to an Internet request. /// </summary> public virtual WebResponse GetResponse() { throw new NotImplementedException(); } /// <summary> /// Returns a proxy configured with the Internet Explorer settings of the currently impersonated user. /// </summary> /// <returns></returns> public static IWebProxy GetSystemWebProxy() { throw new NotImplementedException(); } /// <summary> /// Registers a WebRequest descendant for the specified URI. /// </summary> public static bool RegisterPrefix(string prefix, IWebRequestCreate creator) { prefix = prefix.ToLower(); if (webRequestCreators.ContainsKey(prefix)) return false; webRequestCreators.Add(prefix, creator); return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedModuloNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckLiftedModuloNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyModuloNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Helpers public static byte ModuloNullableByte(byte a, byte b) { return (byte)(a % b); } public static char ModuloNullableChar(char a, char b) { return (char)(a % b); } public static decimal ModuloNullableDecimal(decimal a, decimal b) { return (decimal)(a % b); } public static double ModuloNullableDouble(double a, double b) { return (double)(a % b); } public static float ModuloNullableFloat(float a, float b) { return (float)(a % b); } public static int ModuloNullableInt(int a, int b) { return (int)(a % b); } public static long ModuloNullableLong(long a, long b) { return (long)(a % b); } public static sbyte ModuloNullableSByte(sbyte a, sbyte b) { return (sbyte)(a % b); } public static short ModuloNullableShort(short a, short b) { return (short)(a % b); } public static uint ModuloNullableUInt(uint a, uint b) { return (uint)(a % b); } public static ulong ModuloNullableULong(ulong a, ulong b) { return (ulong)(a % b); } public static ushort ModuloNullableUShort(ushort a, ushort b) { return (ushort)(a % b); } #endregion #region Test verifiers private static void VerifyModuloNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.Modulo( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableByte"))); Func<byte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((byte?)(a % b), f()); } private static void VerifyModuloNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.Modulo( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableChar"))); Func<char?> f = e.Compile(useInterpreter); if (a.HasValue && b == '\0') Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((char?)(a % b), f()); } private static void VerifyModuloNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.Modulo( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDecimal"))); Func<decimal?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyModuloNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.Modulo( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableDouble"))); Func<double?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyModuloNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.Modulo( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableFloat"))); Func<float?> f = e.Compile(useInterpreter); Assert.Equal(a % b, f()); } private static void VerifyModuloNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.Modulo( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableInt"))); Func<int?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == int.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyModuloNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.Modulo( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableLong"))); Func<long?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else if (a == long.MinValue && b == -1) Assert.Throws<OverflowException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyModuloNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.Modulo( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableSByte"))); Func<sbyte?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((sbyte?)(a % b), f()); } private static void VerifyModuloNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.Modulo( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableShort"))); Func<short?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((short?)(a % b), f()); } private static void VerifyModuloNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.Modulo( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUInt"))); Func<uint?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyModuloNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.Modulo( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableULong"))); Func<ulong?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal(a % b, f()); } private static void VerifyModuloNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.Modulo( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedModuloNullableTests).GetTypeInfo().GetDeclaredMethod("ModuloNullableUShort"))); Func<ushort?> f = e.Compile(useInterpreter); if (a.HasValue && b == 0) Assert.Throws<DivideByZeroException>(() => f()); else Assert.Equal((ushort?)(a % b), f()); } #endregion } }
// Adler32.cs - Computes Adler32 data checksum of a data stream // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. #if ZIPLIB using System; namespace ICSharpCode.SharpZipLib.Checksums { /// <summary> /// Computes Adler32 checksum for a stream of data. An Adler32 /// checksum is not as reliable as a CRC32 checksum, but a lot faster to /// compute. /// /// The specification for Adler32 may be found in RFC 1950. /// ZLIB Compressed Data Format Specification version 3.3) /// /// /// From that document: /// /// "ADLER32 (Adler-32 checksum) /// This contains a checksum value of the uncompressed data /// (excluding any dictionary data) computed according to Adler-32 /// algorithm. This algorithm is a 32-bit extension and improvement /// of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 /// standard. /// /// Adler-32 is composed of two sums accumulated per byte: s1 is /// the sum of all bytes, s2 is the sum of all s1 values. Both sums /// are done modulo 65521. s1 is initialized to 1, s2 to zero. The /// Adler-32 checksum is stored as s2*65536 + s1 in most- /// significant-byte first (network) order." /// /// "8.2. The Adler-32 algorithm /// /// The Adler-32 algorithm is much faster than the CRC32 algorithm yet /// still provides an extremely low probability of undetected errors. /// /// The modulo on unsigned long accumulators can be delayed for 5552 /// bytes, so the modulo operation time is negligible. If the bytes /// are a, b, c, the second sum is 3a + 2b + c + 3, and so is position /// and order sensitive, unlike the first sum, which is just a /// checksum. That 65521 is prime is important to avoid a possible /// large class of two-byte errors that leave the check unchanged. /// (The Fletcher checksum uses 255, which is not prime and which also /// makes the Fletcher check insensitive to single byte changes 0 - /// 255.) /// /// The sum s1 is initialized to 1 instead of zero to make the length /// of the sequence part of s2, so that the length does not have to be /// checked separately. (Any sequence of zeroes has a Fletcher /// checksum of zero.)" /// </summary> /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream"/> /// <see cref="ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream"/> internal sealed class Adler32 : IChecksum { /// <summary> /// largest prime smaller than 65536 /// </summary> const uint BASE = 65521; /// <summary> /// Returns the Adler32 data checksum computed so far. /// </summary> public long Value { get { return checksum; } } /// <summary> /// Creates a new instance of the Adler32 class. /// The checksum starts off with a value of 1. /// </summary> public Adler32() { Reset(); } /// <summary> /// Resets the Adler32 checksum to the initial value. /// </summary> public void Reset() { checksum = 1; } /// <summary> /// Updates the checksum with a byte value. /// </summary> /// <param name="value"> /// The data value to add. The high byte of the int is ignored. /// </param> public void Update(int value) { // We could make a length 1 byte array and call update again, but I // would rather not have that overhead uint s1 = checksum & 0xFFFF; uint s2 = checksum >> 16; s1 = (s1 + ((uint)value & 0xFF)) % BASE; s2 = (s1 + s2) % BASE; checksum = (s2 << 16) + s1; } /// <summary> /// Updates the checksum with an array of bytes. /// </summary> /// <param name="buffer"> /// The source of the data to update with. /// </param> public void Update(byte[] buffer) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } Update(buffer, 0, buffer.Length); } /// <summary> /// Updates the checksum with the bytes taken from the array. /// </summary> /// <param name="buffer"> /// an array of bytes /// </param> /// <param name="offset"> /// the start of the data used for this update /// </param> /// <param name="count"> /// the number of bytes to use for this update /// </param> public void Update(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "cannot be negative"); #endif } if (offset >= buffer.Length) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer"); #endif } if (offset + count > buffer.Length) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "exceeds buffer size"); #endif } //(By Per Bothner) uint s1 = checksum & 0xFFFF; uint s2 = checksum >> 16; while (count > 0) { // We can defer the modulo operation: // s1 maximally grows from 65521 to 65521 + 255 * 3800 // s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31 int n = 3800; if (n > count) { n = count; } count -= n; while (--n >= 0) { s1 = s1 + (uint)(buffer[offset++] & 0xff); s2 = s2 + s1; } s1 %= BASE; s2 %= BASE; } checksum = (s2 << 16) | s1; } #region Instance Fields uint checksum; #endregion } } #endif
//----------------------------------------------------------------------- // <copyright file="BusinessBindingListBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>This is the base class from which most business collections</summary> //----------------------------------------------------------------------- #if NETFX_CORE || (ANDROID || IOS) using System; namespace Csla { /// <summary> /// This is the base class from which most business collections /// or lists will be derived. /// </summary> /// <typeparam name="T">Type of the business object being defined.</typeparam> /// <typeparam name="C">Type of the child objects contained in the list.</typeparam> #if TESTING [System.Diagnostics.DebuggerStepThrough] #endif [Serializable] public abstract class BusinessBindingListBase<T, C> : BusinessListBase<T, C> where T : BusinessBindingListBase<T, C> where C : Csla.Core.IEditableBusinessObject { } } #else using System; using System.ComponentModel; using System.Collections.Generic; using Csla.Properties; using Csla.Core; using System.Threading.Tasks; namespace Csla { /// <summary> /// This is the base class from which most business collections /// or lists will be derived. /// </summary> /// <typeparam name="T">Type of the business object being defined.</typeparam> /// <typeparam name="C">Type of the child objects contained in the list.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [Serializable()] public abstract class BusinessBindingListBase<T, C> : Core.ExtendedBindingList<C>, Core.IEditableCollection, ICloneable, Core.ISavable, Core.ISavable<T>, Core.IParent, Server.IDataPortalTarget, INotifyBusy where T : BusinessBindingListBase<T, C> where C : Core.IEditableBusinessObject { #region Constructors /// <summary> /// Creates an instance of the object. /// </summary> protected BusinessBindingListBase() { InitializeIdentity(); Initialize(); this.AllowNew = true; } #endregion #region Initialize /// <summary> /// Override this method to set up event handlers so user /// code in a partial class can respond to events raised by /// generated code. /// </summary> protected virtual void Initialize() { /* allows subclass to initialize events before any other activity occurs */ } #endregion #region Identity private int _identity = -1; int IBusinessObject.Identity { get { return _identity; } } private void InitializeIdentity() { _identity = ((IParent)this).GetNextIdentity(_identity); } [NonSerialized] [NotUndoable] private IdentityManager _identityManager; int IParent.GetNextIdentity(int current) { if (this.Parent != null) { return this.Parent.GetNextIdentity(current); } else { if (_identityManager == null) _identityManager = new IdentityManager(); return _identityManager.GetNextIdentity(current); } } #endregion #region IsDirty, IsValid, IsSavable /// <summary> /// Gets a value indicating whether this object's data has been changed. /// </summary> bool Core.ITrackStatus.IsSelfDirty { get { return IsDirty; } } /// <summary> /// Gets a value indicating whether this object's data has been changed. /// </summary> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public bool IsDirty { get { // any non-new deletions make us dirty foreach (C item in DeletedList) if (!item.IsNew) return true; // run through all the child objects // and if any are dirty then then // collection is dirty foreach (C child in this) if (child.IsDirty) return true; return false; } } bool Core.ITrackStatus.IsSelfValid { get { return IsSelfValid; } } /// <summary> /// Gets a value indicating whether this object is currently in /// a valid state (has no broken validation rules). /// </summary> protected virtual bool IsSelfValid { get { return IsValid; } } /// <summary> /// Gets a value indicating whether this object is currently in /// a valid state (has no broken validation rules). /// </summary> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public virtual bool IsValid { get { // run through all the child objects // and if any are invalid then the // collection is invalid foreach (C child in this) if (!child.IsValid) return false; return true; } } /// <summary> /// Returns true if this object is both dirty and valid. /// </summary> /// <returns>A value indicating if this object is both dirty and valid.</returns> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] public virtual bool IsSavable { get { bool auth = Csla.Rules.BusinessRules.HasPermission(Rules.AuthorizationActions.EditObject, this); return (IsDirty && IsValid && auth && !IsBusy); } } #endregion #region Delete and Undelete child private MobileList<C> _deletedList; /// <summary> /// A collection containing all child objects marked /// for deletion. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1002:DoNotExposeGenericLists")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected MobileList<C> DeletedList { get { if (_deletedList == null) _deletedList = new MobileList<C>(); return _deletedList; } } private void DeleteChild(C child) { // mark the object as deleted child.DeleteChild(); // and add it to the deleted collection for storage DeletedList.Add(child); } private void UnDeleteChild(C child) { // since the object is no longer deleted, remove it from // the deleted collection DeletedList.Remove(child); Add(child); } /// <summary> /// Returns true if the internal deleted list /// contains the specified child object. /// </summary> /// <param name="item">Child object to check.</param> [EditorBrowsable(EditorBrowsableState.Advanced)] public bool ContainsDeleted(C item) { return DeletedList.Contains(item); } #endregion #region Insert, Remove, Clear /// <summary> /// Override this method to create a new object that is added /// to the collection. /// </summary> protected override object AddNewCore() { var item = DataPortal.CreateChild<C>(); Add(item); return item; } /// <summary> /// This method is called by a child object when it /// wants to be removed from the collection. /// </summary> /// <param name="child">The child object to remove.</param> void Core.IEditableCollection.RemoveChild(Csla.Core.IEditableBusinessObject child) { Remove((C)child); } object IEditableCollection.GetDeletedList() { return DeletedList; } /// <summary> /// This method is called by a child object when it /// wants to be removed from the collection. /// </summary> /// <param name="child">The child object to remove.</param> void Core.IParent.RemoveChild(Csla.Core.IEditableBusinessObject child) { Remove((C)child); } /// <summary> /// Sets the edit level of the child object as it is added. /// </summary> /// <param name="index">Index of the item to insert.</param> /// <param name="item">Item to insert.</param> protected override void InsertItem(int index, C item) { // set parent reference item.SetParent(this); base.InsertItem(index, item); } private bool _completelyRemoveChild; /// <summary> /// Marks the child object for deletion and moves it to /// the collection of deleted objects. /// </summary> /// <param name="index">Index of the item to remove.</param> protected override void RemoveItem(int index) { // when an object is 'removed' it is really // being deleted, so do the deletion work C child = this[index]; bool oldRaiseListChangedEvents = this.RaiseListChangedEvents; try { this.RaiseListChangedEvents = false; base.RemoveItem(index); } finally { this.RaiseListChangedEvents = oldRaiseListChangedEvents; } if (!_completelyRemoveChild) { // the child shouldn't be completely removed, // so copy it to the deleted list DeleteChild(child); } if (RaiseListChangedEvents) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemDeleted, index)); } /// <summary> /// Clears the collection, moving all active /// items to the deleted list. /// </summary> protected override void ClearItems() { while (base.Count > 0) RemoveItem(0); base.ClearItems(); } /// <summary> /// Replaces the item at the specified index with /// the specified item, first moving the original /// item to the deleted list. /// </summary> /// <param name="index">The zero-based index of the item to replace.</param> /// <param name="item"> /// The new value for the item at the specified index. /// The value can be null for reference types. /// </param> /// <remarks></remarks> protected override void SetItem(int index, C item) { C child = default(C); if (!(ReferenceEquals((C)(this[index]), item))) child = this[index]; // replace the original object with this new // object bool oldRaiseListChangedEvents = this.RaiseListChangedEvents; try { this.RaiseListChangedEvents = false; // set parent reference item.SetParent(this); // add to list base.SetItem(index, item); } finally { this.RaiseListChangedEvents = oldRaiseListChangedEvents; } if (child != null) DeleteChild(child); if (RaiseListChangedEvents) OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, index)); } #endregion #region Cascade child events /// <summary> /// Handles any PropertyChanged event from /// a child object and echoes it up as /// a ListChanged event. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected override void Child_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (_deserialized && RaiseListChangedEvents && e != null) { for (int index = 0; index < Count; index++) { if (ReferenceEquals(this[index], sender)) { PropertyDescriptor descriptor = GetPropertyDescriptor(e.PropertyName); if (descriptor != null) OnListChanged(new ListChangedEventArgs( ListChangedType.ItemChanged, index, descriptor)); else OnListChanged(new ListChangedEventArgs( ListChangedType.ItemChanged, index)); } } } base.Child_PropertyChanged(sender, e); } private static PropertyDescriptorCollection _propertyDescriptors; private PropertyDescriptor GetPropertyDescriptor(string propertyName) { if (_propertyDescriptors == null) _propertyDescriptors = TypeDescriptor.GetProperties(typeof(C)); PropertyDescriptor result = null; foreach (PropertyDescriptor desc in _propertyDescriptors) if (desc.Name == propertyName) { result = desc; break; } return result; } #endregion #region IsChild [NotUndoable()] private bool _isChild = false; /// <summary> /// Indicates whether this collection object is a child object. /// </summary> /// <returns>True if this is a child object.</returns> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public bool IsChild { get { return _isChild; } } /// <summary> /// Marks the object as being a child object. /// </summary> /// <remarks> /// <para> /// By default all business objects are 'parent' objects. This means /// that they can be directly retrieved and updated into the database. /// </para><para> /// We often also need child objects. These are objects which are contained /// within other objects. For instance, a parent Invoice object will contain /// child LineItem objects. /// </para><para> /// To create a child object, the MarkAsChild method must be called as the /// object is created. Please see Chapter 7 for details on the use of the /// MarkAsChild method. /// </para> /// </remarks> protected void MarkAsChild() { _identity = -1; _isChild = true; } #endregion #region ICloneable object ICloneable.Clone() { return GetClone(); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns>A new object containing the exact data of the original object.</returns> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual object GetClone() { return Core.ObjectCloner.Clone(this); } /// <summary> /// Creates a clone of the object. /// </summary> /// <returns>A new object containing the exact data of the original object.</returns> public T Clone() { return (T)GetClone(); } #endregion #region Serialization Notification [NonSerialized] [NotUndoable] private bool _deserialized = false; /// <summary> /// This method is called on a newly deserialized object /// after deserialization is complete. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnDeserialized() { _deserialized = true; base.OnDeserialized(); foreach (Core.IEditableBusinessObject child in this) { child.SetParent(this); } foreach (Core.IEditableBusinessObject child in DeletedList) child.SetParent(this); } #endregion #region Child Data Access /// <summary> /// Initializes a new instance of the object /// with default values. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void Child_Create() { /* do nothing - list self-initializes */ } /// <summary> /// Saves all items in the list, automatically /// performing insert, update or delete operations /// as necessary. /// </summary> /// <param name="parameters"> /// Optional parameters passed to child update /// methods. /// </param> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void Child_Update(params object[] parameters) { var oldRLCE = this.RaiseListChangedEvents; this.RaiseListChangedEvents = false; try { foreach (var child in DeletedList) DataPortal.UpdateChild(child, parameters); DeletedList.Clear(); foreach (var child in this) if (child.IsDirty) DataPortal.UpdateChild(child, parameters); } finally { this.RaiseListChangedEvents = oldRLCE; } } #endregion #region Data Access /// <summary> /// Saves the object to the database. /// </summary> /// <remarks> /// <para> /// Calling this method starts the save operation, causing the all child /// objects to be inserted, updated or deleted within the database based on the /// each object's current state. /// </para><para> /// All this is contingent on <see cref="IsDirty" />. If /// this value is false, no data operation occurs. /// It is also contingent on <see cref="IsValid" />. If this value is /// false an exception will be thrown to /// indicate that the UI attempted to save an invalid object. /// </para><para> /// It is important to note that this method returns a new version of the /// business collection that contains any data updated during the save operation. /// You MUST update all object references to use this new version of the /// business collection in order to have access to the correct object data. /// </para><para> /// You can override this method to add your own custom behaviors to the save /// operation. For instance, you may add some security checks to make sure /// the user can save the object. If all security checks pass, you would then /// invoke the base Save method via <c>MyBase.Save()</c>. /// </para> /// </remarks> /// <returns>A new object containing the saved values.</returns> public T Save() { try { return SaveAsync(null, true).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 0) throw ex.InnerExceptions[0]; else throw; } } /// <summary> /// Saves the object to the database. /// </summary> public async Task<T> SaveAsync() { return await SaveAsync(null, false); } /// <summary> /// Saves the object to the database. /// </summary> /// <param name="userState">User state data.</param> /// <param name="isSync">True if the save operation should be synchronous.</param> protected virtual async Task<T> SaveAsync(object userState, bool isSync) { T result; if (this.IsChild) throw new InvalidOperationException(Resources.NoSaveChildException); if (!IsValid) throw new Rules.ValidationException(Resources.NoSaveInvalidException); if (IsBusy) throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved); if (IsDirty) { if (isSync) { result = DataPortal.Update<T>((T)this); } else { result = await DataPortal.UpdateAsync<T>((T)this); } } else { result = (T)this; } OnSaved(result, null, userState); return result; } /// <summary> /// Starts an async operation to save the object to the database. /// </summary> public void BeginSave() { BeginSave(null, null); } /// <summary> /// Starts an async operation to save the object to the database. /// </summary> /// <param name="userState">User state object.</param> public void BeginSave(object userState) { BeginSave(null, userState); } /// <summary> /// Starts an async operation to save the object to the database. /// </summary> /// <param name="handler"> /// Method called when the operation is complete. /// </param> public void BeginSave(EventHandler<SavedEventArgs> handler) { BeginSave(handler, null); } /// <summary> /// Starts an async operation to save the object to the database. /// </summary> /// <param name="handler"> /// Method called when the operation is complete. /// </param> /// <param name="userState">User state object.</param> public async void BeginSave(EventHandler<SavedEventArgs> handler, object userState) { T result = default(T); Exception error = null; try { result = await SaveAsync(userState, false); } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 0) error = ex.InnerExceptions[0]; else error = ex; } catch (Exception ex) { error = ex; } if (handler != null) handler(this, new SavedEventArgs(result, error, userState)); } /// <summary> /// Override this method to load a new business object with default /// values from the database. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Create() { } /// <summary> /// Override this method to allow retrieval of an existing business /// object based on data in the database. /// </summary> /// <param name="criteria">An object containing criteria values to identify the object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Fetch(object criteria) { throw new NotSupportedException(Resources.FetchNotSupportedException); } /// <summary> /// Override this method to allow update of a business /// object. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Update() { throw new NotSupportedException(Resources.UpdateNotSupportedException); } /// <summary> /// Override this method to allow immediate deletion of a business object. /// </summary> /// <param name="criteria">An object containing criteria values to identify the object.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] protected virtual void DataPortal_Delete(object criteria) { throw new NotSupportedException(Resources.DeleteNotSupportedException); } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_xyz method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during data access. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during data access.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } /// <summary> /// Called by the server-side DataPortal prior to calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void Child_OnDataPortalInvoke(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal after calling the /// requested DataPortal_XYZ method. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { } /// <summary> /// Called by the server-side DataPortal if an exception /// occurs during data access. /// </summary> /// <param name="e">The DataPortalContext object passed to the DataPortal.</param> /// <param name="ex">The Exception thrown during data access.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", MessageId = "Member")] [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { } #endregion #region ISavable Members #if !(ANDROID || IOS) && !NETFX_CORE object Csla.Core.ISavable.Save() { return Save(); } object Csla.Core.ISavable.Save(bool forceUpdate) { return Save(); } #endif async Task<object> ISavable.SaveAsync() { return await SaveAsync(); } async Task<object> ISavable.SaveAsync(bool forceUpdate) { return await SaveAsync(); } void Csla.Core.ISavable.SaveComplete(object newObject) { OnSaved((T)newObject, null, null); } #if !(ANDROID || IOS) && !NETFX_CORE T Csla.Core.ISavable<T>.Save(bool forceUpdate) { return Save(); } #endif async Task<T> ISavable<T>.SaveAsync(bool forceUpdate) { return await SaveAsync(); } void Csla.Core.ISavable<T>.SaveComplete(T newObject) { OnSaved(newObject, null, null); } [NonSerialized()] [NotUndoable] private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers; [NotUndoable] private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers; /// <summary> /// Event raised when an object has been saved. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event EventHandler<Csla.Core.SavedEventArgs> Saved { add { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Combine(_serializableSavedHandlers, value); else _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Combine(_nonSerializableSavedHandlers, value); } remove { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Remove(_serializableSavedHandlers, value); else _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Remove(_nonSerializableSavedHandlers, value); } } /// <summary> /// Raises the <see cref="Saved"/> event, indicating that the /// object has been saved, and providing a reference /// to the new object instance. /// </summary> /// <param name="newObject">The new object instance.</param> /// <param name="e">Execption that occurred during the operation.</param> /// <param name="userState">User state object.</param> [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnSaved(T newObject, Exception e, object userState) { Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, userState); if (_nonSerializableSavedHandlers != null) _nonSerializableSavedHandlers.Invoke(this, args); if (_serializableSavedHandlers != null) _serializableSavedHandlers.Invoke(this, args); } #endregion #region Parent/Child link [NotUndoable(), NonSerialized()] private Core.IParent _parent; /// <summary> /// Provide access to the parent reference for use /// in child object code. /// </summary> /// <remarks> /// This value will be Nothing for root objects. /// </remarks> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] [EditorBrowsable(EditorBrowsableState.Advanced)] public Core.IParent Parent { get { return _parent; } } /// <summary> /// Used by BusinessListBase as a child object is /// created to tell the child object about its /// parent. /// </summary> /// <param name="parent">A reference to the parent collection object.</param> protected virtual void SetParent(Core.IParent parent) { _parent = parent; _identityManager = null; InitializeIdentity(); } /// <summary> /// Used by BusinessListBase as a child object is /// created to tell the child object about its /// parent. /// </summary> /// <param name="parent">A reference to the parent collection object.</param> void Core.IEditableCollection.SetParent(Core.IParent parent) { this.SetParent(parent); } #endregion #region ToArray /// <summary> /// Get an array containing all items in the list. /// </summary> public C[] ToArray() { List<C> result = new List<C>(); foreach (C item in this) result.Add(item); return result.ToArray(); } #endregion #region ITrackStatus bool Core.ITrackStatus.IsNew { get { return false; } } bool Core.ITrackStatus.IsDeleted { get { return false; } } /// <summary> /// Gets the busy status for this object and its child objects. /// </summary> [Browsable(false)] [System.ComponentModel.DataAnnotations.Display(AutoGenerateField = false)] [System.ComponentModel.DataAnnotations.ScaffoldColumn(false)] public override bool IsBusy { get { // any non-new deletions make us dirty foreach (C item in DeletedList) if (item.IsBusy) return true; // run through all the child objects // and if any are dirty then then // collection is dirty foreach (C child in this) if (child.IsBusy) return true; return false; } } #endregion #region IDataPortalTarget Members void Csla.Server.IDataPortalTarget.CheckRules() { } void Csla.Server.IDataPortalTarget.MarkAsChild() { this.MarkAsChild(); } void Csla.Server.IDataPortalTarget.MarkNew() { } void Csla.Server.IDataPortalTarget.MarkOld() { } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvoke(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvoke(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.DataPortal_OnDataPortalInvokeComplete(e); } void Csla.Server.IDataPortalTarget.DataPortal_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.DataPortal_OnDataPortalException(e, ex); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvoke(DataPortalEventArgs e) { this.Child_OnDataPortalInvoke(e); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalInvokeComplete(DataPortalEventArgs e) { this.Child_OnDataPortalInvokeComplete(e); } void Csla.Server.IDataPortalTarget.Child_OnDataPortalException(DataPortalEventArgs e, Exception ex) { this.Child_OnDataPortalException(e, ex); } #endregion #region Mobile object overrides /// <summary> /// Override this method to retrieve your field values /// from the MobileFormatter serialzation stream. /// </summary> /// <param name="info"> /// Object containing the data to serialize. /// </param> [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnSetState(Csla.Serialization.Mobile.SerializationInfo info) { _isChild = info.GetValue<bool>("Csla.BusinessListBase._isChild"); _identity = info.GetValue<int>("Csla.Core.BusinessBase._identity"); base.OnSetState(info); } /// <summary> /// Override this method to insert your field values /// into the MobileFormatter serialzation stream. /// </summary> /// <param name="info"> /// Object containing the data to serialize. /// </param> [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnGetState(Csla.Serialization.Mobile.SerializationInfo info) { info.AddValue("Csla.BusinessListBase._isChild", _isChild); info.AddValue("Csla.Core.BusinessBase._identity", _identity); base.OnGetState(info); } /// <summary> /// Override this method to insert child objects /// into the MobileFormatter serialization stream. /// </summary> /// <param name="info"> /// Object containing the data to serialize. /// </param> /// <param name="formatter"> /// Reference to the current MobileFormatter. /// </param> [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnGetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter) { base.OnGetChildren(info, formatter); if (_deletedList != null) { var fieldManagerInfo = formatter.SerializeObject(_deletedList); info.AddChild("_deletedList", fieldManagerInfo.ReferenceId); } } /// <summary> /// Override this method to get child objects /// from the MobileFormatter serialization stream. /// </summary> /// <param name="info"> /// Object containing the serialized data. /// </param> /// <param name="formatter"> /// Reference to the current MobileFormatter. /// </param> [System.ComponentModel.EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnSetChildren(Csla.Serialization.Mobile.SerializationInfo info, Csla.Serialization.Mobile.MobileFormatter formatter) { if (info.Children.ContainsKey("_deletedList")) { var childData = info.Children["_deletedList"]; _deletedList = (MobileList<C>)formatter.GetObject(childData.ReferenceId); } base.OnSetChildren(info, formatter); } #endregion } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Umbraco.Core.Auditing; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; using umbraco.interfaces; namespace Umbraco.Core.Services { /// <summary> /// Represents the DataType Service, which is an easy access to operations involving <see cref="IDataType"/> and <see cref="IDataTypeDefinition"/> /// </summary> public class DataTypeService : IDataTypeService { private readonly RepositoryFactory _repositoryFactory; private readonly IDatabaseUnitOfWorkProvider _uowProvider; private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); public DataTypeService() : this(new RepositoryFactory()) {} public DataTypeService(RepositoryFactory repositoryFactory) : this(new PetaPocoUnitOfWorkProvider(), repositoryFactory) { } public DataTypeService(IDatabaseUnitOfWorkProvider provider) : this(provider, new RepositoryFactory()) { } public DataTypeService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory) { _repositoryFactory = repositoryFactory; _uowProvider = provider; } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its Id /// </summary> /// <param name="id">Id of the <see cref="IDataTypeDefinition"/></param> /// <returns><see cref="IDataTypeDefinition"/></returns> public IDataTypeDefinition GetDataTypeDefinitionById(int id) { using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(_uowProvider.GetUnitOfWork())) { return repository.Get(id); } } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its unique guid Id /// </summary> /// <param name="id">Unique guid Id of the DataType</param> /// <returns><see cref="IDataTypeDefinition"/></returns> public IDataTypeDefinition GetDataTypeDefinitionById(Guid id) { using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(_uowProvider.GetUnitOfWork())) { var query = Query<IDataTypeDefinition>.Builder.Where(x => x.Key == id); var definitions = repository.GetByQuery(query); return definitions.FirstOrDefault(); } } /// <summary> /// Gets a <see cref="IDataTypeDefinition"/> by its control Id /// </summary> /// <param name="id">Id of the DataType control</param> /// <returns>Collection of <see cref="IDataTypeDefinition"/> objects with a matching contorl id</returns> public IEnumerable<IDataTypeDefinition> GetDataTypeDefinitionByControlId(Guid id) { using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(_uowProvider.GetUnitOfWork())) { var query = Query<IDataTypeDefinition>.Builder.Where(x => x.ControlId == id); var definitions = repository.GetByQuery(query); return definitions; } } /// <summary> /// Gets all <see cref="IDataTypeDefinition"/> objects or those with the ids passed in /// </summary> /// <param name="ids">Optional array of Ids</param> /// <returns>An enumerable list of <see cref="IDataTypeDefinition"/> objects</returns> public IEnumerable<IDataTypeDefinition> GetAllDataTypeDefinitions(params int[] ids) { using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(_uowProvider.GetUnitOfWork())) { return repository.GetAll(ids); } } /// <summary> /// Gets all prevalues for an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="id">Id of the <see cref="IDataTypeDefinition"/> to retrieve prevalues from</param> /// <returns>An enumerable list of string values</returns> public IEnumerable<string> GetPreValuesByDataTypeId(int id) { using (var uow = _uowProvider.GetUnitOfWork()) { var dtos = uow.Database.Fetch<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new {Id = id}); var list = dtos.Select(x => x.Value).ToList(); return list; } } /// <summary> /// Gets all prevalues for an <see cref="IDataTypeDefinition"/> /// </summary> /// <remarks> /// This method should be kept internal until a proper PreValue object model is introduced. /// </remarks> /// <param name="id">Id of the <see cref="IDataTypeDefinition"/> to retrieve prevalues from</param> /// <returns>An enumerable list of Tuples containing Id, Alias, SortOrder, Value</returns> internal IEnumerable<Tuple<int, string, int, string>> GetDetailedPreValuesByDataTypeId(int id) { using (var uow = _uowProvider.GetUnitOfWork()) { var dtos = uow.Database.Fetch<DataTypePreValueDto>("WHERE datatypeNodeId = @Id", new { Id = id }); var list = dtos.Select(x => new Tuple<int, string, int, string>(x.Id, x.Alias, x.SortOrder, x.Value)).ToList(); return list; } } /// <summary> /// Gets a specific PreValue by its Id /// </summary> /// <param name="id">Id of the PreValue to retrieve the value from</param> /// <returns>PreValue as a string</returns> public string GetPreValueAsString(int id) { using (var uow = _uowProvider.GetUnitOfWork()) { var dto = uow.Database.FirstOrDefault<DataTypePreValueDto>("WHERE id = @Id", new { Id = id }); return dto != null ? dto.Value : string.Empty; } } /// <summary> /// Saves an <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow)) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } } Audit.Add(AuditTypes.Save, string.Format("Save DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); } /// <summary> /// Saves a collection of <see cref="IDataTypeDefinition"/> /// </summary> /// <param name="dataTypeDefinitions"><see cref="IDataTypeDefinition"/> to save</param> /// <param name="userId">Id of the user issueing the save</param> public void Save(IEnumerable<IDataTypeDefinition> dataTypeDefinitions, int userId = 0) { if (Saving.IsRaisedEventCancelled(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions), this)) return; using (new WriteLock(Locker)) { var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow)) { foreach (var dataTypeDefinition in dataTypeDefinitions) { dataTypeDefinition.CreatorId = userId; repository.AddOrUpdate(dataTypeDefinition); } uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<IDataTypeDefinition>(dataTypeDefinitions, false), this); } } Audit.Add(AuditTypes.Save, string.Format("Save DataTypeDefinition performed by user"), userId, -1); } /// <summary> /// Saves a list of PreValues for a given DataTypeDefinition /// </summary> /// <param name="id">Id of the DataTypeDefinition to save PreValues for</param> /// <param name="values">List of string values to save</param> public void SavePreValues(int id, IEnumerable<string> values) { using (new WriteLock(Locker)) { using (var uow = _uowProvider.GetUnitOfWork()) { var sortOrderObj = uow.Database.ExecuteScalar<object>( "SELECT max(sortorder) FROM cmsDataTypePreValues WHERE datatypeNodeId = @DataTypeId", new { DataTypeId = id }); int sortOrder; if (sortOrderObj == null || int.TryParse(sortOrderObj.ToString(), out sortOrder) == false) { sortOrder = 1; } using (var transaction = uow.Database.GetTransaction()) { foreach (var value in values) { var dto = new DataTypePreValueDto { DataTypeNodeId = id, Value = value, SortOrder = sortOrder }; uow.Database.Insert(dto); sortOrder++; } transaction.Complete(); } } } } /// <summary> /// Deletes an <see cref="IDataTypeDefinition"/> /// </summary> /// <remarks> /// Please note that deleting a <see cref="IDataTypeDefinition"/> will remove /// all the <see cref="PropertyType"/> data that references this <see cref="IDataTypeDefinition"/>. /// </remarks> /// <param name="dataTypeDefinition"><see cref="IDataTypeDefinition"/> to delete</param> /// <param name="userId">Optional Id of the user issueing the deletion</param> public void Delete(IDataTypeDefinition dataTypeDefinition, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition), this)) return; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateContentTypeRepository(uow)) { //Find ContentTypes using this IDataTypeDefinition on a PropertyType var query = Query<PropertyType>.Builder.Where(x => x.DataTypeDefinitionId == dataTypeDefinition.Id); var contentTypes = repository.GetByQuery(query); //Loop through the list of results and remove the PropertyTypes that references the DataTypeDefinition that is being deleted foreach (var contentType in contentTypes) { if (contentType == null) continue; foreach (var group in contentType.PropertyGroups) { var types = @group.PropertyTypes.Where(x => x.DataTypeDefinitionId == dataTypeDefinition.Id).ToList(); foreach (var propertyType in types) { @group.PropertyTypes.Remove(propertyType); } } repository.AddOrUpdate(contentType); } var dataTypeRepository = _repositoryFactory.CreateDataTypeDefinitionRepository(uow); dataTypeRepository.Delete(dataTypeDefinition); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IDataTypeDefinition>(dataTypeDefinition, false), this); } Audit.Add(AuditTypes.Delete, string.Format("Delete DataTypeDefinition performed by user"), userId, dataTypeDefinition.Id); } /// <summary> /// Gets the <see cref="IDataType"/> specified by it's unique ID /// </summary> /// <param name="id">Id of the DataType, which corresponds to the Guid Id of the control</param> /// <returns><see cref="IDataType"/> object</returns> public IDataType GetDataTypeById(Guid id) { return DataTypesResolver.Current.GetById(id); } /// <summary> /// Gets a complete list of all registered <see cref="IDataType"/>'s /// </summary> /// <returns>An enumerable list of <see cref="IDataType"/> objects</returns> public IEnumerable<IDataType> GetAllDataTypes() { return DataTypesResolver.Current.DataTypes; } #region Event Handlers /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IDataTypeService, DeleteEventArgs<IDataTypeDefinition>> Deleted; /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IDataTypeService, SaveEventArgs<IDataTypeDefinition>> Saved; #endregion } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; namespace OpenQA.Selenium { [TestFixture] public class FormHandlingTests : DriverTestFixture { [Test] public void ShouldClickOnSubmitInputElements() { driver.Url = formsPage; driver.FindElement(By.Id("submitButton")).Click(); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ClickingOnUnclickableElementsDoesNothing() { driver.Url = formsPage; driver.FindElement(By.XPath("//body")).Click(); } [Test] public void ShouldBeAbleToClickImageButtons() { driver.Url = formsPage; driver.FindElement(By.Id("imageButton")).Click(); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldBeAbleToSubmitForms() { driver.Url = formsPage; driver.FindElement(By.Name("login")).Submit(); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyInputElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.Id("checky")).Submit(); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] public void ShouldSubmitAFormWhenAnyElementWithinThatFormIsSubmitted() { driver.Url = formsPage; driver.FindElement(By.XPath("//form/p")).Submit(); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual(driver.Title, "We Arrive Here"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotBeAbleToSubmitAFormThatDoesNotExist() { driver.Url = formsPage; driver.FindElement(By.Name("there is no spoon")).Submit(); } [Test] public void ShouldBeAbleToEnterTextIntoATextAreaBySettingItsValue() { driver.Url = javascriptPage; IWebElement textarea = driver.FindElement(By.Id("keyUpArea")); String cheesey = "Brie and cheddar"; textarea.SendKeys(cheesey); Assert.AreEqual(textarea.GetAttribute("value"), cheesey); } [Test] public void ShouldSubmitAFormUsingTheNewlineLiteral() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys("\n"); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldSubmitAFormUsingTheEnterKey() { driver.Url = formsPage; IWebElement nestedForm = driver.FindElement(By.Id("nested_form")); IWebElement input = nestedForm.FindElement(By.Name("x")); input.SendKeys(Keys.Enter); WaitFor(TitleToBe("We Arrive Here")); Assert.AreEqual("We Arrive Here", driver.Title); Assert.IsTrue(driver.Url.EndsWith("?x=name")); } [Test] public void ShouldEnterDataIntoFormFields() { driver.Url = xhtmlTestPage; IWebElement element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String originalValue = element.GetAttribute("value"); Assert.AreEqual(originalValue, "change"); element.Clear(); element.SendKeys("some text"); element = driver.FindElement(By.XPath("//form[@name='someForm']/input[@id='username']")); String newFormValue = element.GetAttribute("value"); Assert.AreEqual(newFormValue, "some text"); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] public void ShouldBeAbleToAlterTheContentsOfAFileUploadInputElement() { driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); uploadElement.SendKeys(inputFile.FullName); System.IO.FileInfo outputFile = new System.IO.FileInfo(uploadElement.GetAttribute("value")); Assert.AreEqual(inputFile.Name, outputFile.Name); inputFile.Delete(); } [Test] [IgnoreBrowser(Browser.Android, "Does not yet support file uploads")] [IgnoreBrowser(Browser.IPhone, "Does not yet support file uploads")] [IgnoreBrowser(Browser.Safari, "Does not yet support file uploads")] public void ShouldBeAbleToUploadTheSameFileTwice() { System.IO.FileInfo inputFile = new System.IO.FileInfo("test.txt"); System.IO.StreamWriter inputFileWriter = inputFile.CreateText(); inputFileWriter.WriteLine("Hello world"); inputFileWriter.Close(); driver.Url = formsPage; IWebElement uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); driver.Url = formsPage; uploadElement = driver.FindElement(By.Id("upload")); Assert.IsTrue(string.IsNullOrEmpty(uploadElement.GetAttribute("value"))); uploadElement.SendKeys(inputFile.FullName); uploadElement.Submit(); // If we get this far, then we're all good. } [Test] public void SendingKeyboardEventsShouldAppendTextInInputs() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Some"); element.SendKeys(" text"); value = element.GetAttribute("value"); Assert.AreEqual(value, "Some text"); } [Test] public void SendingKeyboardEventsShouldAppendTextInInputsWithExistingValue() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("inputWithText")); element.SendKeys(". Some text"); string value = element.GetAttribute("value"); Assert.AreEqual("Example text. Some text", value); } [Test] [IgnoreBrowser(Browser.HtmlUnit, "Not implemented going to the end of the line first")] public void SendingKeyboardEventsShouldAppendTextInTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys(". Some text"); String value = element.GetAttribute("value"); Assert.AreEqual(value, "Example text. Some text"); } [Test] public void ShouldBeAbleToClearTextFromInputElements() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("working")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } [Test] public void EmptyTextBoxesShouldReturnAnEmptyStringNotNull() { driver.Url = formsPage; IWebElement emptyTextBox = driver.FindElement(By.Id("working")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); IWebElement emptyTextArea = driver.FindElement(By.Id("emptyTextArea")); Assert.AreEqual(emptyTextBox.GetAttribute("value"), ""); } [Test] public void ShouldBeAbleToClearTextFromTextAreas() { driver.Url = formsPage; IWebElement element = driver.FindElement(By.Id("withText")); element.SendKeys("Some text"); String value = element.GetAttribute("value"); Assert.IsTrue(value.Length > 0); element.Clear(); value = element.GetAttribute("value"); Assert.AreEqual(value.Length, 0); } private Func<bool> TitleToBe(string desiredTitle) { return () => { return driver.Title == desiredTitle; }; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Threading.Tasks.Tests.Status { #region Helper Classes / Enum public class TestParameters { public readonly TestAction TestAction; public MyTaskCreationOptions ChildTaskCreationOptions; public bool CreateChildTask; public bool IsPromise; public TaskStatus? FinalTaskStatus; public TaskStatus? FinalChildTaskStatus; public TaskStatus? FinalPromiseStatus; public TestParameters(TestAction testAction) { TestAction = testAction; } } public enum TestAction { None, CompletedTask, CancelTask, CancelTaskAndAcknowledge, CancelScheduledTask, CancelCreatedTask, FailedTask, FailedChildTask } public enum MyTaskCreationOptions { None = TaskCreationOptions.None, RespectParentCancellation = -2, AttachedToParent = TaskCreationOptions.AttachedToParent } public class StatusTestException : Exception { } #endregion public sealed class TaskStatusTest { #region Private Fields private Task _task; private Task _childTask; private TaskCompletionSource<int> _promise; private CancellationToken _childTaskToken; private readonly MyTaskCreationOptions _childCreationOptions; private readonly bool _createChildTask; private readonly bool _isPromise; private TaskStatus? _finalTaskStatus; private TaskStatus? _finalChildTaskStatus; private TaskStatus? _finalPromiseStatus; private volatile TestAction _testAction; private readonly ManualResetEventSlim _mre; private readonly CancellationTokenSource _taskCts; #endregion public TaskStatusTest(TestParameters parameters) { _testAction = parameters.TestAction; _childCreationOptions = parameters.ChildTaskCreationOptions; _createChildTask = parameters.CreateChildTask; _isPromise = parameters.IsPromise; _finalTaskStatus = parameters.FinalTaskStatus; _finalChildTaskStatus = parameters.FinalChildTaskStatus; _finalPromiseStatus = parameters.FinalPromiseStatus; _mre = new ManualResetEventSlim(false); _taskCts = new CancellationTokenSource(); _childTaskToken = new CancellationToken(false); } internal void RealRun() { if (_isPromise) { _promise = new TaskCompletionSource<int>(); } else { _task = new Task(TaskRun, _taskCts.Token); } if (_testAction != TestAction.None) { try { bool executeTask = false; if (_isPromise) { switch (_testAction) { case TestAction.CompletedTask: _promise.SetResult(1); break; case TestAction.FailedTask: _promise.SetException(new StatusTestException()); break; } } else { if (_testAction == TestAction.CancelScheduledTask) { CancelWaitingToRunTaskScheduler scheduler = new CancelWaitingToRunTaskScheduler(); CancellationTokenSource cts = new CancellationTokenSource(); scheduler.Cancellation = cts; // Replace _task with a task that has a custom scheduler _task = Task.Factory.StartNew(() => { }, cts.Token, TaskCreationOptions.None, scheduler); try { _task.GetAwaiter().GetResult(); } catch (Exception ex) { if (ex is OperationCanceledException) Debug.WriteLine("OperationCanceledException Exception was thrown as expected"); else Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", ex.ToString())); } } else if (_testAction == TestAction.CancelCreatedTask) { _taskCts.Cancel(); } else //When the TestAction is CompletedTask and IsPromise is false, the code will reach this point { executeTask = true; _task.Start(); } } if (_task != null && executeTask) { _mre.Wait(); // // Current Task status is WaitingForChildrenToComplete if Task didn't Cancel/Faulted and Child was created // without Detached options and current status of the child isn't RanToCompletion or Faulted yet // Task.Delay(1).Wait(); if (_createChildTask && _childTask != null && _testAction != TestAction.CancelTask && _testAction != TestAction.CancelTaskAndAcknowledge && _testAction != TestAction.FailedTask && _childCreationOptions == MyTaskCreationOptions.AttachedToParent && _childTask.Status != TaskStatus.RanToCompletion && _childTask.Status != TaskStatus.Faulted) { //we may have reach this point too soon, let's keep spinning until the status changes. while (_task.Status == TaskStatus.Running) { Task.Delay(1).Wait(); } // // If we're still waiting for children our Status should reflect so. For this verification, the // parent task's status needs to be read before the child task's status (they are volatile loads) to // make the child task's status more recent, since the child task may complete during the status // reads. // if (_task.Status != TaskStatus.WaitingForChildrenToComplete && !_childTask.IsCompleted) { Assert.True(false, string.Format("Expecting current Task status to be WaitingForChildren but getting {0}", _task.Status.ToString())); } } _task.Wait(); } } catch (AggregateException exp) { if ((_testAction == TestAction.CancelTaskAndAcknowledge || _testAction == TestAction.CancelScheduledTask || _testAction == TestAction.CancelCreatedTask) && exp.Flatten().InnerException.GetType() == typeof(TaskCanceledException)) { Debug.WriteLine("TaskCanceledException Exception was thrown as expected"); } else if ((_testAction == TestAction.FailedTask || _testAction == TestAction.FailedChildTask) && _task.IsFaulted && exp.Flatten().InnerException.GetType() == typeof(StatusTestException)) { Debug.WriteLine("StatusTestException Exception was thrown as expected"); } else { Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", exp.ToString())); } } try { // // Need to wait for Children task if it was created with Default option (Detached by default), // or current task was either canceled or failed // if (_createChildTask && (_childCreationOptions == MyTaskCreationOptions.None || _testAction == TestAction.CancelTask || _testAction == TestAction.CancelTaskAndAcknowledge || _testAction == TestAction.FailedTask)) { _childTask.Wait(); } } catch (AggregateException exp) { if (((_testAction == TestAction.CancelTask || _testAction == TestAction.CancelTaskAndAcknowledge) && _childCreationOptions == MyTaskCreationOptions.RespectParentCancellation) && exp.Flatten().InnerException.GetType() == typeof(TaskCanceledException)) { Debug.WriteLine("TaskCanceledException Exception was thrown as expected"); } else if (_testAction == TestAction.FailedChildTask && _childTask.IsFaulted && exp.Flatten().InnerException.GetType() == typeof(StatusTestException)) { Debug.WriteLine("StatusTestException Exception was thrown as expected"); } else { Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", exp.ToString())); } } } // // Verification // if (_finalTaskStatus != null && _finalTaskStatus.Value != _task.Status) { Assert.True(false, string.Format("Expecting Task final Status to be {0}, while getting {1}", _finalTaskStatus.Value, _task.Status)); } if (_finalChildTaskStatus != null && _finalChildTaskStatus.Value != _childTask.Status) { Assert.True(false, string.Format("Expecting Child Task final Status to be {0}, while getting {1}", _finalChildTaskStatus.Value, _childTask.Status)); } if (_finalPromiseStatus != null && _finalPromiseStatus.Value != _promise.Task.Status) { Assert.True(false, string.Format("Expecting Promise Status to be {0}, while getting {1}", _finalPromiseStatus.Value, _promise.Task.Status)); } // // Extra verifications for Cancel Task // if (_task != null && _task.Status == TaskStatus.Canceled && _task.IsCanceled != true) { Assert.True(false, string.Format("Task final Status is Canceled, expecting IsCanceled property to be True as well")); } if (_childTask != null && _childTask.Status == TaskStatus.Canceled && _childTask.IsCanceled != true) { Assert.True(false, string.Format("Child Task final Status is Canceled, expecting IsCanceled property to be True as well")); } // // Extra verification for faulted Promise // if (_isPromise && _testAction == TestAction.FailedTask) { // // If promise with Exception, read the exception so we don't // crash on Finalizer // AggregateException exp = _promise.Task.Exception; if (!_promise.Task.IsFaulted || exp == null) { Assert.True(false, string.Format("No Exception found on promise")); } else if (exp.Flatten().InnerException.GetType() == typeof(StatusTestException)) { Debug.WriteLine("StatusTestException Exception was thrown as expected"); } else { Assert.True(false, string.Format("Exception on promise has mismatched type, expecting StatusTestException, actual: {0}", exp.Flatten().InnerException.GetType())); } } } private void TaskRun() { try { if (_createChildTask) { TaskCreationOptions childTCO = (TaskCreationOptions)(int)_childCreationOptions; // // Pass the same token used by parent to child Task to simulate RespectParentCancellation // if (_childCreationOptions == MyTaskCreationOptions.RespectParentCancellation) { _childTaskToken = _taskCts.Token; childTCO = TaskCreationOptions.AttachedToParent; } _childTask = new Task(ChildTaskRun, null, _childTaskToken, childTCO); if (_childTask.Status != TaskStatus.Created) { Assert.True(false, string.Format("Expecting Child Task status to be Created while getting {0}", _childTask.Status.ToString())); } if (_testAction != TestAction.CancelTask && _testAction != TestAction.CancelTaskAndAcknowledge) { // // if cancel action, start the child task after calling Cancel() // _childTask.Start(); } } if (_task.Status != TaskStatus.Running) { Assert.True(false, string.Format("Expecting Current Task status to be Running while getting {0}", _task.Status.ToString())); } switch (_testAction) { case TestAction.CancelTask: if (_createChildTask) { _childTask.Start(); } _taskCts.Cancel(); break; case TestAction.CancelTaskAndAcknowledge: if (_createChildTask) { _childTask.Start(); } _taskCts.Cancel(); if (_taskCts.Token.IsCancellationRequested) { throw new OperationCanceledException(_taskCts.Token); } break; case TestAction.FailedTask: throw new StatusTestException(); } } finally { _mre.Set(); } return; } private void ChildTaskRun(object o) { if (_childTask.Status != TaskStatus.Running) { Assert.True(false, string.Format("Expecting Child Task status to be Running while getting {0}", _childTask.Status.ToString())); } switch (_testAction) { case TestAction.FailedChildTask: throw new StatusTestException(); } // // Sleep for a few milliseconds to simulate a child task executing // Task t = Task.Delay(1); t.Wait(); if (_childTaskToken.IsCancellationRequested) { throw new OperationCanceledException(_childTaskToken); } return; } } // Custom task scheduler that allows a task to be cancelled before queuing it internal class CancelWaitingToRunTaskScheduler : TaskScheduler { public CancellationTokenSource Cancellation; protected override void QueueTask(Task task) { Cancellation.Cancel(); TryExecuteTask(task); } protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; } protected override IEnumerable<Task> GetScheduledTasks() { return null; } } public sealed class TaskStatusTests { [Fact] public static void TaskStatus0() { TestParameters parameters = new TestParameters(TestAction.None) { FinalTaskStatus = TaskStatus.Created, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus1() { TestParameters parameters = new TestParameters(TestAction.None) { IsPromise = true, FinalPromiseStatus = TaskStatus.WaitingForActivation, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus2() { TestParameters parameters = new TestParameters(TestAction.CompletedTask) { FinalTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus3() { TestParameters parameters = new TestParameters(TestAction.CompletedTask) { ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent, CreateChildTask = true, FinalTaskStatus = TaskStatus.RanToCompletion, FinalChildTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus4() { TestParameters parameters = new TestParameters(TestAction.CompletedTask) { IsPromise = true, FinalPromiseStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus5() { TestParameters parameters = new TestParameters(TestAction.FailedTask) { IsPromise = true, FinalPromiseStatus = TaskStatus.Faulted, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus6() { TestParameters parameters = new TestParameters(TestAction.CancelCreatedTask) { FinalTaskStatus = TaskStatus.Canceled, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus7() { TestParameters parameters = new TestParameters(TestAction.CancelScheduledTask) { FinalTaskStatus = TaskStatus.Canceled, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus8() { TestParameters parameters = new TestParameters(TestAction.CancelTask) { FinalTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus9() { TestParameters parameters = new TestParameters(TestAction.CancelTask) { ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent, CreateChildTask = true, FinalTaskStatus = TaskStatus.RanToCompletion, FinalChildTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus10() { TestParameters parameters = new TestParameters(TestAction.CancelTask) { ChildTaskCreationOptions = MyTaskCreationOptions.RespectParentCancellation, CreateChildTask = true, FinalTaskStatus = TaskStatus.RanToCompletion, FinalChildTaskStatus = TaskStatus.Canceled, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus11() { TestParameters parameters = new TestParameters(TestAction.FailedTask) { FinalTaskStatus = TaskStatus.Faulted, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus12() { TestParameters parameters = new TestParameters(TestAction.FailedTask) { ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent, CreateChildTask = true, FinalTaskStatus = TaskStatus.Faulted, FinalChildTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus13() { TestParameters parameters = new TestParameters(TestAction.FailedTask) { CreateChildTask = true, FinalTaskStatus = TaskStatus.Faulted, FinalChildTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus14() { TestParameters parameters = new TestParameters(TestAction.FailedChildTask) { ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent, CreateChildTask = true, FinalTaskStatus = TaskStatus.Faulted, FinalChildTaskStatus = TaskStatus.Faulted, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus15() { TestParameters parameters = new TestParameters(TestAction.FailedChildTask) { CreateChildTask = true, FinalTaskStatus = TaskStatus.RanToCompletion, FinalChildTaskStatus = TaskStatus.Faulted, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] [OuterLoop] public static void TaskStatus16() { TestParameters parameters = new TestParameters(TestAction.CancelTaskAndAcknowledge) { ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent, CreateChildTask = true, FinalTaskStatus = TaskStatus.Canceled, FinalChildTaskStatus = TaskStatus.RanToCompletion, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } [Fact] public static void TaskStatus17() { TestParameters parameters = new TestParameters(TestAction.CancelTaskAndAcknowledge) { ChildTaskCreationOptions = MyTaskCreationOptions.RespectParentCancellation, CreateChildTask = true, FinalTaskStatus = TaskStatus.Canceled, FinalChildTaskStatus = TaskStatus.Canceled, }; TaskStatusTest test = new TaskStatusTest(parameters); test.RealRun(); } } }
/* ==================================================================== 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 NPOI.OpenXmlFormats.Spreadsheet; using System; using NPOI.XSSF.Model; using NPOI.XSSF.UserModel; using NPOI.SS.Util; using NPOI.SS.UserModel; using System.Collections.Generic; using NPOI.Util; using NPOI.SS; using System.Collections; namespace NPOI.XSSF.UserModel { /** * High level representation of a row of a spreadsheet. */ public class XSSFRow : IRow, IComparable<XSSFRow> { private static POILogger _logger = POILogFactory.GetLogger(typeof(XSSFRow)); /** * the xml bean Containing all cell defInitions for this row */ private CT_Row _row; /** * Cells of this row keyed by their column indexes. * The TreeMap ensures that the cells are ordered by columnIndex in the ascending order. */ private SortedDictionary<int, ICell> _cells; /** * the parent sheet */ private XSSFSheet _sheet; /** * Construct a XSSFRow. * * @param row the xml bean Containing all cell defInitions for this row. * @param sheet the parent sheet. */ public XSSFRow(CT_Row row, XSSFSheet sheet) { _row = row; _sheet = sheet; _cells = new SortedDictionary<int, ICell>(); if (0 < row.SizeOfCArray()) { foreach (CT_Cell c in row.c) { XSSFCell cell = new XSSFCell(this, c); _cells.Add(cell.ColumnIndex,cell); sheet.OnReadCell(cell); } } } /** * Returns the XSSFSheet this row belongs to * * @return the XSSFSheet that owns this row */ public ISheet Sheet { get { return this._sheet; } } /** * Cell iterator over the physically defined cells: * <blockquote><pre> * for (Iterator<Cell> it = row.cellIterator(); it.HasNext(); ) { * Cell cell = it.next(); * ... * } * </pre></blockquote> * * @return an iterator over cells in this row. */ public SortedDictionary<int, ICell>.ValueCollection.Enumerator CellIterator() { return _cells.Values.GetEnumerator(); } /** * Alias for {@link #cellIterator()} to allow foreach loops: * <blockquote><pre> * for(Cell cell : row){ * ... * } * </pre></blockquote> * * @return an iterator over cells in this row. */ public IEnumerator<ICell> GetEnumerator() { return CellIterator(); } /** * Compares two <code>XSSFRow</code> objects. Two rows are equal if they belong to the same worksheet and * their row indexes are Equal. * * @param row the <code>XSSFRow</code> to be Compared. * @return the value <code>0</code> if the row number of this <code>XSSFRow</code> is * equal to the row number of the argument <code>XSSFRow</code>; a value less than * <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically less * than the row number of the argument <code>XSSFRow</code>; and a value greater * than <code>0</code> if the row number of this this <code>XSSFRow</code> is numerically * greater than the row number of the argument <code>XSSFRow</code>. * @throws ArgumentException if the argument row belongs to a different worksheet */ public int CompareTo(XSSFRow row) { int thisVal = this.RowNum; if (row.Sheet != Sheet) throw new ArgumentException("The Compared rows must belong to the same XSSFSheet"); int anotherVal = row.RowNum; return (thisVal < anotherVal ? -1 : (thisVal == anotherVal ? 0 : 1)); } /** * Use this to create new cells within the row and return it. * <p> * The cell that is returned is a {@link Cell#CELL_TYPE_BLANK}. The type can be Changed * either through calling <code>SetCellValue</code> or <code>SetCellType</code>. * </p> * @param columnIndex - the column number this cell represents * @return Cell a high level representation of the Created cell. * @throws ArgumentException if columnIndex < 0 or greater than 16384, * the maximum number of columns supported by the SpreadsheetML format (.xlsx) */ public ICell CreateCell(int columnIndex) { return CreateCell(columnIndex, CellType.Blank); } /** * Use this to create new cells within the row and return it. * * @param columnIndex - the column number this cell represents * @param type - the cell's data type * @return XSSFCell a high level representation of the Created cell. * @throws ArgumentException if the specified cell type is invalid, columnIndex < 0 * or greater than 16384, the maximum number of columns supported by the SpreadsheetML format (.xlsx) * @see Cell#CELL_TYPE_BLANK * @see Cell#CELL_TYPE_BOOLEAN * @see Cell#CELL_TYPE_ERROR * @see Cell#CELL_TYPE_FORMULA * @see Cell#CELL_TYPE_NUMERIC * @see Cell#CELL_TYPE_STRING */ public ICell CreateCell(int columnIndex, CellType type) { CT_Cell ctCell; XSSFCell prev = _cells.ContainsKey(columnIndex) ? (XSSFCell)_cells[columnIndex] : null; if (prev != null) { ctCell = prev.GetCTCell(); ctCell.Set(new CT_Cell()); } else { ctCell = _row.AddNewC(); } XSSFCell xcell = new XSSFCell(this, ctCell); xcell.SetCellNum(columnIndex); if (type != CellType.Blank) { xcell.SetCellType(type); } _cells[columnIndex] = xcell; return xcell; } /** * Returns the cell at the given (0 based) index, * with the {@link NPOI.SS.usermodel.Row.MissingCellPolicy} from the parent Workbook. * * @return the cell at the given (0 based) index */ public ICell GetCell(int cellnum) { return GetCell(cellnum, _sheet.Workbook.MissingCellPolicy); } /// <summary> /// Get the hssfcell representing a given column (logical cell) /// 0-based. If you ask for a cell that is not defined, then /// you Get a null. /// This is the basic call, with no policies applied /// </summary> /// <param name="cellnum">0 based column number</param> /// <returns>Cell representing that column or null if Undefined.</returns> private ICell RetrieveCell(int cellnum) { if (!_cells.ContainsKey(cellnum)) return null; //if (cellnum < 0 || cellnum >= cells.Count) return null; return _cells[cellnum]; } /** * Returns the cell at the given (0 based) index, with the specified {@link NPOI.SS.usermodel.Row.MissingCellPolicy} * * @return the cell at the given (0 based) index * @throws ArgumentException if cellnum < 0 or the specified MissingCellPolicy is invalid * @see Row#RETURN_NULL_AND_BLANK * @see Row#RETURN_BLANK_AS_NULL * @see Row#CREATE_NULL_AS_BLANK */ public ICell GetCell(int cellnum, MissingCellPolicy policy) { if (cellnum < 0) throw new ArgumentException("Cell index must be >= 0"); XSSFCell cell = (XSSFCell)RetrieveCell(cellnum); if (policy == MissingCellPolicy.RETURN_NULL_AND_BLANK) { return cell; } if (policy == MissingCellPolicy.RETURN_BLANK_AS_NULL) { if (cell == null) return cell; if (cell.CellType == CellType.Blank) { return null; } return cell; } if (policy == MissingCellPolicy.CREATE_NULL_AS_BLANK) { if (cell == null) { return CreateCell(cellnum, CellType.Blank); } return cell; } throw new ArgumentException("Illegal policy " + policy + " (" + policy.id + ")"); } int GetFirstKey(SortedDictionary<int, ICell>.KeyCollection keys) { int i = 0; foreach (int key in keys) { if (i == 0) return key; } throw new ArgumentOutOfRangeException(); } int GetLastKey(SortedDictionary<int, ICell>.KeyCollection keys) { int i = 0; foreach (int key in keys) { if (i == keys.Count - 1) return key; i++; } throw new ArgumentOutOfRangeException(); } /** * Get the number of the first cell Contained in this row. * * @return short representing the first logical cell in the row, * or -1 if the row does not contain any cells. */ public short FirstCellNum { get { return (short)(_cells.Count == 0 ? -1 : GetFirstKey(_cells.Keys)); } } /** * Gets the index of the last cell Contained in this row <b>PLUS ONE</b>. The result also * happens to be the 1-based column number of the last cell. This value can be used as a * standard upper bound when iterating over cells: * <pre> * short minColIx = row.GetFirstCellNum(); * short maxColIx = row.GetLastCellNum(); * for(short colIx=minColIx; colIx&lt;maxColIx; colIx++) { * XSSFCell cell = row.GetCell(colIx); * if(cell == null) { * continue; * } * //... do something with cell * } * </pre> * * @return short representing the last logical cell in the row <b>PLUS ONE</b>, * or -1 if the row does not contain any cells. */ public short LastCellNum { get { return (short)(_cells.Count == 0 ? -1 : (GetLastKey(_cells.Keys) + 1)); } } /** * Get the row's height measured in twips (1/20th of a point). If the height is not Set, the default worksheet value is returned, * See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()} * * @return row height measured in twips (1/20th of a point) */ public short Height { get { return (short)(HeightInPoints * 20); } set { if (value < 0) { if (_row.IsSetHt()) _row.unSetHt(); if (_row.IsSetCustomHeight()) _row.unSetCustomHeight(); } else { _row.ht = ((double)value / 20); _row.customHeight = (true); } } } /** * Returns row height measured in point size. If the height is not Set, the default worksheet value is returned, * See {@link NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints()} * * @return row height measured in point size * @see NPOI.XSSF.usermodel.XSSFSheet#GetDefaultRowHeightInPoints() */ public float HeightInPoints { get { if (this._row.IsSetHt()) { return (float)this._row.ht; } return _sheet.DefaultRowHeightInPoints; } set { this.Height = (short)(value == -1 ? -1 : (value * 20)); } } /** * Gets the number of defined cells (NOT number of cells in the actual row!). * That is to say if only columns 0,4,5 have values then there would be 3. * * @return int representing the number of defined cells in the row. */ public int PhysicalNumberOfCells { get { return _cells.Count; } } /** * Get row number this row represents * * @return the row number (0 based) */ public int RowNum { get { return (int)_row.r-1; } set { int maxrow = SpreadsheetVersion.EXCEL2007.LastRowIndex; if (value < 0 || value > maxrow) { throw new ArgumentException("Invalid row number (" + value + ") outside allowable range (0.." + maxrow + ")"); } _row.r = (uint)(value+1); } } /** * Get whether or not to display this row with 0 height * * @return - height is zero or not. */ public bool ZeroHeight { get { return (bool)this._row.hidden; } set { this._row.hidden = value; } } /** * Is this row formatted? Most aren't, but some rows * do have whole-row styles. For those that do, you * can get the formatting from {@link #GetRowStyle()} */ public bool IsFormatted { get { return _row.IsSetS(); } } /** * Returns the whole-row cell style. Most rows won't * have one of these, so will return null. Call * {@link #isFormatted()} to check first. */ public ICellStyle RowStyle { get { if (!IsFormatted) return null; StylesTable stylesSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource(); if (stylesSource.NumCellStyles > 0) { return stylesSource.GetStyleAt((int)_row.s); } else { return null; } } set { if (value == null) { if (_row.IsSetS()) { _row.UnsetS(); _row.UnsetCustomFormat(); } } else { StylesTable styleSource = ((XSSFWorkbook)Sheet.Workbook).GetStylesSource(); XSSFCellStyle xStyle = (XSSFCellStyle)value; xStyle.VerifyBelongsToStylesSource(styleSource); long idx = styleSource.PutStyle(xStyle); _row.s = (uint)idx; _row.customFormat = (true); } } } /** * Applies a whole-row cell styling to the row. * If the value is null then the style information is Removed, * causing the cell to used the default workbook style. */ public void SetRowStyle(ICellStyle style) { } /** * Remove the Cell from this row. * * @param cell the cell to remove */ public void RemoveCell(ICell cell) { if (cell.Row != this) { throw new ArgumentException("Specified cell does not belong to this row"); } XSSFCell xcell = (XSSFCell)cell; if (xcell.IsPartOfArrayFormulaGroup) { xcell.NotifyArrayFormulaChanging(); } if (cell.CellType == CellType.Formula) { ((XSSFWorkbook)_sheet.Workbook).OnDeleteFormula(xcell); } _cells.Remove(cell.ColumnIndex); } /** * Returns the underlying CT_Row xml bean Containing all cell defInitions in this row * * @return the underlying CT_Row xml bean */ public CT_Row GetCTRow() { return _row; } /** * Fired when the document is written to an output stream. * * @see NPOI.XSSF.usermodel.XSSFSheet#Write(java.io.OutputStream) () */ internal void OnDocumentWrite() { // check if cells in the CT_Row are ordered bool isOrdered = true; if (_row.SizeOfCArray() != _cells.Count) isOrdered = false; else { int i = 0; foreach (XSSFCell cell in _cells.Values) { CT_Cell c1 = cell.GetCTCell(); CT_Cell c2 = _row.GetCArray(i++); String r1 = c1.r; String r2 = c2.r; if (!(r1 == null ? r2 == null : r1.Equals(r2))) { isOrdered = false; break; } } } if (!isOrdered) { CT_Cell[] cArray = new CT_Cell[_cells.Count]; int i = 0; foreach (XSSFCell c in _cells.Values) { cArray[i++] = c.GetCTCell(); } _row.SetCArray(cArray); } } /** * @return formatted xml representation of this row */ public override String ToString() { return _row.ToString(); } /** * update cell references when Shifting rows * * @param n the number of rows to move */ internal void Shift(int n) { int rownum = RowNum + n; CalculationChain calcChain = ((XSSFWorkbook)_sheet.Workbook).GetCalculationChain(); int sheetId = (int)_sheet.sheet.sheetId; String msg = "Row[rownum=" + RowNum + "] contains cell(s) included in a multi-cell array formula. " + "You cannot change part of an array."; foreach (ICell c in this) { XSSFCell cell = (XSSFCell)c; if (cell.IsPartOfArrayFormulaGroup) { cell.NotifyArrayFormulaChanging(msg); } //remove the reference in the calculation chain if (calcChain != null) calcChain.RemoveItem(sheetId, cell.GetReference()); CT_Cell CT_Cell = cell.GetCTCell(); String r = new CellReference(rownum, cell.ColumnIndex).FormatAsString(); CT_Cell.r = r; } RowNum = rownum; } #region IRow Members public List<ICell> Cells { get { List<ICell> cells = new List<ICell>(); foreach (ICell cell in _cells.Values) { cells.Add(cell); } return cells; } } public void MoveCell(ICell cell, int newColumn) { throw new NotImplementedException(); } public IRow CopyRowTo(int targetIndex) { return this.Sheet.CopyRow(this.RowNum, targetIndex); } public ICell CopyCell(int sourceIndex, int targetIndex) { return CellUtil.CopyCell(this, sourceIndex, targetIndex); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public bool HasCustomHeight() { throw new NotImplementedException(); } public int OutlineLevel { get { return _row.outlineLevel; } } public bool? Hidden { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public bool? Collapsed { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } #endregion } }
//solar shading calculator //written by Yifan Liu - [email protected] //April. 26th, 2013 // based on fomula from http://www.esrl.noaa.gov/gmd/grad/solcalc/calcdetails.html // this script calculates the zimuth and altitude angle, which matches(+-1 difference): http://pveducation.org/pvcdrom/properties-of-sunlight/sun-position-calculator // also matches (+-2): http://www.esrl.noaa.gov/gmd/grad/solcalc/ // the difference is caused by compiler lose of decimal precision when calculating julianday. The compiler loses precision when handling floats with more than seven digits //INSTRUCTION: Positive z axis is the default NORTH, positive x axis is the default EAST //euler.y of sun = Azmuith angle of sun -180; //euler.x of sun = Altitude angle of sun; //!!!Make sure align the north of the site to the Z axis before using this script. using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using UnityEngine.UI; public class SunLightWidget : MonoBehaviour { public static SunLightWidget Instance; public SunlightWidgetData InputData; // The center database of all the input data needed by the calculation algorithm public string xmlPath; public RectTransform cityButPrefab; public RectTransform cityDropdown; public Text yearLabelText; public Text monthLabelText; public Text dateLabelText; public Text currentCityOnDisplay; public Transform sun; public static DateTime time = new DateTime(); // see the DateTime script for class definition public float longitude; public float latitude; public float localTime; public float timeZone; public float altitude; public float azimuth; public float julianDay; public float julianCentury; public float geomMeanLongSun; public float geomMeanAnomSun; public float eccentEarthOrbit; public float sunEqOfCtr; public float sunTrueLong; public float sunAppLong; public float meanObliqEcliptic; public float ObliqCorr; public float declinationAngle; public float varY; public float eqOfTime; public float trueSolarTime; public float hourAngle; public float zenithAngle; private RectTransform hourSlider; // the hour of day is not saved into the inputData and xml. It is directly read from the slider value, range [0,1] // private bool widgetStart; // default is false, turn to true when the "start widget" is clicked public bool dayLightSaving; // default is false, true -> daylight saving -> deduct an hour from localtime during calculation void Awake(){ xmlPath = Application.dataPath + "/sunlightWidgetData.xml"; if(Instance == null){ Instance = this; } else{ Debug.LogError("Error: two instances of sunlightwidget"); } } // Use this for initialization //PRE: Assign panel to the panel variable in inspector void Start () { if(true){//need to check for file path validity InputData = XmlIO.Load(xmlPath, typeof(SunlightWidgetData)) as SunlightWidgetData; } // Debug.Log("input loaded: " + InputData); //this section initializes the UI with the inputData loaded from the xml populateCityDropDown(InputData.ListOfCity, cityDropdown,cityButPrefab); populateTimeLabels(InputData); currentCityOnDisplay.text = InputData.CurrentCity.CityName; //set up reference to hourSlider hourSlider = transform.FindChild("mainPanel").FindChild("Slider") as RectTransform; dayLightSaving = false; } public void AddNewCityToDropDown(string cityName){ RectTransform cityItem = Instantiate(cityButPrefab) as RectTransform; cityItem.parent = cityDropdown; cityItem.FindChild("Text").GetComponent<UnityEngine.UI.Text>().text = cityName; } void populateCityDropDown(List<City> listOfCity, RectTransform dropdownPanel, RectTransform cityButPrefab){ //remove existing item in the dropdown foreach(RectTransform item in dropdownPanel){ Destroy (item.gameObject); } foreach(City city in listOfCity){ RectTransform cityItem = Instantiate(cityButPrefab) as RectTransform; cityItem.parent = dropdownPanel; cityItem.FindChild("Text").GetComponent<UnityEngine.UI.Text>().text = city.CityName; if(!CityDropdownLongEnough()){ IncreaseCityDropdownSize(); } } } public void IncreaseCityDropdownSize(){ cityDropdown.sizeDelta = new Vector2(121.3f, cityDropdown.sizeDelta.y + 18.0f); } //overload method allows specify size public void IncreaseCityDropdownSize(float incrementSize){ cityDropdown.sizeDelta = new Vector2(121.3f, cityDropdown.sizeDelta.y + incrementSize); } //check if cityDropdown(contenPanel)'s height is enought to hold all the cities public bool CityDropdownLongEnough(){ if(cityDropdown.sizeDelta.y - 16 * InputData.ListOfCity.Count <= 2){ return false; }else{ return true; } } void populateTimeLabels(SunlightWidgetData database){ dateLabelText.text = database.Date.ToString(); monthLabelText.text = database.Month.ToString(); yearLabelText.text = database.Year.ToString(); } //save the inputDate to the xml file at path Application.dataPath + "/sunlightWidgetData.xml" public void saveDataToXML(){ XmlIO.Save(InputData, xmlPath); } //This method calls all the functions needed to calculate the sun position and rotate the sun //called by the hour slider public void calcSunCoordination(){ time = new DateTime(InputData.Year, InputData.Month, InputData.Date); localTime = hourSlider.GetComponent<Slider>().value; longitude = InputData.CurrentCity.Longitude; latitude = InputData.CurrentCity.Latitude; timeZone = InputData.CurrentCity.TimeZone; julianDay = dateToJulian(time); julianCentury = calcJulianCentury(time); geomMeanAnomSun = calcGeoMeanAnomSun(time); eccentEarthOrbit = calcEccentEarthOrbit(time); meanObliqEcliptic = calcMeanObliqEcliptic(time); ObliqCorr = calcObliqCorr(meanObliqEcliptic); varY = calcVarY(ObliqCorr); geomMeanLongSun = calcMeanLongSun(julianCentury); eqOfTime = calcEqOfTime(geomMeanLongSun,geomMeanAnomSun,eccentEarthOrbit,varY); if(!dayLightSaving){ trueSolarTime = calcTrueSolarTime(localTime,eqOfTime,longitude,timeZone); } else{ trueSolarTime = calcTrueSolarTime(localTime - 0.041667f,eqOfTime,longitude,timeZone); } hourAngle = calcHourAngle(trueSolarTime); sunEqOfCtr = calcSunEqOfCtr(julianCentury,geomMeanAnomSun); sunTrueLong = calcSunTrueLong(geomMeanLongSun,sunEqOfCtr); sunAppLong = calcSunAppLong(sunTrueLong); declinationAngle = calcDeclinationAngle(ObliqCorr,sunAppLong); zenithAngle = calcZenithAngle(latitude, declinationAngle,hourAngle); azimuth = calcAzimuthAngle(hourAngle,latitude,zenithAngle,declinationAngle); // Debug.Log("azimuth: " + azimuth); altitude = calcAltitudeAngle(zenithAngle); // Debug.Log("altitude: " + altitude); //rotate the sun rotateSun(azimuth, altitude); adjustSunIntensity(altitude); } //reduce sun intensity during dust and increase sun intensity during dawn private void adjustSunIntensity(float altitude){ //check if sun is below ground, if so reduce sun intensity if(altitude <= 0){ float intensity = sun.GetComponent<Light>().intensity; sun.GetComponent<Light>().intensity = Mathf.Lerp(1,0.01f,(0f - altitude)/10); }else{ // this is to prevent a jump in time, i.e. non-continuous time change if(sun.GetComponent<Light>().intensity < 0.9f){ sun.GetComponent<Light>().intensity = 1; } } } //PRE: azimuth and altitude angle must be initialized //POST: rotate the sun based on the azimuth and altitude angle public void rotateSun(float azimuth, float altitude){ while(azimuth < 0){ azimuth += 360; } while (azimuth > 360){ azimuth -= 360; } //set azimuth angle sun.eulerAngles = new Vector3(0, azimuth - 180, 0); // to set z be north, y should be azimuth - 180, if z is south , y should be azimuth //set altitude angle sun.eulerAngles = new Vector3(altitude, sun.eulerAngles.y, sun.eulerAngles.z); } //converts the current date to Julianday public float dateToJulian(DateTime time){ float month = time.Month; float day = time.Day; float year = time.Year; if(month < 3){ month = month + 12; year = year -1; } // NOTE that julianDay here loses precision. It is truncated into an int after adding "1721119". The float or double cannot hold decimals when storing //numbers with more than 7 digits. float julianDay = day + (153.0f * month - 457.0f) / 5.0f + 365.0f * year + (year/4.0f) - (year / 100.0f) + (year/400.0f) + 1721119.0f + localTime - timeZone/24.0f; //print out julianDay // Debug.Log(julianDay); return julianDay; } public float calcAzimuthAngle(float hourAngle, float latitude, float zenithAngle, float declinationAngle){ float radLatitude = latitude * Mathf.Deg2Rad; float radZenithAngle = zenithAngle * Mathf.Deg2Rad; float radDeclinationAngle = declinationAngle * Mathf.Deg2Rad; float sinRadLatitude = Mathf.Sin(radLatitude); float sinRadDeclinationAngle = Mathf.Sin(radDeclinationAngle); float sinRadZenithAngle = Mathf.Sin(radZenithAngle); float cosRadLatitude = Mathf.Cos(radLatitude); // float cosRadDeclinationAngle = Mathf.Cos(radDeclinationAngle); float cosRadZenithAngle = Mathf.Cos(radZenithAngle); float azimuth; if(hourAngle > 0){ azimuth = (Mathf.Acos(((sinRadLatitude * cosRadZenithAngle) - sinRadDeclinationAngle)/(cosRadLatitude * sinRadZenithAngle))*Mathf.Rad2Deg + 180) % 360; } else{ azimuth = (540 - Mathf.Acos(((sinRadLatitude * cosRadZenithAngle)- sinRadDeclinationAngle)/ (cosRadLatitude * sinRadZenithAngle))*Mathf.Rad2Deg) % 360; } return azimuth; } public float calcAltitudeAngle(float zenithAngle){ return 90-zenithAngle; } public float calcHourAngle(float trueSolarTime){ float hourAngle; if(trueSolarTime /4 < 0){ hourAngle = trueSolarTime/4 + 180; } else{ hourAngle = trueSolarTime/4 -180; } return hourAngle; } public float calcTrueSolarTime(float localTime, float eqOfTime, float longitude, float timeZone){ float trueSolarTime1; if((localTime * 1440 + eqOfTime + 4* longitude - 60* timeZone) < 0){ trueSolarTime1 = (localTime * 1440 + eqOfTime + 4* longitude - 60* timeZone) - 1440 * Mathf.Floor((localTime * 1440 + eqOfTime + 4* longitude - 60* timeZone)/1440); } else{ trueSolarTime1 = ((localTime * 1440 + eqOfTime + 4* longitude - 60* timeZone) % 1440); } return trueSolarTime1; } public float calcEqOfTime(float geomMeanLongSun, float geomMeanAnomSun, float eccentEarthOrbit, float varY){ float radMeanLongSun = geomMeanLongSun * Mathf.Deg2Rad; float radGeoMeanAnomSun = geomMeanAnomSun * Mathf.Deg2Rad; float eqOfTime; eqOfTime = 4*(varY * Mathf.Sin(2 * radMeanLongSun) - 2 * eccentEarthOrbit * Mathf.Sin(radGeoMeanAnomSun) + 4 * eccentEarthOrbit * varY * Mathf.Sin(radGeoMeanAnomSun) * Mathf.Cos(2 * radMeanLongSun) - 0.5f *varY * varY*Mathf.Sin(4 * radMeanLongSun) - 1.25f * eccentEarthOrbit * eccentEarthOrbit * Mathf.Sin(2 * radGeoMeanAnomSun))*Mathf.Rad2Deg; return eqOfTime; } public float calcMeanLongSun(float julianCentury){ float geomMeanLongSun = (280.46646f + julianCentury * (36000.76983f + julianCentury * 0.0003032f))% 360; return geomMeanLongSun; } public float calcJulianCentury(DateTime time){ float julianCentury = (dateToJulian(time) - 2451545) / 36525; return julianCentury; } public float calcVarY(float obliqCorr){ float varY = Mathf.Tan((obliqCorr/2)*Mathf.Deg2Rad)*Mathf.Tan((obliqCorr/2)*Mathf.Deg2Rad); return varY; } public float calcObliqCorr(float meanObliqEcliptic){ float obliqCorr = meanObliqEcliptic + 0.00256f * Mathf.Cos((125.04f - 1934.136f * calcJulianCentury(time))*Mathf.Deg2Rad); return obliqCorr; } public float calcMeanObliqEcliptic(DateTime time){ float julianCentury = calcJulianCentury(time); float meanObliqEcliptic = 23+(26+((21.448f-julianCentury*(46.815f+julianCentury*(0.00059f - julianCentury * 0.001813f))))/60)/60; return meanObliqEcliptic; } public float calcEccentEarthOrbit(DateTime time){ float julianCentury = calcJulianCentury(time); float eccenEarthOrbit = 0.016708634f - julianCentury * (0.000042037f+0.0000001267f* julianCentury); return eccenEarthOrbit; } public float calcGeoMeanAnomSun(DateTime time){ float julianCentury = calcJulianCentury(time); float geoMeanAnomSun = 357.52911f+julianCentury*(35999.05029f - 0.0001537f*julianCentury); return geoMeanAnomSun; } public float calcDeclinationAngle(float obliqCorr, float sunAppLong){ float declinationAngle = Mathf.Asin(Mathf.Sin(obliqCorr* Mathf.Deg2Rad)* Mathf.Sin(sunAppLong* Mathf.Deg2Rad))*Mathf.Rad2Deg; return declinationAngle; } public float calcSunAppLong(float sunTrueLong){ float sunAppLong = sunTrueLong - 0.00569f-0.00478f*Mathf.Sin((125.04f-1934.136f*this.julianCentury)*Mathf.Deg2Rad); return sunAppLong; } public float calcSunTrueLong(float geomMeanLongSun, float sunEqOfCtr){ return geomMeanLongSun + sunEqOfCtr; } public float calcSunEqOfCtr(float julianCentury, float geomMeanAnomSun){ return (Mathf.Sin(geomMeanAnomSun*Mathf.Deg2Rad)*(1.914602f - julianCentury*(0.004817f+0.000014f*julianCentury)) + Mathf.Sin(geomMeanAnomSun *2 *Mathf.Deg2Rad)*(0.019993f-0.000101f*julianCentury) + Mathf.Sin(3*geomMeanAnomSun*Mathf.Deg2Rad* 0.000289f)); } public float calcZenithAngle(float latitude, float declinationAngle, float hourAngle){ return ((Mathf.Acos(Mathf.Sin(latitude*Mathf.Deg2Rad)*Mathf.Sin(declinationAngle *Mathf.Deg2Rad)+ Mathf.Cos(latitude*Mathf.Deg2Rad)*Mathf.Cos(declinationAngle*Mathf.Deg2Rad)*Mathf.Cos(hourAngle*Mathf.Deg2Rad)))*Mathf.Rad2Deg); } }
using UnityEngine; using System.Collections; using System.IO; using System.Collections.Generic; [System.Serializable] public struct MVFaceCollection { public byte[,,] colorIndices; } [System.Serializable] public struct MVVoxel { public byte x, y, z, colorIndex; } [System.Serializable] public class MVVoxelChunk { // all voxels public byte[,,] voxels; // 6 dir, x+. x-, y+, y-, z+, z- public MVFaceCollection[] faces; public int x = 0, y = 0, z = 0; public int sizeX { get { return voxels.GetLength (0); } } public int sizeY { get { return voxels.GetLength (1); } } public int sizeZ { get { return voxels.GetLength (2); } } } public enum MVFaceDir { XPos = 0, XNeg = 1, YPos = 2, YNeg = 3, ZPos = 4, ZNeg = 5 } [System.Serializable] public class MVMainChunk { public MVVoxelChunk voxelChunk; public MVVoxelChunk alphaMaskChunk; public Color[] palatte; public int sizeX, sizeY, sizeZ; public byte[] version; #region default_palatte public static Color[] defaultPalatte = new Color[] { new Color(1.000000f, 1.000000f, 1.000000f), new Color(1.000000f, 1.000000f, 0.800000f), new Color(1.000000f, 1.000000f, 0.600000f), new Color(1.000000f, 1.000000f, 0.400000f), new Color(1.000000f, 1.000000f, 0.200000f), new Color(1.000000f, 1.000000f, 0.000000f), new Color(1.000000f, 0.800000f, 1.000000f), new Color(1.000000f, 0.800000f, 0.800000f), new Color(1.000000f, 0.800000f, 0.600000f), new Color(1.000000f, 0.800000f, 0.400000f), new Color(1.000000f, 0.800000f, 0.200000f), new Color(1.000000f, 0.800000f, 0.000000f), new Color(1.000000f, 0.600000f, 1.000000f), new Color(1.000000f, 0.600000f, 0.800000f), new Color(1.000000f, 0.600000f, 0.600000f), new Color(1.000000f, 0.600000f, 0.400000f), new Color(1.000000f, 0.600000f, 0.200000f), new Color(1.000000f, 0.600000f, 0.000000f), new Color(1.000000f, 0.400000f, 1.000000f), new Color(1.000000f, 0.400000f, 0.800000f), new Color(1.000000f, 0.400000f, 0.600000f), new Color(1.000000f, 0.400000f, 0.400000f), new Color(1.000000f, 0.400000f, 0.200000f), new Color(1.000000f, 0.400000f, 0.000000f), new Color(1.000000f, 0.200000f, 1.000000f), new Color(1.000000f, 0.200000f, 0.800000f), new Color(1.000000f, 0.200000f, 0.600000f), new Color(1.000000f, 0.200000f, 0.400000f), new Color(1.000000f, 0.200000f, 0.200000f), new Color(1.000000f, 0.200000f, 0.000000f), new Color(1.000000f, 0.000000f, 1.000000f), new Color(1.000000f, 0.000000f, 0.800000f), new Color(1.000000f, 0.000000f, 0.600000f), new Color(1.000000f, 0.000000f, 0.400000f), new Color(1.000000f, 0.000000f, 0.200000f), new Color(1.000000f, 0.000000f, 0.000000f), new Color(0.800000f, 1.000000f, 1.000000f), new Color(0.800000f, 1.000000f, 0.800000f), new Color(0.800000f, 1.000000f, 0.600000f), new Color(0.800000f, 1.000000f, 0.400000f), new Color(0.800000f, 1.000000f, 0.200000f), new Color(0.800000f, 1.000000f, 0.000000f), new Color(0.800000f, 0.800000f, 1.000000f), new Color(0.800000f, 0.800000f, 0.800000f), new Color(0.800000f, 0.800000f, 0.600000f), new Color(0.800000f, 0.800000f, 0.400000f), new Color(0.800000f, 0.800000f, 0.200000f), new Color(0.800000f, 0.800000f, 0.000000f), new Color(0.800000f, 0.600000f, 1.000000f), new Color(0.800000f, 0.600000f, 0.800000f), new Color(0.800000f, 0.600000f, 0.600000f), new Color(0.800000f, 0.600000f, 0.400000f), new Color(0.800000f, 0.600000f, 0.200000f), new Color(0.800000f, 0.600000f, 0.000000f), new Color(0.800000f, 0.400000f, 1.000000f), new Color(0.800000f, 0.400000f, 0.800000f), new Color(0.800000f, 0.400000f, 0.600000f), new Color(0.800000f, 0.400000f, 0.400000f), new Color(0.800000f, 0.400000f, 0.200000f), new Color(0.800000f, 0.400000f, 0.000000f), new Color(0.800000f, 0.200000f, 1.000000f), new Color(0.800000f, 0.200000f, 0.800000f), new Color(0.800000f, 0.200000f, 0.600000f), new Color(0.800000f, 0.200000f, 0.400000f), new Color(0.800000f, 0.200000f, 0.200000f), new Color(0.800000f, 0.200000f, 0.000000f), new Color(0.800000f, 0.000000f, 1.000000f), new Color(0.800000f, 0.000000f, 0.800000f), new Color(0.800000f, 0.000000f, 0.600000f), new Color(0.800000f, 0.000000f, 0.400000f), new Color(0.800000f, 0.000000f, 0.200000f), new Color(0.800000f, 0.000000f, 0.000000f), new Color(0.600000f, 1.000000f, 1.000000f), new Color(0.600000f, 1.000000f, 0.800000f), new Color(0.600000f, 1.000000f, 0.600000f), new Color(0.600000f, 1.000000f, 0.400000f), new Color(0.600000f, 1.000000f, 0.200000f), new Color(0.600000f, 1.000000f, 0.000000f), new Color(0.600000f, 0.800000f, 1.000000f), new Color(0.600000f, 0.800000f, 0.800000f), new Color(0.600000f, 0.800000f, 0.600000f), new Color(0.600000f, 0.800000f, 0.400000f), new Color(0.600000f, 0.800000f, 0.200000f), new Color(0.600000f, 0.800000f, 0.000000f), new Color(0.600000f, 0.600000f, 1.000000f), new Color(0.600000f, 0.600000f, 0.800000f), new Color(0.600000f, 0.600000f, 0.600000f), new Color(0.600000f, 0.600000f, 0.400000f), new Color(0.600000f, 0.600000f, 0.200000f), new Color(0.600000f, 0.600000f, 0.000000f), new Color(0.600000f, 0.400000f, 1.000000f), new Color(0.600000f, 0.400000f, 0.800000f), new Color(0.600000f, 0.400000f, 0.600000f), new Color(0.600000f, 0.400000f, 0.400000f), new Color(0.600000f, 0.400000f, 0.200000f), new Color(0.600000f, 0.400000f, 0.000000f), new Color(0.600000f, 0.200000f, 1.000000f), new Color(0.600000f, 0.200000f, 0.800000f), new Color(0.600000f, 0.200000f, 0.600000f), new Color(0.600000f, 0.200000f, 0.400000f), new Color(0.600000f, 0.200000f, 0.200000f), new Color(0.600000f, 0.200000f, 0.000000f), new Color(0.600000f, 0.000000f, 1.000000f), new Color(0.600000f, 0.000000f, 0.800000f), new Color(0.600000f, 0.000000f, 0.600000f), new Color(0.600000f, 0.000000f, 0.400000f), new Color(0.600000f, 0.000000f, 0.200000f), new Color(0.600000f, 0.000000f, 0.000000f), new Color(0.400000f, 1.000000f, 1.000000f), new Color(0.400000f, 1.000000f, 0.800000f), new Color(0.400000f, 1.000000f, 0.600000f), new Color(0.400000f, 1.000000f, 0.400000f), new Color(0.400000f, 1.000000f, 0.200000f), new Color(0.400000f, 1.000000f, 0.000000f), new Color(0.400000f, 0.800000f, 1.000000f), new Color(0.400000f, 0.800000f, 0.800000f), new Color(0.400000f, 0.800000f, 0.600000f), new Color(0.400000f, 0.800000f, 0.400000f), new Color(0.400000f, 0.800000f, 0.200000f), new Color(0.400000f, 0.800000f, 0.000000f), new Color(0.400000f, 0.600000f, 1.000000f), new Color(0.400000f, 0.600000f, 0.800000f), new Color(0.400000f, 0.600000f, 0.600000f), new Color(0.400000f, 0.600000f, 0.400000f), new Color(0.400000f, 0.600000f, 0.200000f), new Color(0.400000f, 0.600000f, 0.000000f), new Color(0.400000f, 0.400000f, 1.000000f), new Color(0.400000f, 0.400000f, 0.800000f), new Color(0.400000f, 0.400000f, 0.600000f), new Color(0.400000f, 0.400000f, 0.400000f), new Color(0.400000f, 0.400000f, 0.200000f), new Color(0.400000f, 0.400000f, 0.000000f), new Color(0.400000f, 0.200000f, 1.000000f), new Color(0.400000f, 0.200000f, 0.800000f), new Color(0.400000f, 0.200000f, 0.600000f), new Color(0.400000f, 0.200000f, 0.400000f), new Color(0.400000f, 0.200000f, 0.200000f), new Color(0.400000f, 0.200000f, 0.000000f), new Color(0.400000f, 0.000000f, 1.000000f), new Color(0.400000f, 0.000000f, 0.800000f), new Color(0.400000f, 0.000000f, 0.600000f), new Color(0.400000f, 0.000000f, 0.400000f), new Color(0.400000f, 0.000000f, 0.200000f), new Color(0.400000f, 0.000000f, 0.000000f), new Color(0.200000f, 1.000000f, 1.000000f), new Color(0.200000f, 1.000000f, 0.800000f), new Color(0.200000f, 1.000000f, 0.600000f), new Color(0.200000f, 1.000000f, 0.400000f), new Color(0.200000f, 1.000000f, 0.200000f), new Color(0.200000f, 1.000000f, 0.000000f), new Color(0.200000f, 0.800000f, 1.000000f), new Color(0.200000f, 0.800000f, 0.800000f), new Color(0.200000f, 0.800000f, 0.600000f), new Color(0.200000f, 0.800000f, 0.400000f), new Color(0.200000f, 0.800000f, 0.200000f), new Color(0.200000f, 0.800000f, 0.000000f), new Color(0.200000f, 0.600000f, 1.000000f), new Color(0.200000f, 0.600000f, 0.800000f), new Color(0.200000f, 0.600000f, 0.600000f), new Color(0.200000f, 0.600000f, 0.400000f), new Color(0.200000f, 0.600000f, 0.200000f), new Color(0.200000f, 0.600000f, 0.000000f), new Color(0.200000f, 0.400000f, 1.000000f), new Color(0.200000f, 0.400000f, 0.800000f), new Color(0.200000f, 0.400000f, 0.600000f), new Color(0.200000f, 0.400000f, 0.400000f), new Color(0.200000f, 0.400000f, 0.200000f), new Color(0.200000f, 0.400000f, 0.000000f), new Color(0.200000f, 0.200000f, 1.000000f), new Color(0.200000f, 0.200000f, 0.800000f), new Color(0.200000f, 0.200000f, 0.600000f), new Color(0.200000f, 0.200000f, 0.400000f), new Color(0.200000f, 0.200000f, 0.200000f), new Color(0.200000f, 0.200000f, 0.000000f), new Color(0.200000f, 0.000000f, 1.000000f), new Color(0.200000f, 0.000000f, 0.800000f), new Color(0.200000f, 0.000000f, 0.600000f), new Color(0.200000f, 0.000000f, 0.400000f), new Color(0.200000f, 0.000000f, 0.200000f), new Color(0.200000f, 0.000000f, 0.000000f), new Color(0.000000f, 1.000000f, 1.000000f), new Color(0.000000f, 1.000000f, 0.800000f), new Color(0.000000f, 1.000000f, 0.600000f), new Color(0.000000f, 1.000000f, 0.400000f), new Color(0.000000f, 1.000000f, 0.200000f), new Color(0.000000f, 1.000000f, 0.000000f), new Color(0.000000f, 0.800000f, 1.000000f), new Color(0.000000f, 0.800000f, 0.800000f), new Color(0.000000f, 0.800000f, 0.600000f), new Color(0.000000f, 0.800000f, 0.400000f), new Color(0.000000f, 0.800000f, 0.200000f), new Color(0.000000f, 0.800000f, 0.000000f), new Color(0.000000f, 0.600000f, 1.000000f), new Color(0.000000f, 0.600000f, 0.800000f), new Color(0.000000f, 0.600000f, 0.600000f), new Color(0.000000f, 0.600000f, 0.400000f), new Color(0.000000f, 0.600000f, 0.200000f), new Color(0.000000f, 0.600000f, 0.000000f), new Color(0.000000f, 0.400000f, 1.000000f), new Color(0.000000f, 0.400000f, 0.800000f), new Color(0.000000f, 0.400000f, 0.600000f), new Color(0.000000f, 0.400000f, 0.400000f), new Color(0.000000f, 0.400000f, 0.200000f), new Color(0.000000f, 0.400000f, 0.000000f), new Color(0.000000f, 0.200000f, 1.000000f), new Color(0.000000f, 0.200000f, 0.800000f), new Color(0.000000f, 0.200000f, 0.600000f), new Color(0.000000f, 0.200000f, 0.400000f), new Color(0.000000f, 0.200000f, 0.200000f), new Color(0.000000f, 0.200000f, 0.000000f), new Color(0.000000f, 0.000000f, 1.000000f), new Color(0.000000f, 0.000000f, 0.800000f), new Color(0.000000f, 0.000000f, 0.600000f), new Color(0.000000f, 0.000000f, 0.400000f), new Color(0.000000f, 0.000000f, 0.200000f), new Color(0.933333f, 0.000000f, 0.000000f), new Color(0.866667f, 0.000000f, 0.000000f), new Color(0.733333f, 0.000000f, 0.000000f), new Color(0.666667f, 0.000000f, 0.000000f), new Color(0.533333f, 0.000000f, 0.000000f), new Color(0.466667f, 0.000000f, 0.000000f), new Color(0.333333f, 0.000000f, 0.000000f), new Color(0.266667f, 0.000000f, 0.000000f), new Color(0.133333f, 0.000000f, 0.000000f), new Color(0.066667f, 0.000000f, 0.000000f), new Color(0.000000f, 0.933333f, 0.000000f), new Color(0.000000f, 0.866667f, 0.000000f), new Color(0.000000f, 0.733333f, 0.000000f), new Color(0.000000f, 0.666667f, 0.000000f), new Color(0.000000f, 0.533333f, 0.000000f), new Color(0.000000f, 0.466667f, 0.000000f), new Color(0.000000f, 0.333333f, 0.000000f), new Color(0.000000f, 0.266667f, 0.000000f), new Color(0.000000f, 0.133333f, 0.000000f), new Color(0.000000f, 0.066667f, 0.000000f), new Color(0.000000f, 0.000000f, 0.933333f), new Color(0.000000f, 0.000000f, 0.866667f), new Color(0.000000f, 0.000000f, 0.733333f), new Color(0.000000f, 0.000000f, 0.666667f), new Color(0.000000f, 0.000000f, 0.533333f), new Color(0.000000f, 0.000000f, 0.466667f), new Color(0.000000f, 0.000000f, 0.333333f), new Color(0.000000f, 0.000000f, 0.266667f), new Color(0.000000f, 0.000000f, 0.133333f), new Color(0.000000f, 0.000000f, 0.066667f), new Color(0.933333f, 0.933333f, 0.933333f), new Color(0.866667f, 0.866667f, 0.866667f), new Color(0.733333f, 0.733333f, 0.733333f), new Color(0.666667f, 0.666667f, 0.666667f), new Color(0.533333f, 0.533333f, 0.533333f), new Color(0.466667f, 0.466667f, 0.466667f), new Color(0.333333f, 0.333333f, 0.333333f), new Color(0.266667f, 0.266667f, 0.266667f), new Color(0.133333f, 0.133333f, 0.133333f), new Color(0.066667f, 0.066667f, 0.066667f), new Color(0.000000f, 0.000000f, 0.000000f) }; #endregion } public static class MVImporter { public static Material DefaultMaterial { get { return new Material (Shader.Find ("MagicaVoxel/FlatColor")); } } public static MVMainChunk LoadVOXFromData(byte[] data, MVVoxelChunk alphaMask = null, bool generateFaces = false) { using (MemoryStream ms = new MemoryStream (data)) { using (BinaryReader br = new BinaryReader (ms)) { MVMainChunk mainChunk = new MVMainChunk (); // "VOX " br.ReadInt32 (); // "VERSION " mainChunk.version = br.ReadBytes(4); byte[] chunkId = br.ReadBytes (4); if (chunkId [0] != 'M' || chunkId [1] != 'A' || chunkId [2] != 'I' || chunkId [3] != 'N') { Debug.LogError ("[MVImport] Invalid MainChunk ID, main chunk expected"); return null; } int chunkSize = br.ReadInt32 (); int childrenSize = br.ReadInt32 (); // main chunk should have nothing... skip br.ReadBytes (chunkSize); int readSize = 0; while (readSize < childrenSize) { chunkId = br.ReadBytes (4); if (chunkId [0] == 'S' && chunkId [1] == 'I' && chunkId [2] == 'Z' && chunkId [3] == 'E') { readSize += ReadSizeChunk (br, mainChunk); } else if (chunkId [0] == 'X' && chunkId [1] == 'Y' && chunkId [2] == 'Z' && chunkId [3] == 'I') { readSize += ReadVoxelChunk (br, mainChunk.voxelChunk); } else if (chunkId [0] == 'R' && chunkId [1] == 'G' && chunkId [2] == 'B' && chunkId [3] == 'A') { mainChunk.palatte = new Color[256]; readSize += ReadPalattee (br, mainChunk.palatte); } else { Debug.LogError ("[MVImport] Chunk ID not recognized, got " + System.Text.Encoding.ASCII.GetString(chunkId)); break; } } mainChunk.alphaMaskChunk = alphaMask; if (generateFaces) GenerateFaces(mainChunk.voxelChunk, alphaMask); if (mainChunk.palatte == null) mainChunk.palatte = MVMainChunk.defaultPalatte; return mainChunk; } } } public static MVMainChunk LoadVOX(string path, MVVoxelChunk alphaMask = null, bool generateFaces = false) { byte[] bytes = File.ReadAllBytes (path); if (bytes [0] != 'V' || bytes [1] != 'O' || bytes [2] != 'X' || bytes [3] != ' ') { Debug.LogError ("Invalid VOX file, magic number mismatch"); return null; } return LoadVOXFromData (bytes, alphaMask, generateFaces); } public static void GenerateFaces(MVVoxelChunk voxelChunk, MVVoxelChunk alphaMask) { voxelChunk.faces = new MVFaceCollection[6]; for (int i = 0; i < 6; ++i) { voxelChunk.faces [i].colorIndices = new byte[voxelChunk.sizeX, voxelChunk.sizeY, voxelChunk.sizeZ]; } for (int x = 0; x < voxelChunk.sizeX; ++x) { for (int y = 0; y < voxelChunk.sizeY; ++y) { for (int z = 0; z < voxelChunk.sizeZ; ++z) { int alpha = alphaMask == null ? (byte)0 : alphaMask.voxels[x, y, z]; // left right if (x == 0 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x - 1, y, z)) voxelChunk.faces [(int)MVFaceDir.XNeg].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; if (x == voxelChunk.sizeX - 1 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x + 1, y, z)) voxelChunk.faces [(int)MVFaceDir.XPos].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; // up down if (y == 0 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x, y - 1, z)) voxelChunk.faces [(int)MVFaceDir.YNeg].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; if (y == voxelChunk.sizeY - 1 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x, y + 1, z)) voxelChunk.faces [(int)MVFaceDir.YPos].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; // forward backward if (z == 0 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x, y, z - 1)) voxelChunk.faces [(int)MVFaceDir.ZNeg].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; if (z == voxelChunk.sizeZ - 1 || DetermineEmptyOrOtherAlphaVoxel(voxelChunk, alphaMask, alpha, x, y, z + 1)) voxelChunk.faces [(int)MVFaceDir.ZPos].colorIndices [x, y, z] = voxelChunk.voxels [x, y, z]; } } } } static int ReadSizeChunk(BinaryReader br, MVMainChunk mainChunk) { int chunkSize = br.ReadInt32 (); int childrenSize = br.ReadInt32 (); mainChunk.sizeX = br.ReadInt32 (); mainChunk.sizeZ = br.ReadInt32 (); mainChunk.sizeY = br.ReadInt32 (); mainChunk.voxelChunk = new MVVoxelChunk (); mainChunk.voxelChunk.voxels = new byte[mainChunk.sizeX, mainChunk.sizeY, mainChunk.sizeZ]; Debug.Log (string.Format ("[MVImporter] Voxel Size {0}x{1}x{2}", mainChunk.sizeX, mainChunk.sizeY, mainChunk.sizeZ)); if (childrenSize > 0) { br.ReadBytes (childrenSize); Debug.LogWarning ("[MVImporter] Nested chunk not supported"); } return chunkSize + childrenSize + 4 * 3; } static int ReadVoxelChunk(BinaryReader br, MVVoxelChunk chunk) { int chunkSize = br.ReadInt32 (); int childrenSize = br.ReadInt32 (); int numVoxels = br.ReadInt32 (); for (int i = 0; i < numVoxels; ++i) { int x = (int)br.ReadByte (); int z = (int)br.ReadByte (); int y = (int)br.ReadByte (); chunk.voxels [x, y, z] = br.ReadByte(); } if (childrenSize > 0) { br.ReadBytes (childrenSize); Debug.LogWarning ("[MVImporter] Nested chunk not supported"); } return chunkSize + childrenSize + 4 * 3; } static int ReadPalattee(BinaryReader br, Color[] colors) { int chunkSize = br.ReadInt32 (); int childrenSize = br.ReadInt32 (); for (int i = 0; i < 256; ++i) { colors [i] = new Color ((float)br.ReadByte () / 255.0f, (float)br.ReadByte () / 255.0f, (float)br.ReadByte () / 255.0f, (float)br.ReadByte () / 255.0f); } if (childrenSize > 0) { br.ReadBytes (childrenSize); Debug.LogWarning ("[MVImporter] Nested chunk not supported"); } return chunkSize + childrenSize + 4 * 3; } public static Mesh[] CreateMeshes(MVMainChunk chunk, float sizePerVox) { return CreateMeshesFromChunk(chunk.voxelChunk, chunk.palatte, sizePerVox, chunk.alphaMaskChunk); } public static GameObject[] CreateVoxelGameObjects(MVMainChunk chunk, Transform parent, Material mat, float sizePerVox) { return CreateVoxelGameObjectsForChunk(chunk.voxelChunk, chunk.palatte, parent, mat, sizePerVox, chunk.alphaMaskChunk); } public static GameObject[] CreateVoxelGameObjects(MVMainChunk chunk, Transform parent, Material mat, float sizePerVox, Vector3 origin) { return CreateVoxelGameObjectsForChunk(chunk.voxelChunk, chunk.palatte, parent, mat, sizePerVox, chunk.alphaMaskChunk, origin); } public static GameObject[] CreateIndividualVoxelGameObjects(MVMainChunk chunk, Transform parent, Material mat, float sizePerVox) { return CreateIndividualVoxelGameObjectsForChunk(chunk.voxelChunk, chunk.palatte, parent, mat, sizePerVox, chunk.alphaMaskChunk); } public static GameObject[] CreateIndividualVoxelGameObjects(MVMainChunk chunk, Transform parent, Material mat, float sizePerVox, Vector3 origin) { return CreateIndividualVoxelGameObjectsForChunk(chunk.voxelChunk, chunk.palatte, parent, mat, sizePerVox, chunk.alphaMaskChunk, origin); } public static Mesh CubeMeshWithColor(float size, Color c) { float halfSize = size / 2; Vector3[] verts = new Vector3[] { new Vector3 (-halfSize, -halfSize, -halfSize), new Vector3 (-halfSize, halfSize, -halfSize), new Vector3 (halfSize, halfSize, -halfSize), new Vector3 (halfSize, -halfSize, -halfSize), new Vector3 (halfSize, -halfSize, halfSize), new Vector3 (halfSize, halfSize, halfSize), new Vector3 (-halfSize, halfSize, halfSize), new Vector3 (-halfSize, -halfSize, halfSize) }; int[] indicies = new int[] { 0, 1, 2, // 1 0, 2, 3, 3, 2, 5, // 2 3, 5, 4, 5, 2, 1, // 3 5, 1, 6, 3, 4, 7, // 4 3, 7, 0, 0, 7, 6, // 5 0, 6, 1, 4, 5, 6, // 6 4, 6, 7 }; Color[] colors = new Color[] { c, c, c, c, c, c, c, c }; Mesh mesh = new Mesh (); mesh.vertices = verts; mesh.colors = colors; mesh.triangles = indicies; mesh.RecalculateNormals (); return mesh; } public static GameObject CreateGameObject(Transform parent, Vector3 pos, string name, Mesh mesh, Material mat) { GameObject go = new GameObject (); go.name = name; go.transform.SetParent (parent); go.transform.localPosition = pos; MeshFilter mf = go.AddComponent<MeshFilter> (); mf.mesh = mesh; MeshRenderer mr = go.AddComponent<MeshRenderer> (); mr.material = mat; return go; } public static GameObject[] CreateIndividualVoxelGameObjectsForChunk(MVVoxelChunk chunk, Color[] palatte, Transform parent, Material mat, float sizePerVox, MVVoxelChunk alphaMask) { Vector3 origin = new Vector3( (float)chunk.sizeX / 2, (float)chunk.sizeY / 2, (float)chunk.sizeZ / 2); return CreateIndividualVoxelGameObjectsForChunk(chunk, palatte, parent, mat, sizePerVox, alphaMask, origin); } public static GameObject[] CreateIndividualVoxelGameObjectsForChunk(MVVoxelChunk chunk, Color[] palatte, Transform parent, Material mat, float sizePerVox, MVVoxelChunk alphaMask, Vector3 origin) { List<GameObject> result = new List<GameObject> (); if (alphaMask != null && (alphaMask.sizeX != chunk.sizeX || alphaMask.sizeY != chunk.sizeY || alphaMask.sizeZ != chunk.sizeZ)) { Debug.LogErrorFormat("Unable to create meshes from chunk : Chunk's size ({0},{1},{2}) differs from alphaMask chunk's size ({3},{4},{5})", chunk.sizeX, chunk.sizeY, chunk.sizeZ, alphaMask.sizeX, alphaMask.sizeY, alphaMask.sizeZ); return result.ToArray(); } for (int x = 0; x < chunk.sizeX; ++x) { for (int y = 0; y < chunk.sizeY; ++y) { for (int z = 0; z < chunk.sizeZ; ++z) { if (chunk.voxels [x, y, z] != 0) { float px = (x - origin.x + 0.5f) * sizePerVox, py = (y - origin.y + 0.5f) * sizePerVox, pz = (z - origin.z + 0.5f) * sizePerVox; Color c = palatte [chunk.voxels [x, y, z] - 1]; if (alphaMask != null && alphaMask.voxels[x, y, z] != 0) c.a = (float)(alphaMask.voxels [x, y, z] - 1) / 255; GameObject go = CreateGameObject ( parent, new Vector3 (px, py, pz), string.Format ("Voxel ({0}, {1}, {2})", x, y, z), MVImporter.CubeMeshWithColor (sizePerVox, c), mat); MVVoxModelVoxel v = go.AddComponent<MVVoxModelVoxel> (); v.voxel = new MVVoxel () { x = (byte)x, y = (byte)y, z = (byte)z, colorIndex = chunk.voxels [x, y, z] }; result.Add (go); } } } } return result.ToArray(); } public static GameObject[] CreateVoxelGameObjectsForChunk(MVVoxelChunk chunk, Color[] palatte, Transform parent, Material mat, float sizePerVox, MVVoxelChunk alphaMask) { Vector3 origin = new Vector3( (float)chunk.sizeX / 2, (float)chunk.sizeY / 2, (float)chunk.sizeZ / 2); return CreateVoxelGameObjectsForChunk(chunk, palatte, parent, mat, sizePerVox, alphaMask, origin); } public static GameObject[] CreateVoxelGameObjectsForChunk(MVVoxelChunk chunk, Color[] palatte, Transform parent, Material mat, float sizePerVox, MVVoxelChunk alphaMask, Vector3 origin) { List<GameObject> result = new List<GameObject> (); Mesh[] meshes = CreateMeshesFromChunk (chunk, palatte, sizePerVox, alphaMask, origin); int index = 0; foreach (Mesh mesh in meshes) { GameObject go = new GameObject (); go.name = string.Format ("VoxelMesh ({0})", index); go.transform.SetParent (parent); go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.Euler (Vector3.zero); go.transform.localScale = Vector3.one; MeshFilter mf = go.AddComponent<MeshFilter> (); mf.mesh = mesh; MeshRenderer mr = go.AddComponent<MeshRenderer> (); mr.material = mat; go.AddComponent<MVVoxModelMesh> (); result.Add (go); index++; } return result.ToArray (); } public static Mesh[] CreateMeshesFromChunk(MVVoxelChunk chunk, Color[] palatte, float sizePerVox, MVVoxelChunk alphaMask) { Vector3 origin = new Vector3( (float)chunk.sizeX / 2, (float)chunk.sizeY / 2, (float)chunk.sizeZ / 2); return CreateMeshesFromChunk(chunk, palatte, sizePerVox, alphaMask, origin); } public static Mesh[] CreateMeshesFromChunk(MVVoxelChunk chunk, Color[] palatte, float sizePerVox, MVVoxelChunk alphaMask, Vector3 origin) { if (alphaMask != null && (alphaMask.sizeX != chunk.sizeX || alphaMask.sizeY != chunk.sizeY || alphaMask.sizeZ != chunk.sizeZ)) { Debug.LogErrorFormat("Unable to create meshes from chunk : Chunk's size ({0},{1},{2}) differs from alphaMask chunk's size ({3},{4},{5})", chunk.sizeX, chunk.sizeY, chunk.sizeZ, alphaMask.sizeX, alphaMask.sizeY, alphaMask.sizeZ); return new Mesh[] { }; } List<Vector3> verts = new List<Vector3> (); List<Vector3> normals = new List<Vector3> (); List<Color> colors = new List<Color> (); List<int> indicies = new List<int> (); Vector3[] faceNormals = new Vector3[] { Vector3.right, Vector3.left, Vector3.up, Vector3.down, Vector3.forward, Vector3.back }; List<Mesh> result = new List<Mesh> (); if (sizePerVox <= 0.0f) sizePerVox = 0.1f; float halfSize = sizePerVox / 2.0f; int currentQuadCount = 0; int totalQuadCount = 0; for (int f = 0; f < 6; ++f) { for (int x = 0; x < chunk.sizeX; ++x) { for (int y = 0; y < chunk.sizeY; ++y) { for (int z = 0; z < chunk.sizeZ; ++z) { int cidx = chunk.faces [f].colorIndices [x, y, z]; int alpha = alphaMask == null ? (byte)0 : alphaMask.voxels[x, y, z]; if (cidx != 0) { float px = (x - origin.x + 0.5f) * sizePerVox, py = (y - origin.y + 0.5f) * sizePerVox, pz = (z - origin.z + 0.5f) * sizePerVox; int rx = x, ry = y, rz = z; switch (f) { case 1: case 0: { ry = y + 1; while (ry < chunk.sizeY && CompareColor(cidx, alpha, chunk, alphaMask, f, x, ry, z)) ry++; ry--; rz = z + 1; while (rz < chunk.sizeZ) { bool inc = true; for (int k = y; k <= ry; ++k) { inc = inc & (CompareColor(cidx, alpha, chunk, alphaMask, f, x, k, rz)); } if (inc) rz++; else break; } rz--; break; } case 3: case 2: { rx = x + 1; while (rx < chunk.sizeX && CompareColor(cidx, alpha, chunk, alphaMask, f, rx, y, z)) rx++; rx--; rz = z + 1; while (rz < chunk.sizeZ) { bool inc = true; for (int k = x; k <= rx; ++k) { inc = inc & (CompareColor(cidx, alpha, chunk, alphaMask, f, k, y, rz)); } if (inc) rz++; else break; } rz--; break; } case 5: case 4: { rx = x + 1; while (rx < chunk.sizeX && CompareColor(cidx, alpha, chunk, alphaMask, f, rx, y, z)) rx++; rx--; ry = y + 1; while (ry < chunk.sizeY) { bool inc = true; for (int k = x; k <= rx; ++k) { inc = inc & (CompareColor(cidx, alpha, chunk, alphaMask, f, k, ry, z)); } if (inc) ry++; else break; } ry--; break; } } for (int kx = x; kx <= rx; ++kx) { for (int ky = y; ky <= ry; ++ky) { for (int kz = z; kz <= rz; ++kz) { if(kx != x || ky != y || kz != z) chunk.faces [f].colorIndices [kx, ky, kz] = 0; } } } int dx = rx - x; int dy = ry - y; int dz = rz - z; switch (f) { case 1: verts.Add (new Vector3 (px - halfSize, py - halfSize, pz - halfSize)); verts.Add (new Vector3 (px - halfSize, py - halfSize, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px - halfSize, py + halfSize + sizePerVox * dy, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px - halfSize, py + halfSize + sizePerVox * dy, pz - halfSize)); break; case 0: verts.Add (new Vector3 (px + halfSize, py - halfSize, pz - halfSize)); verts.Add (new Vector3 (px + halfSize, py + halfSize + sizePerVox * dy, pz - halfSize)); verts.Add (new Vector3 (px + halfSize, py + halfSize + sizePerVox * dy, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px + halfSize, py - halfSize, pz + halfSize + sizePerVox * dz)); break; case 3: verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py - halfSize, pz - halfSize)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py - halfSize, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px - halfSize, py - halfSize, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px - halfSize, py - halfSize, pz - halfSize)); break; case 2: verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py + halfSize, pz - halfSize)); verts.Add (new Vector3 (px - halfSize, py + halfSize, pz - halfSize)); verts.Add (new Vector3 (px - halfSize, py + halfSize, pz + halfSize + sizePerVox * dz)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py + halfSize, pz + halfSize + sizePerVox * dz)); break; case 5: verts.Add (new Vector3 (px - halfSize, py + halfSize + sizePerVox * dy, pz - halfSize)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py + halfSize + sizePerVox * dy, pz - halfSize)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py - halfSize, pz - halfSize)); verts.Add (new Vector3 (px - halfSize, py - halfSize, pz - halfSize)); break; case 4: verts.Add (new Vector3 (px - halfSize, py + halfSize + sizePerVox * dy, pz + halfSize)); verts.Add (new Vector3 (px - halfSize, py - halfSize, pz + halfSize)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py - halfSize, pz + halfSize)); verts.Add (new Vector3 (px + halfSize + sizePerVox * dx, py + halfSize + sizePerVox * dy, pz + halfSize)); break; } normals.Add (faceNormals [f]); normals.Add (faceNormals [f]); normals.Add (faceNormals [f]); normals.Add (faceNormals [f]); // color index starts with 1 Color c = palatte [cidx - 1]; if (alpha != 0) c.a = (float)(alpha - 1) / 255; colors.Add (c); colors.Add (c); colors.Add (c); colors.Add (c); indicies.Add (currentQuadCount * 4 + 0); indicies.Add (currentQuadCount * 4 + 1); indicies.Add (currentQuadCount * 4 + 2); indicies.Add (currentQuadCount * 4 + 2); indicies.Add (currentQuadCount * 4 + 3); indicies.Add (currentQuadCount * 4 + 0); currentQuadCount += 1; // u3d max if (verts.Count + 4 >= 65000) { Mesh mesh = new Mesh (); mesh.vertices = verts.ToArray(); mesh.colors = colors.ToArray(); mesh.normals = normals.ToArray(); mesh.triangles = indicies.ToArray (); ; result.Add (mesh); verts.Clear (); colors.Clear (); normals.Clear (); indicies.Clear (); totalQuadCount += currentQuadCount; currentQuadCount = 0; } } } } } } if (verts.Count > 0) { Mesh mesh = new Mesh (); mesh.vertices = verts.ToArray(); mesh.colors = colors.ToArray(); mesh.normals = normals.ToArray(); mesh.triangles = indicies.ToArray (); ; result.Add (mesh); totalQuadCount += currentQuadCount; } Debug.Log (string.Format ("[MVImport] Mesh generated, total quads {0}", totalQuadCount)); return result.ToArray(); } private static bool CompareColor(int cidx, int alpha, MVVoxelChunk chunk, MVVoxelChunk alphaChunk, int f, int x, int y, int z) { if (alphaChunk == null) return chunk.faces[f].colorIndices[x, y, z] == cidx; else return chunk.faces[f].colorIndices[x, y, z] == cidx && alphaChunk.voxels[x, y, z] == alpha; } private static bool DetermineEmptyOrOtherAlphaVoxel(MVVoxelChunk voxelChunk, MVVoxelChunk alphaMask, int a, int x, int y, int z) { bool isEmpty = voxelChunk.voxels[x, y, z] == 0; if (alphaMask == null) return isEmpty; else { bool otherAlpha = alphaMask.voxels[x, y, z] != a; return isEmpty || otherAlpha; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using RRLab.PhysiologyWorkbench.Data; namespace RRLab.PhysiologyDataWorkshop { public partial class HomePanel : UserControl, INotifyPropertyChanged { public enum WhoseData { Me, Everybody }; public enum DatesToShow { Today, ThisWeek, ThisMonth, Anytime }; public event EventHandler ProgramChanged; private PhysiologyDataWorkshopProgram _Program; [Bindable(true)] public PhysiologyDataWorkshopProgram Program { get { return _Program; } set { if (Program != null) Program.DataSetChanged -= new EventHandler(OnDataSetChanged); _Program = value; if (Program != null) { ProgramBindingSource.DataSource = Program; Program.DataSetChanged += new EventHandler(OnDataSetChanged); } else ProgramBindingSource.DataSource = typeof(PhysiologyDataWorkshopProgram); OnDataSetChanged(this, EventArgs.Empty); if (ProgramChanged != null) ProgramChanged(this, EventArgs.Empty); NotifyPropertyChanged("Program"); } } public event EventHandler WhoseDataIsShownChanged; private WhoseData _WhoseDataIsShown = WhoseData.Me; [Bindable(true)] [SettingsBindable(true)] [DefaultValue(HomePanel.WhoseData.Me)] public WhoseData WhoseDataIsShown { get { return _WhoseDataIsShown; } set { _WhoseDataIsShown = value; OnWhoseDataIsShownChanged(EventArgs.Empty); NotifyPropertyChanged("WhoseDataIsShown"); } } public event EventHandler WhichDatesToShowChanged; private DatesToShow _WhichDatesToShow = DatesToShow.Anytime; [Bindable(true)] [SettingsBindable(true)] [DefaultValue(HomePanel.DatesToShow.Anytime)] public DatesToShow WhichDatesToShow { get { return _WhichDatesToShow; } set { _WhichDatesToShow = value; OnWhichDatesToShowChanged(EventArgs.Empty); NotifyPropertyChanged("WhichDatesToShow"); } } public HomePanel() { InitializeComponent(); } protected virtual void OnDataSetChanged(object sender, EventArgs e) { if (Program != null && Program.DataSet != null) { CellsBindingSource.DataSource = Program.DataSet; } else { CellsBindingSource.DataSource = typeof(PhysiologyDataSet); } CheckIfControlShouldBeEnabled(); } protected virtual void CheckIfControlShouldBeEnabled() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(CheckIfControlShouldBeEnabled)); return; } if (Program == null || Program.DataSet == null || !(CellsBindingSource.Current is DataRowView)) Enabled = false; else Enabled = true; } private void OnCurrentCellChanged(object sender, EventArgs e) { if (CellsDataGridView.CurrentRow != null && Program != null) Program.CurrentCellID = (int)CellsDataGridView.CurrentRow.Cells[0].Value; } private void OnDatesToShowSelectionChanged(object sender, EventArgs e) { switch (DateRangeComboBox.Text) { case "Today": WhichDatesToShow = DatesToShow.Today; break; case "This Week": WhichDatesToShow = DatesToShow.ThisWeek; break; case "This Month": WhichDatesToShow = DatesToShow.ThisMonth; break; case "Anytime": default: WhichDatesToShow = DatesToShow.Anytime; break; } } private void OnWhoseDataSelectionChanged(object sender, EventArgs e) { switch (WhoseDataComboBox.Text) { case "Me": WhoseDataIsShown = WhoseData.Me; break; case "Everybody": WhoseDataIsShown = WhoseData.Everybody; break; default: WhoseDataIsShown = WhoseData.Everybody; break; } } protected virtual void OnWhoseDataIsShownChanged(EventArgs e) { UpdateDataFilter(); if(WhoseDataIsShownChanged != null) try { WhoseDataIsShownChanged(this, e); } catch (Exception x) { ; } } protected virtual void OnWhichDatesToShowChanged(EventArgs e) { UpdateDataFilter(); if (WhichDatesToShowChanged != null) try { WhichDatesToShowChanged(this, e); } catch (Exception x) { ; } } protected virtual void UpdateDataFilter() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(UpdateDataFilter)); return; } string userFilter = null; if (WhoseDataIsShown == WhoseData.Me) userFilter = String.Format("UserID = {0}", Program.MyUserID); string dateFilter = null; switch (WhichDatesToShow) { case DatesToShow.Today: dateFilter = String.Format("Created = '{0}/{1}/{2}'", DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day); break; case DatesToShow.ThisWeek: DateTime beginningOfWeek = DateTime.Today; beginningOfWeek = beginningOfWeek.AddDays(1-(int)beginningOfWeek.DayOfWeek); DateTime endOfWeek = DateTime.Today; endOfWeek = endOfWeek.AddDays(7 - (int)endOfWeek.DayOfWeek); dateFilter = String.Format("Created > '{0}/{1}/{2}' AND Created < '{3}/{4}/{5}'", beginningOfWeek.Year, beginningOfWeek.Month, beginningOfWeek.Day, endOfWeek.Year, endOfWeek.Month, endOfWeek.Day); break; case DatesToShow.ThisMonth: DateTime beginningOfMonth = DateTime.Today; beginningOfMonth = beginningOfMonth.AddDays(1-beginningOfMonth.Day); DateTime endOfMonth = beginningOfMonth.AddMonths(1).AddDays(-1); dateFilter = String.Format("Created > '{0}/{1}/{2}' AND Created < '{3}/{4}/{5}'", beginningOfMonth.Year, beginningOfMonth.Month, beginningOfMonth.Day, endOfMonth.Year, endOfMonth.Month, endOfMonth.Day); break; default: break; } if (userFilter != null && dateFilter != null) CellsBindingSource.Filter = String.Format("({0}) AND ({1})", userFilter, dateFilter); else if (userFilter != null) CellsBindingSource.Filter = userFilter; else CellsBindingSource.Filter = dateFilter; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; protected void NotifyPropertyChanged(string property) { if(PropertyChanged != null) try { PropertyChanged(this, new PropertyChangedEventArgs(property)); } catch (Exception x) { ; } } #endregion } }
// ReSharper disable All using System.Collections.Generic; using System.Dynamic; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Controllers; using Frapid.ApplicationState.Cache; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.Config.DataAccess; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.Framework; using Frapid.Framework.Extensions; using Frapid.WebApi; namespace Frapid.Config.Api { /// <summary> /// Provides a direct HTTP access to perform various tasks such as adding, editing, and removing Custom Field Forms. /// </summary> [RoutePrefix("api/v1.0/config/custom-field-form")] public class CustomFieldFormController : FrapidApiController { /// <summary> /// The CustomFieldForm repository. /// </summary> private ICustomFieldFormRepository CustomFieldFormRepository; public CustomFieldFormController() { } public CustomFieldFormController(ICustomFieldFormRepository repository) { this.CustomFieldFormRepository = repository; } protected override void Initialize(HttpControllerContext context) { base.Initialize(context); if (this.CustomFieldFormRepository == null) { this.CustomFieldFormRepository = new Frapid.Config.DataAccess.CustomFieldForm { _Catalog = this.MetaUser.Catalog, _LoginId = this.MetaUser.LoginId, _UserId = this.MetaUser.UserId }; } } /// <summary> /// Creates meta information of "custom field form" entity. /// </summary> /// <returns>Returns the "custom field form" meta information to perform CRUD operation.</returns> [AcceptVerbs("GET", "HEAD")] [Route("meta")] [Route("~/api/config/custom-field-form/meta")] [RestAuthorize] public EntityView GetEntityView() { return new EntityView { PrimaryKey = "form_name", Columns = new List<EntityColumn>() { new EntityColumn { ColumnName = "form_name", PropertyName = "FormName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = true, IsSerial = false, Value = "", MaxLength = 100 }, new EntityColumn { ColumnName = "table_name", PropertyName = "TableName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 }, new EntityColumn { ColumnName = "key_name", PropertyName = "KeyName", DataType = "string", DbDataType = "varchar", IsNullable = false, IsPrimaryKey = false, IsSerial = false, Value = "", MaxLength = 100 } } }; } /// <summary> /// Counts the number of custom field forms. /// </summary> /// <returns>Returns the count of the custom field forms.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count")] [Route("~/api/config/custom-field-form/count")] [RestAuthorize] public long Count() { try { return this.CustomFieldFormRepository.Count(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns all collection of custom field form. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("all")] [Route("~/api/config/custom-field-form/all")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> GetAll() { try { return this.CustomFieldFormRepository.GetAll(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns collection of custom field form for export. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("export")] [Route("~/api/config/custom-field-form/export")] [RestAuthorize] public IEnumerable<dynamic> Export() { try { return this.CustomFieldFormRepository.Export(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns an instance of custom field form. /// </summary> /// <param name="formName">Enter FormName to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("{formName}")] [Route("~/api/config/custom-field-form/{formName}")] [RestAuthorize] public Frapid.Config.Entities.CustomFieldForm Get(string formName) { try { return this.CustomFieldFormRepository.Get(formName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } [AcceptVerbs("GET", "HEAD")] [Route("get")] [Route("~/api/config/custom-field-form/get")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> Get([FromUri] string[] formNames) { try { return this.CustomFieldFormRepository.Get(formNames); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the first instance of custom field form. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("first")] [Route("~/api/config/custom-field-form/first")] [RestAuthorize] public Frapid.Config.Entities.CustomFieldForm GetFirst() { try { return this.CustomFieldFormRepository.GetFirst(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the previous instance of custom field form. /// </summary> /// <param name="formName">Enter FormName to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("previous/{formName}")] [Route("~/api/config/custom-field-form/previous/{formName}")] [RestAuthorize] public Frapid.Config.Entities.CustomFieldForm GetPrevious(string formName) { try { return this.CustomFieldFormRepository.GetPrevious(formName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the next instance of custom field form. /// </summary> /// <param name="formName">Enter FormName to search for.</param> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("next/{formName}")] [Route("~/api/config/custom-field-form/next/{formName}")] [RestAuthorize] public Frapid.Config.Entities.CustomFieldForm GetNext(string formName) { try { return this.CustomFieldFormRepository.GetNext(formName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Returns the last instance of custom field form. /// </summary> /// <returns></returns> [AcceptVerbs("GET", "HEAD")] [Route("last")] [Route("~/api/config/custom-field-form/last")] [RestAuthorize] public Frapid.Config.Entities.CustomFieldForm GetLast() { try { return this.CustomFieldFormRepository.GetLast(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field forms on each page, sorted by the property FormName. /// </summary> /// <returns>Returns the first page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("")] [Route("~/api/config/custom-field-form")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> GetPaginatedResult() { try { return this.CustomFieldFormRepository.GetPaginatedResult(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a paginated collection containing 10 custom field forms on each page, sorted by the property FormName. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset.</param> /// <returns>Returns the requested page from the collection.</returns> [AcceptVerbs("GET", "HEAD")] [Route("page/{pageNumber}")] [Route("~/api/config/custom-field-form/page/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> GetPaginatedResult(long pageNumber) { try { return this.CustomFieldFormRepository.GetPaginatedResult(pageNumber); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field forms using the supplied filter(s). /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the count of filtered custom field forms.</returns> [AcceptVerbs("POST")] [Route("count-where")] [Route("~/api/config/custom-field-form/count-where")] [RestAuthorize] public long CountWhere([FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldFormRepository.CountWhere(f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field forms on each page, sorted by the property FormName. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("POST")] [Route("get-where/{pageNumber}")] [Route("~/api/config/custom-field-form/get-where/{pageNumber}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> GetWhere(long pageNumber, [FromBody]JArray filters) { try { List<Frapid.DataAccess.Models.Filter> f = filters.ToObject<List<Frapid.DataAccess.Models.Filter>>(JsonHelper.GetJsonSerializer()); return this.CustomFieldFormRepository.GetWhere(pageNumber, f); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Counts the number of custom field forms using the supplied filter name. /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns the count of filtered custom field forms.</returns> [AcceptVerbs("GET", "HEAD")] [Route("count-filtered/{filterName}")] [Route("~/api/config/custom-field-form/count-filtered/{filterName}")] [RestAuthorize] public long CountFiltered(string filterName) { try { return this.CustomFieldFormRepository.CountFiltered(filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Creates a filtered and paginated collection containing 10 custom field forms on each page, sorted by the property FormName. /// </summary> /// <param name="pageNumber">Enter the page number to produce the resultset. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns the requested page from the collection using the supplied filters.</returns> [AcceptVerbs("GET", "HEAD")] [Route("get-filtered/{pageNumber}/{filterName}")] [Route("~/api/config/custom-field-form/get-filtered/{pageNumber}/{filterName}")] [RestAuthorize] public IEnumerable<Frapid.Config.Entities.CustomFieldForm> GetFiltered(long pageNumber, string filterName) { try { return this.CustomFieldFormRepository.GetFiltered(pageNumber, filterName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Displayfield is a lightweight key/value collection of custom field forms. /// </summary> /// <returns>Returns an enumerable key/value collection of custom field forms.</returns> [AcceptVerbs("GET", "HEAD")] [Route("display-fields")] [Route("~/api/config/custom-field-form/display-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.DisplayField> GetDisplayFields() { try { return this.CustomFieldFormRepository.GetDisplayFields(); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for custom field forms. /// </summary> /// <returns>Returns an enumerable custom field collection of custom field forms.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields")] [Route("~/api/config/custom-field-form/custom-fields")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields() { try { return this.CustomFieldFormRepository.GetCustomFields(null); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// A custom field is a user defined field for custom field forms. /// </summary> /// <returns>Returns an enumerable custom field collection of custom field forms.</returns> [AcceptVerbs("GET", "HEAD")] [Route("custom-fields/{resourceId}")] [Route("~/api/config/custom-field-form/custom-fields/{resourceId}")] [RestAuthorize] public IEnumerable<Frapid.DataAccess.Models.CustomField> GetCustomFields(string resourceId) { try { return this.CustomFieldFormRepository.GetCustomFields(resourceId); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds or edits your instance of CustomFieldForm class. /// </summary> /// <param name="customFieldForm">Your instance of custom field forms class to add or edit.</param> [AcceptVerbs("POST")] [Route("add-or-edit")] [Route("~/api/config/custom-field-form/add-or-edit")] [RestAuthorize] public object AddOrEdit([FromBody]Newtonsoft.Json.Linq.JArray form) { dynamic customFieldForm = form[0].ToObject<ExpandoObject>(JsonHelper.GetJsonSerializer()); List<Frapid.DataAccess.Models.CustomField> customFields = form[1].ToObject<List<Frapid.DataAccess.Models.CustomField>>(JsonHelper.GetJsonSerializer()); if (customFieldForm == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { return this.CustomFieldFormRepository.AddOrEdit(customFieldForm, customFields); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Adds your instance of CustomFieldForm class. /// </summary> /// <param name="customFieldForm">Your instance of custom field forms class to add.</param> [AcceptVerbs("POST")] [Route("add/{customFieldForm}")] [Route("~/api/config/custom-field-form/add/{customFieldForm}")] [RestAuthorize] public void Add(Frapid.Config.Entities.CustomFieldForm customFieldForm) { if (customFieldForm == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.CustomFieldFormRepository.Add(customFieldForm); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Edits existing record with your instance of CustomFieldForm class. /// </summary> /// <param name="customFieldForm">Your instance of CustomFieldForm class to edit.</param> /// <param name="formName">Enter the value for FormName in order to find and edit the existing record.</param> [AcceptVerbs("PUT")] [Route("edit/{formName}")] [Route("~/api/config/custom-field-form/edit/{formName}")] [RestAuthorize] public void Edit(string formName, [FromBody] Frapid.Config.Entities.CustomFieldForm customFieldForm) { if (customFieldForm == null) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.MethodNotAllowed)); } try { this.CustomFieldFormRepository.Update(customFieldForm, formName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } private List<ExpandoObject> ParseCollection(JArray collection) { return JsonConvert.DeserializeObject<List<ExpandoObject>>(collection.ToString(), JsonHelper.GetJsonSerializerSettings()); } /// <summary> /// Adds or edits multiple instances of CustomFieldForm class. /// </summary> /// <param name="collection">Your collection of CustomFieldForm class to bulk import.</param> /// <returns>Returns list of imported formNames.</returns> /// <exception cref="DataAccessException">Thrown when your any CustomFieldForm class in the collection is invalid or malformed.</exception> [AcceptVerbs("POST")] [Route("bulk-import")] [Route("~/api/config/custom-field-form/bulk-import")] [RestAuthorize] public List<object> BulkImport([FromBody]JArray collection) { List<ExpandoObject> customFieldFormCollection = this.ParseCollection(collection); if (customFieldFormCollection == null || customFieldFormCollection.Count.Equals(0)) { return null; } try { return this.CustomFieldFormRepository.BulkImport(customFieldFormCollection); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } /// <summary> /// Deletes an existing instance of CustomFieldForm class via FormName. /// </summary> /// <param name="formName">Enter the value for FormName in order to find and delete the existing record.</param> [AcceptVerbs("DELETE")] [Route("delete/{formName}")] [Route("~/api/config/custom-field-form/delete/{formName}")] [RestAuthorize] public void Delete(string formName) { try { this.CustomFieldFormRepository.Delete(formName); } catch (UnauthorizedException) { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Forbidden)); } catch (DataAccessException ex) { throw new HttpResponseException(new HttpResponseMessage { Content = new StringContent(ex.Message), StatusCode = HttpStatusCode.InternalServerError }); } #if !DEBUG catch { throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Classes: Object Security family of classes ** ** ===========================================================*/ using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; namespace System.Security.AccessControl { public enum AccessControlModification { Add = 0, Set = 1, Reset = 2, Remove = 3, RemoveAll = 4, RemoveSpecific = 5, } public abstract class ObjectSecurity { #region Private Members private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); internal readonly CommonSecurityDescriptor _securityDescriptor; private bool _ownerModified = false; private bool _groupModified = false; private bool _saclModified = false; private bool _daclModified = false; // only these SACL control flags will be automatically carry forward // when update with new security descriptor. private static readonly ControlFlags SACL_CONTROL_FLAGS = ControlFlags.SystemAclPresent | ControlFlags.SystemAclAutoInherited | ControlFlags.SystemAclProtected; // only these DACL control flags will be automatically carry forward // when update with new security descriptor private static readonly ControlFlags DACL_CONTROL_FLAGS = ControlFlags.DiscretionaryAclPresent | ControlFlags.DiscretionaryAclAutoInherited | ControlFlags.DiscretionaryAclProtected; #endregion #region Constructors protected ObjectSecurity() { } protected ObjectSecurity( bool isContainer, bool isDS ) : this() { // we will create an empty DACL, denying anyone any access as the default. 5 is the capacity. DiscretionaryAcl dacl = new DiscretionaryAcl(isContainer, isDS, 5); _securityDescriptor = new CommonSecurityDescriptor( isContainer, isDS, ControlFlags.None, null, null, null, dacl ); } protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor) : this() { if ( securityDescriptor == null ) { throw new ArgumentNullException( nameof(securityDescriptor)); } _securityDescriptor = securityDescriptor; } #endregion #region Private methods private void UpdateWithNewSecurityDescriptor( RawSecurityDescriptor newOne, AccessControlSections includeSections ) { Debug.Assert( newOne != null, "Must not supply a null parameter here" ); if (( includeSections & AccessControlSections.Owner ) != 0 ) { _ownerModified = true; _securityDescriptor.Owner = newOne.Owner; } if (( includeSections & AccessControlSections.Group ) != 0 ) { _groupModified = true; _securityDescriptor.Group = newOne.Group; } if (( includeSections & AccessControlSections.Audit ) != 0 ) { _saclModified = true; if ( newOne.SystemAcl != null ) { _securityDescriptor.SystemAcl = new SystemAcl( IsContainer, IsDS, newOne.SystemAcl, true ); } else { _securityDescriptor.SystemAcl = null; } // carry forward the SACL related control flags _securityDescriptor.UpdateControlFlags(SACL_CONTROL_FLAGS, (ControlFlags)(newOne.ControlFlags & SACL_CONTROL_FLAGS)); } if (( includeSections & AccessControlSections.Access ) != 0 ) { _daclModified = true; if ( newOne.DiscretionaryAcl != null ) { _securityDescriptor.DiscretionaryAcl = new DiscretionaryAcl( IsContainer, IsDS, newOne.DiscretionaryAcl, true ); } else { _securityDescriptor.DiscretionaryAcl = null; } // by the following property set, the _securityDescriptor's control flags // may contains DACL present flag. That needs to be carried forward! Therefore, we OR // the current _securityDescriptor.s DACL present flag. ControlFlags daclFlag = (_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclPresent); _securityDescriptor.UpdateControlFlags(DACL_CONTROL_FLAGS, (ControlFlags)((newOne.ControlFlags | daclFlag) & DACL_CONTROL_FLAGS)); } } #endregion #region Protected Properties and Methods /// <summary> /// Gets the security descriptor for this instance. /// </summary> protected CommonSecurityDescriptor SecurityDescriptor => _securityDescriptor; protected void ReadLock() { _lock.EnterReadLock(); } protected void ReadUnlock() { _lock.ExitReadLock(); } protected void WriteLock() { _lock.EnterWriteLock(); } protected void WriteUnlock() { _lock.ExitWriteLock(); } protected bool OwnerModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _ownerModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _ownerModified = value; } } protected bool GroupModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _groupModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _groupModified = value; } } protected bool AuditRulesModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _saclModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _saclModified = value; } } protected bool AccessRulesModified { get { if (!( _lock.IsReadLockHeld || _lock.IsWriteLockHeld )) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForReadOrWrite ); } return _daclModified; } set { if ( !_lock.IsWriteLockHeld ) { throw new InvalidOperationException( SR.InvalidOperation_MustLockForWrite ); } _daclModified = value; } } protected bool IsContainer { get { return _securityDescriptor.IsContainer; } } protected bool IsDS { get { return _securityDescriptor.IsDS; } } // // Persists the changes made to the object // // This overloaded method takes a name of an existing object // protected virtual void Persist( string name, AccessControlSections includeSections ) { throw NotImplemented.ByDesign; } // // if Persist (by name) is implemented, then this function will also try to enable take ownership // privilege while persisting if the enableOwnershipPrivilege is true. // Integrators can override it if this is not desired. // protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections ) { Privilege ownerPrivilege = null; try { if (enableOwnershipPrivilege) { ownerPrivilege = new Privilege(Privilege.TakeOwnership); try { ownerPrivilege.Enable(); } catch (PrivilegeNotHeldException) { // we will ignore this exception and press on just in case this is a remote resource } } Persist(name, includeSections); } catch { // protection against exception filter-based luring attacks if ( ownerPrivilege != null ) { ownerPrivilege.Revert(); } throw; } finally { if (ownerPrivilege != null) { ownerPrivilege.Revert(); } } } // // Persists the changes made to the object // // This overloaded method takes a handle to an existing object // protected virtual void Persist( SafeHandle handle, AccessControlSections includeSections ) { throw NotImplemented.ByDesign; } #endregion #region Public Methods // // Sets and retrieves the owner of this object // public IdentityReference GetOwner( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Owner == null ) { return null; } return _securityDescriptor.Owner.Translate( targetType ); } finally { ReadUnlock(); } } public void SetOwner( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } WriteLock(); try { _securityDescriptor.Owner = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _ownerModified = true; } finally { WriteUnlock(); } } // // Sets and retrieves the group of this object // public IdentityReference GetGroup( System.Type targetType ) { ReadLock(); try { if ( _securityDescriptor.Group == null ) { return null; } return _securityDescriptor.Group.Translate( targetType ); } finally { ReadUnlock(); } } public void SetGroup( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } WriteLock(); try { _securityDescriptor.Group = identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier; _groupModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAccessRules( IdentityReference identity ) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } WriteLock(); try { _securityDescriptor.PurgeAccessControl( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _daclModified = true; } finally { WriteUnlock(); } } public virtual void PurgeAuditRules(IdentityReference identity) { if ( identity == null ) { throw new ArgumentNullException( nameof(identity)); } WriteLock(); try { _securityDescriptor.PurgeAudit( identity.Translate( typeof( SecurityIdentifier )) as SecurityIdentifier ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAccessRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetDiscretionaryAclProtection( isProtected, preserveInheritance ); _daclModified = true; } finally { WriteUnlock(); } } public bool AreAuditRulesProtected { get { ReadLock(); try { return (( _securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected ) != 0 ); } finally { ReadUnlock(); } } } public void SetAuditRuleProtection( bool isProtected, bool preserveInheritance ) { WriteLock(); try { _securityDescriptor.SetSystemAclProtection( isProtected, preserveInheritance ); _saclModified = true; } finally { WriteUnlock(); } } public bool AreAccessRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsDiscretionaryAclCanonical; } finally { ReadUnlock(); } } } public bool AreAuditRulesCanonical { get { ReadLock(); try { return _securityDescriptor.IsSystemAclCanonical; } finally { ReadUnlock(); } } } public static bool IsSddlConversionSupported() { return true; // SDDL to binary conversions are supported on Windows 2000 and higher } public string GetSecurityDescriptorSddlForm( AccessControlSections includeSections ) { ReadLock(); try { return _securityDescriptor.GetSddlForm( includeSections ); } finally { ReadUnlock(); } } public void SetSecurityDescriptorSddlForm( string sddlForm ) { SetSecurityDescriptorSddlForm( sddlForm, AccessControlSections.All ); } public void SetSecurityDescriptorSddlForm( string sddlForm, AccessControlSections includeSections ) { if ( sddlForm == null ) { throw new ArgumentNullException( nameof(sddlForm)); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( SR.Arg_EnumAtLeastOneFlag, nameof(includeSections)); } WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( sddlForm ), includeSections ); } finally { WriteUnlock(); } } public byte[] GetSecurityDescriptorBinaryForm() { ReadLock(); try { byte[] result = new byte[_securityDescriptor.BinaryLength]; _securityDescriptor.GetBinaryForm( result, 0 ); return result; } finally { ReadUnlock(); } } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm ) { SetSecurityDescriptorBinaryForm( binaryForm, AccessControlSections.All ); } public void SetSecurityDescriptorBinaryForm( byte[] binaryForm, AccessControlSections includeSections ) { if ( binaryForm == null ) { throw new ArgumentNullException( nameof(binaryForm)); } if (( includeSections & AccessControlSections.All ) == 0 ) { throw new ArgumentException( SR.Arg_EnumAtLeastOneFlag, nameof(includeSections)); } WriteLock(); try { UpdateWithNewSecurityDescriptor( new RawSecurityDescriptor( binaryForm, 0 ), includeSections ); } finally { WriteUnlock(); } } public abstract Type AccessRightType { get; } public abstract Type AccessRuleType { get; } public abstract Type AuditRuleType { get; } protected abstract bool ModifyAccess( AccessControlModification modification, AccessRule rule, out bool modified); protected abstract bool ModifyAudit( AccessControlModification modification, AuditRule rule, out bool modified ); public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( nameof(rule)); } if ( !this.AccessRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) ) { throw new ArgumentException( SR.AccessControl_InvalidAccessRuleType, nameof(rule)); } WriteLock(); try { return ModifyAccess(modification, rule, out modified); } finally { WriteUnlock(); } } public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified) { if ( rule == null ) { throw new ArgumentNullException( nameof(rule)); } if ( !this.AuditRuleType.GetTypeInfo().IsAssignableFrom(rule.GetType().GetTypeInfo()) ) { throw new ArgumentException( SR.AccessControl_InvalidAuditRuleType, nameof(rule)); } WriteLock(); try { return ModifyAudit(modification, rule, out modified); } finally { WriteUnlock(); } } public abstract AccessRule AccessRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type ); public abstract AuditRule AuditRuleFactory( IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags ); #endregion } }
using UnityEngine; using System.Collections; public class RPG_Camera : MonoBehaviour { public static RPG_Camera instance; public Transform cameraPivot; public float distance = 5f; public float distanceMax = 1000f; public float mouseSpeed = 8f; public float mouseScroll = 15f; public float mouseSmoothingFactor = 0.08f; public float camDistanceSpeed = 0.7f; public float camBottomDistance = 1f; public float firstPersonThreshold = 0.8f; public float characterFadeThreshold = 1.8f; private Vector3 desiredPosition; private float desiredDistance; private float lastDistance; private float mouseX = 0f; private float mouseXSmooth = 0f; private float mouseXVel; private float mouseY = 0f; private float mouseYSmooth = 0f; private float mouseYVel; private float mouseYMin = -89.5f; private float mouseYMax = 89.5f; private float distanceVel; private bool camBottom; private bool constraint; private static float halfFieldOfView; private static float planeAspect; private static float halfPlaneHeight; private static float halfPlaneWidth; void Awake() { instance = this; } void Start() { distance = Mathf.Clamp(distance, 0.05f, distanceMax); desiredDistance = distance; halfFieldOfView = (Camera.main.fieldOfView / 2) * Mathf.Deg2Rad; planeAspect = Camera.main.aspect; halfPlaneHeight = Camera.main.nearClipPlane * Mathf.Tan(halfFieldOfView); halfPlaneWidth = halfPlaneHeight * planeAspect; mouseX = 0f; mouseY = 15f; } public static void CameraSetup() { GameObject cameraUsed; GameObject cameraPivot; RPG_Camera cameraScript; if (Camera.main != null) cameraUsed = Camera.main.gameObject; else { cameraUsed = new GameObject("Main Camera"); cameraUsed.AddComponent<Camera>(); cameraUsed.tag = "MainCamera"; } if (!cameraUsed.GetComponent("RPG_Camera")) cameraUsed.AddComponent<RPG_Camera>(); cameraScript = cameraUsed.GetComponent("RPG_Camera") as RPG_Camera; cameraPivot = GameObject.Find("cameraPivot") as GameObject; cameraScript.cameraPivot = cameraPivot.transform; } void LateUpdate() { if (cameraPivot == null) { Debug.Log("Error: No cameraPivot found! Please read the manual for further instructions."); return; } GetInput(); GetDesiredPosition(); PositionUpdate(); CharacterFade(); } void GetInput() { if (distance > 0.1) { // distance > 0.05 would be too close, so 0.1 is fine Debug.DrawLine(transform.position, transform.position - Vector3.up * camBottomDistance, Color.green); camBottom = Physics.Linecast(transform.position, transform.position - Vector3.up * camBottomDistance); } bool constrainMouseY = camBottom && transform.position.y - cameraPivot.transform.position.y <= 0; if (Input.GetMouseButton(0) || Input.GetMouseButton(1)) { Cursor.visible = false; // if you want the cursor behavior of the version 1.0, change this line to "Screen.lockCursor = true;" mouseX += Input.GetAxis("Mouse X") * mouseSpeed; if (constrainMouseY) { if (Input.GetAxis("Mouse Y") < 0) mouseY -= Input.GetAxis("Mouse Y") * mouseSpeed; } else mouseY -= Input.GetAxis("Mouse Y") * mouseSpeed; } else Cursor.visible = true; // if you want the cursor behavior of the version 1.0, change this line to "Screen.lockCursor = false;" mouseY = ClampAngle(mouseY, -89.5f, 89.5f); mouseXSmooth = Mathf.SmoothDamp(mouseXSmooth, mouseX, ref mouseXVel, mouseSmoothingFactor); mouseYSmooth = Mathf.SmoothDamp(mouseYSmooth, mouseY, ref mouseYVel, mouseSmoothingFactor); if (constrainMouseY) mouseYMin = mouseY; else mouseYMin = -89.5f; mouseYSmooth = ClampAngle(mouseYSmooth, mouseYMin, mouseYMax); if (Input.GetMouseButton(1)) RPG_Controller.instance.transform.rotation = Quaternion.Euler(RPG_Controller.instance.transform.eulerAngles.x, Camera.main.transform.eulerAngles.y, RPG_Controller.instance.transform.eulerAngles.z); desiredDistance = desiredDistance - Input.GetAxis("Mouse ScrollWheel") * mouseScroll; if (desiredDistance > distanceMax) desiredDistance = distanceMax; if (desiredDistance < 0.05) desiredDistance = 0.05f; } void GetDesiredPosition() { distance = desiredDistance; desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance); float closestDistance; constraint = false; closestDistance = CheckCameraClipPlane(cameraPivot.position, desiredPosition); if (closestDistance != -1) { distance = closestDistance; desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance); constraint = true; } distance -= Camera.main.nearClipPlane; if (lastDistance < distance || !constraint) distance = Mathf.SmoothDamp(lastDistance, distance, ref distanceVel, camDistanceSpeed); if (distance < 0.05) distance = 0.05f; lastDistance = distance; desiredPosition = GetCameraPosition(mouseYSmooth, mouseXSmooth, distance); // if the camera view was blocked, then this is the new "forced" position } void PositionUpdate() { transform.position = desiredPosition; if (distance > 0.05) transform.LookAt(cameraPivot); } void CharacterFade() { if (RPG_Animation.instance == null) return; if (distance < firstPersonThreshold) RPG_Animation.instance.GetComponent<Renderer>().enabled = false; else if (distance < characterFadeThreshold) { RPG_Animation.instance.GetComponent<Renderer>().enabled = true; float characterAlpha = 1 - (characterFadeThreshold - distance) / (characterFadeThreshold - firstPersonThreshold); if (RPG_Animation.instance.GetComponent<Renderer>().material.color.a != characterAlpha) RPG_Animation.instance.GetComponent<Renderer>().material.color = new Color(RPG_Animation.instance.GetComponent<Renderer>().material.color.r, RPG_Animation.instance.GetComponent<Renderer>().material.color.g, RPG_Animation.instance.GetComponent<Renderer>().material.color.b, characterAlpha); } else { RPG_Animation.instance.GetComponent<Renderer>().enabled = true; if (RPG_Animation.instance.GetComponent<Renderer>().material.color.a != 1) RPG_Animation.instance.GetComponent<Renderer>().material.color = new Color(RPG_Animation.instance.GetComponent<Renderer>().material.color.r, RPG_Animation.instance.GetComponent<Renderer>().material.color.g, RPG_Animation.instance.GetComponent<Renderer>().material.color.b, 1); } } Vector3 GetCameraPosition(float xAxis, float yAxis, float distance) { Vector3 offset = new Vector3(0, 0, -distance); Quaternion rotation = Quaternion.Euler(xAxis, yAxis, 0); return cameraPivot.position + rotation * offset; } float CheckCameraClipPlane(Vector3 from, Vector3 to) { var closestDistance = -1f; RaycastHit hitInfo; ClipPlaneVertexes clipPlane = GetClipPlaneAt(to); Debug.DrawLine(clipPlane.UpperLeft, clipPlane.UpperRight); Debug.DrawLine(clipPlane.UpperRight, clipPlane.LowerRight); Debug.DrawLine(clipPlane.LowerRight, clipPlane.LowerLeft); Debug.DrawLine(clipPlane.LowerLeft, clipPlane.UpperLeft); Debug.DrawLine(from, to, Color.red); Debug.DrawLine(from - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperLeft, Color.cyan); Debug.DrawLine(from + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperRight, Color.cyan); Debug.DrawLine(from - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerLeft, Color.cyan); Debug.DrawLine(from + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerRight, Color.cyan); if (Physics.Linecast(from, to, out hitInfo) && hitInfo.collider.tag != "Player") closestDistance = hitInfo.distance - Camera.main.nearClipPlane; if (Physics.Linecast(from - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperLeft, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, from); if (Physics.Linecast(from + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, clipPlane.UpperRight, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, from); if (Physics.Linecast(from - transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerLeft, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point + transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, from); if (Physics.Linecast(from + transform.right * halfPlaneWidth - transform.up * halfPlaneHeight, clipPlane.LowerRight, out hitInfo) && hitInfo.collider.tag != "Player") if (hitInfo.distance < closestDistance || closestDistance == -1) closestDistance = Vector3.Distance(hitInfo.point - transform.right * halfPlaneWidth + transform.up * halfPlaneHeight, from); return closestDistance; } float ClampAngle(float angle, float min, float max) { while (angle < -360 || angle > 360) { if (angle < -360) angle += 360; if (angle > 360) angle -= 360; } return Mathf.Clamp(angle, min, max); } public struct ClipPlaneVertexes { public Vector3 UpperLeft; public Vector3 UpperRight; public Vector3 LowerLeft; public Vector3 LowerRight; } public static ClipPlaneVertexes GetClipPlaneAt(Vector3 pos) { var clipPlane = new ClipPlaneVertexes(); if (Camera.main == null) return clipPlane; Transform transform = Camera.main.transform; float offset = Camera.main.nearClipPlane; clipPlane.UpperLeft = pos - transform.right * halfPlaneWidth; clipPlane.UpperLeft += transform.up * halfPlaneHeight; clipPlane.UpperLeft += transform.forward * offset; clipPlane.UpperRight = pos + transform.right * halfPlaneWidth; clipPlane.UpperRight += transform.up * halfPlaneHeight; clipPlane.UpperRight += transform.forward * offset; clipPlane.LowerLeft = pos - transform.right * halfPlaneWidth; clipPlane.LowerLeft -= transform.up * halfPlaneHeight; clipPlane.LowerLeft += transform.forward * offset; clipPlane.LowerRight = pos + transform.right * halfPlaneWidth; clipPlane.LowerRight -= transform.up * halfPlaneHeight; clipPlane.LowerRight += transform.forward * offset; return clipPlane; } public void RotateWithCharacter() { float rotation = Input.GetAxis("Horizontal") * RPG_Controller.instance.turnSpeed; mouseX += rotation; } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.AutoScaling.Model { /// <summary> /// <para> A scaling Activity is a long-running process that represents a change to your AutoScalingGroup, such as changing the size of the /// group. It can also be a process to replace an instance, or a process to perform any other long-running operations supported by the API. /// </para> /// </summary> public class Activity { private string activityId; private string autoScalingGroupName; private string description; private string cause; private DateTime? startTime; private DateTime? endTime; private string statusCode; private string statusMessage; private int? progress; private string details; /// <summary> /// Specifies the ID of the activity. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string ActivityId { get { return this.activityId; } set { this.activityId = value; } } /// <summary> /// Sets the ActivityId property /// </summary> /// <param name="activityId">The value to set for the ActivityId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithActivityId(string activityId) { this.activityId = activityId; return this; } // Check to see if ActivityId property is set internal bool IsSetActivityId() { return this.activityId != null; } /// <summary> /// The name of the Auto Scaling group. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string AutoScalingGroupName { get { return this.autoScalingGroupName; } set { this.autoScalingGroupName = value; } } /// <summary> /// Sets the AutoScalingGroupName property /// </summary> /// <param name="autoScalingGroupName">The value to set for the AutoScalingGroupName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithAutoScalingGroupName(string autoScalingGroupName) { this.autoScalingGroupName = autoScalingGroupName; return this; } // Check to see if AutoScalingGroupName property is set internal bool IsSetAutoScalingGroupName() { return this.autoScalingGroupName != null; } /// <summary> /// Contains a friendly, more verbose description of the scaling activity. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// Contains the reason the activity was begun. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 1023</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string Cause { get { return this.cause; } set { this.cause = value; } } /// <summary> /// Sets the Cause property /// </summary> /// <param name="cause">The value to set for the Cause property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithCause(string cause) { this.cause = cause; return this; } // Check to see if Cause property is set internal bool IsSetCause() { return this.cause != null; } /// <summary> /// Provides the start time of this activity. /// /// </summary> public DateTime StartTime { get { return this.startTime ?? default(DateTime); } set { this.startTime = value; } } /// <summary> /// Sets the StartTime property /// </summary> /// <param name="startTime">The value to set for the StartTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithStartTime(DateTime startTime) { this.startTime = startTime; return this; } // Check to see if StartTime property is set internal bool IsSetStartTime() { return this.startTime.HasValue; } /// <summary> /// Provides the end time of this activity. /// /// </summary> public DateTime EndTime { get { return this.endTime ?? default(DateTime); } set { this.endTime = value; } } /// <summary> /// Sets the EndTime property /// </summary> /// <param name="endTime">The value to set for the EndTime property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithEndTime(DateTime endTime) { this.endTime = endTime; return this; } // Check to see if EndTime property is set internal bool IsSetEndTime() { return this.endTime.HasValue; } /// <summary> /// Contains the current status of the activity. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Allowed Values</term> /// <description>WaitingForSpotInstanceRequestId, WaitingForSpotInstanceId, WaitingForInstanceId, PreInService, InProgress, Successful, Failed, Cancelled</description> /// </item> /// </list> /// </para> /// </summary> public string StatusCode { get { return this.statusCode; } set { this.statusCode = value; } } /// <summary> /// Sets the StatusCode property /// </summary> /// <param name="statusCode">The value to set for the StatusCode property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithStatusCode(string statusCode) { this.statusCode = statusCode; return this; } // Check to see if StatusCode property is set internal bool IsSetStatusCode() { return this.statusCode != null; } /// <summary> /// Contains a friendly, more verbose description of the activity status. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 255</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string StatusMessage { get { return this.statusMessage; } set { this.statusMessage = value; } } /// <summary> /// Sets the StatusMessage property /// </summary> /// <param name="statusMessage">The value to set for the StatusMessage property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithStatusMessage(string statusMessage) { this.statusMessage = statusMessage; return this; } // Check to see if StatusMessage property is set internal bool IsSetStatusMessage() { return this.statusMessage != null; } /// <summary> /// Specifies a value between 0 and 100 that indicates the progress of the activity. /// /// </summary> public int Progress { get { return this.progress ?? default(int); } set { this.progress = value; } } /// <summary> /// Sets the Progress property /// </summary> /// <param name="progress">The value to set for the Progress property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithProgress(int progress) { this.progress = progress; return this; } // Check to see if Progress property is set internal bool IsSetProgress() { return this.progress.HasValue; } /// <summary> /// Contains details of the scaling activity. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Pattern</term> /// <description>[\u0020-\uD7FF\uE000-\uFFFD\uD800\uDC00-\uDBFF\uDFFF\r\n\t]*</description> /// </item> /// </list> /// </para> /// </summary> public string Details { get { return this.details; } set { this.details = value; } } /// <summary> /// Sets the Details property /// </summary> /// <param name="details">The value to set for the Details property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Activity WithDetails(string details) { this.details = details; return this; } // Check to see if Details property is set internal bool IsSetDetails() { return this.details != null; } } }
//------------------------------------------------------------------------------ // <copyright file="OleDbConnection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.OleDb { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using SysTx = System.Transactions; // wraps the OLEDB IDBInitialize interface which represents a connection // Notes about connection pooling // 1. Connection pooling isn't supported on Win95 // 2. Only happens if we use the IDataInitialize or IDBPromptInitialize interfaces // it won't happen if you directly create the provider and set its properties // 3. First call on IDBInitialize must be Initialize, can't QI for any other interfaces before that [DefaultEvent("InfoMessage")] public sealed partial class OleDbConnection : DbConnection, ICloneable, IDbConnection { static private readonly object EventInfoMessage = new object(); public OleDbConnection(string connectionString) : this() { ConnectionString = connectionString; } private OleDbConnection(OleDbConnection connection) : this() { // Clone CopyFrom(connection); } [ DefaultValue(""), #pragma warning disable 618 // ignore obsolete warning about RecommendedAsConfigurable to use SettingsBindableAttribute RecommendedAsConfigurable(true), #pragma warning restore 618 SettingsBindableAttribute(true), RefreshProperties(RefreshProperties.All), ResCategoryAttribute(Res.DataCategory_Data), Editor("Microsoft.VSDesigner.Data.ADO.Design.OleDbConnectionStringEditor, " + AssemblyRef.MicrosoftVSDesigner, "System.Drawing.Design.UITypeEditor, " + AssemblyRef.SystemDrawing), ResDescriptionAttribute(Res.OleDbConnection_ConnectionString), ] override public string ConnectionString { get { return ConnectionString_Get(); } set { ConnectionString_Set(value); } } private OleDbConnectionString OleDbConnectionStringValue { get { return (OleDbConnectionString)ConnectionOptions; } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescriptionAttribute(Res.OleDbConnection_ConnectionTimeout), ] override public int ConnectionTimeout { get { IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.get_ConnectionTimeout|API> %d#\n", ObjectID); try { object value = null; if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_TIMEOUT); } else { OleDbConnectionString constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.ConnectTimeout : ADP.DefaultConnectionTimeout; } if (null != value) { return Convert.ToInt32(value, CultureInfo.InvariantCulture); } else { return ADP.DefaultConnectionTimeout; } } finally { Bid.ScopeLeave(ref hscp); } } } [ DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescriptionAttribute(Res.OleDbConnection_Database), ] override public string Database { get { IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.get_Database|API> %d#\n", ObjectID); try { OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions; object value = (null != constr) ? constr.InitialCatalog : ADP.StrEmpty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { OleDbConnectionInternal connection = GetOpenConnection(); if (null != connection) { if (connection.HasSession) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG); } else { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_CATALOG); } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.InitialCatalog : ADP.StrEmpty; } } return Convert.ToString(value, CultureInfo.InvariantCulture); } finally { Bid.ScopeLeave(ref hscp); } } } [ Browsable(true), ResDescriptionAttribute(Res.OleDbConnection_DataSource), ] override public string DataSource { get { IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.get_DataSource|API> %d#\n", ObjectID); try { OleDbConnectionString constr = (OleDbConnectionString)UserConnectionOptions; object value = (null != constr) ? constr.DataSource : ADP.StrEmpty; if ((null != value) && !((string)value).StartsWith(DbConnectionOptions.DataDirectory, StringComparison.OrdinalIgnoreCase)) { if (IsOpen) { value = GetDataSourceValue(OleDbPropertySetGuid.DBInit, ODB.DBPROP_INIT_DATASOURCE); if ((null == value) || ((value is string) && (0 == (value as string).Length))) { value = GetDataSourceValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_DATASOURCENAME); // MDAC 76248 } } else { constr = this.OleDbConnectionStringValue; value = (null != constr) ? constr.DataSource : ADP.StrEmpty; } } return Convert.ToString(value, CultureInfo.InvariantCulture); } finally { Bid.ScopeLeave(ref hscp); } } } internal bool IsOpen { get { return (null != GetOpenConnection()); } } internal OleDbTransaction LocalTransaction { set { OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { openConnection.LocalTransaction = value; } } } [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResCategoryAttribute(Res.DataCategory_Data), ResDescriptionAttribute(Res.OleDbConnection_Provider), ] public String Provider { get { Bid.Trace("<oledb.OleDbConnection.get_Provider|API> %d#\n", ObjectID); OleDbConnectionString constr = this.OleDbConnectionStringValue; string value = ((null != constr) ? constr.ConvertValueToString(ODB.Provider, null) : null); return ((null != value) ? value : ADP.StrEmpty); } } internal OleDbConnectionPoolGroupProviderInfo ProviderInfo { get { return (OleDbConnectionPoolGroupProviderInfo)PoolGroup.ProviderInfo; } } [ ResDescriptionAttribute(Res.OleDbConnection_ServerVersion), ] override public string ServerVersion { // MDAC 55481 get { return InnerConnection.ServerVersion; } } [ Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), ResDescriptionAttribute(Res.DbConnection_State), ] override public ConnectionState State { get { return InnerConnection.State; } } [ EditorBrowsableAttribute(EditorBrowsableState.Advanced), ] public void ResetState() { // MDAC 58606 IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbCommand.ResetState|API> %d#\n", ObjectID); try { if (IsOpen) { object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_CONNECTIONSTATUS); if (value is Int32) { int connectionStatus = (int) value; switch (connectionStatus) { case ODB.DBPROPVAL_CS_UNINITIALIZED: // provider closed on us case ODB.DBPROPVAL_CS_COMMUNICATIONFAILURE: // broken connection GetOpenConnection().DoomThisConnection(); NotifyWeakReference(OleDbReferenceCollection.Canceling); // MDAC 71435 Close(); break; case ODB.DBPROPVAL_CS_INITIALIZED: // everything is okay break; default: // have to assume everything is okay Debug.Assert(false, "Unknown 'Connection Status' value " + connectionStatus.ToString("G", CultureInfo.InvariantCulture)); break; } } } } finally { Bid.ScopeLeave(ref hscp); } } [ ResCategoryAttribute(Res.DataCategory_InfoMessage), ResDescriptionAttribute(Res.DbConnection_InfoMessage), ] public event OleDbInfoMessageEventHandler InfoMessage { add { Events.AddHandler(EventInfoMessage, value); } remove { Events.RemoveHandler(EventInfoMessage, value); } } internal UnsafeNativeMethods.ICommandText ICommandText() { Debug.Assert(null != GetOpenConnection(), "ICommandText closed"); return GetOpenConnection().ICommandText(); } private IDBPropertiesWrapper IDBProperties() { Debug.Assert(null != GetOpenConnection(), "IDBProperties closed"); return GetOpenConnection().IDBProperties(); } internal IOpenRowsetWrapper IOpenRowset() { Debug.Assert(null != GetOpenConnection(), "IOpenRowset closed"); return GetOpenConnection().IOpenRowset(); } internal int SqlSupport() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SqlSupport"); return this.OleDbConnectionStringValue.GetSqlSupport(this); } internal bool SupportMultipleResults() { Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportMultipleResults"); return this.OleDbConnectionStringValue.GetSupportMultipleResults(this); } internal bool SupportIRow(OleDbCommand cmd) { // MDAC 72902 Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString SupportIRow"); return this.OleDbConnectionStringValue.GetSupportIRow(this, cmd); } internal int QuotedIdentifierCase() { // MDAC 67385 Debug.Assert(null != this.OleDbConnectionStringValue, "no OleDbConnectionString QuotedIdentifierCase"); int quotedIdentifierCase; object value = GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_QUOTEDIDENTIFIERCASE); if (value is Int32) {// not OleDbPropertyStatus quotedIdentifierCase = (int) value; } else { quotedIdentifierCase = -1; } return quotedIdentifierCase; } new public OleDbTransaction BeginTransaction() { return BeginTransaction(IsolationLevel.Unspecified); } new public OleDbTransaction BeginTransaction(IsolationLevel isolationLevel) { return (OleDbTransaction)InnerConnection.BeginTransaction(isolationLevel); } override public void ChangeDatabase(string value) { OleDbConnection.ExecutePermission.Demand(); IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.ChangeDatabase|API> %d#, value='%ls'\n", ObjectID, value); try { CheckStateOpen(ADP.ChangeDatabase); if ((null == value) || (0 == value.Trim().Length)) { // MDAC 62679 throw ADP.EmptyDatabaseName(); } SetDataSourcePropertyValue(OleDbPropertySetGuid.DataSource, ODB.DBPROP_CURRENTCATALOG, ODB.Current_Catalog, true, value); } finally { Bid.ScopeLeave(ref hscp); } } internal void CheckStateOpen(string method) { ConnectionState state = State; if (ConnectionState.Open != state) { throw ADP.OpenConnectionRequired(method, state); } } object ICloneable.Clone() { OleDbConnection clone = new OleDbConnection(this); Bid.Trace("<oledb.OleDbConnection.Clone|API> %d#, clone=%d#\n", ObjectID, clone.ObjectID); return clone; } override public void Close() { InnerConnection.CloseConnection(this, ConnectionFactory); // does not require GC.KeepAlive(this) because of OnStateChange } new public OleDbCommand CreateCommand() { return new OleDbCommand("", this); } private void DisposeMe(bool disposing) { // MDAC 65459 if (disposing) { // release mananged objects if (DesignMode) { // release the object pool in design-mode so that // native MDAC can be properly released during shutdown OleDbConnection.ReleaseObjectPool(); } } } // suppress this message - we cannot use SafeHandle here. Also, see notes in the code (VSTFDEVDIV# 560355) [SuppressMessage("Microsoft.Reliability", "CA2004:RemoveCallsToGCKeepAlive")] override protected DbTransaction BeginDbTransaction(IsolationLevel isolationLevel) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<prov.OleDbConnection.BeginDbTransaction|API> %d#, isolationLevel=%d{ds.IsolationLevel}", ObjectID, (int)isolationLevel); try { DbTransaction transaction = InnerConnection.BeginTransaction(isolationLevel); // VSTFDEVDIV# 560355 - InnerConnection doesn't maintain a ref on the outer connection (this) and // subsequently leaves open the possibility that the outer connection could be GC'ed before the DbTransaction // is fully hooked up (leaving a DbTransaction with a null connection property). Ensure that this is reachable // until the completion of BeginTransaction with KeepAlive GC.KeepAlive(this); return transaction; } finally { Bid.ScopeLeave(ref hscp); } } public void EnlistDistributedTransaction(System.EnterpriseServices.ITransaction transaction) { EnlistDistributedTransactionHelper(transaction); } internal object GetDataSourcePropertyValue(Guid propertySet, int propertyID) { OleDbConnectionInternal connection = GetOpenConnection(); return connection.GetDataSourcePropertyValue(propertySet, propertyID); } internal object GetDataSourceValue(Guid propertySet, int propertyID) { object value = GetDataSourcePropertyValue(propertySet, propertyID); if ((value is OleDbPropertyStatus) || Convert.IsDBNull(value)) { value = null; } return value; } private OleDbConnectionInternal GetOpenConnection() { DbConnectionInternal innerConnection = InnerConnection; return (innerConnection as OleDbConnectionInternal); } internal void GetLiteralQuotes(string method, out string quotePrefix, out string quoteSuffix) { CheckStateOpen(method); OleDbConnectionPoolGroupProviderInfo info = ProviderInfo; if (info.HasQuoteFix) { quotePrefix = info.QuotePrefix; quoteSuffix = info.QuoteSuffix; } else { OleDbConnectionInternal connection = GetOpenConnection(); quotePrefix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_PREFIX); quoteSuffix = connection.GetLiteralInfo(ODB.DBLITERAL_QUOTE_SUFFIX); if (null == quotePrefix) { quotePrefix = ""; } if (null == quoteSuffix) { quoteSuffix = quotePrefix; } info.SetQuoteFix(quotePrefix, quoteSuffix); } } public DataTable GetOleDbSchemaTable(Guid schema, object[] restrictions) { // MDAC 61846 OleDbConnection.ExecutePermission.Demand(); IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.GetOleDbSchemaTable|API> %d#, schema=%ls, restrictions\n", ObjectID, schema); try { CheckStateOpen(ADP.GetOleDbSchemaTable); OleDbConnectionInternal connection = GetOpenConnection(); if (OleDbSchemaGuid.DbInfoLiterals == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoLiterals(); } throw ODB.InvalidRestrictionsDbInfoLiteral("restrictions"); } else if (OleDbSchemaGuid.SchemaGuids == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildSchemaGuids(); } throw ODB.InvalidRestrictionsSchemaGuids("restrictions"); } else if (OleDbSchemaGuid.DbInfoKeywords == schema) { if ((null == restrictions) || (0 == restrictions.Length)) { return connection.BuildInfoKeywords(); } throw ODB.InvalidRestrictionsDbInfoKeywords("restrictions"); } if (connection.SupportSchemaRowset(schema)) { return connection.GetSchemaRowset(schema, restrictions); } else { using(IDBSchemaRowsetWrapper wrapper = connection.IDBSchemaRowset()) { if (null == wrapper.Value) { throw ODB.SchemaRowsetsNotSupported(Provider); // MDAC 72689 } } throw ODB.NotSupportedSchemaTable(schema, this); // MDAC 63279 } } finally { Bid.ScopeLeave(ref hscp); } } internal DataTable GetSchemaRowset(Guid schema, object[] restrictions) { Debug.Assert(null != GetOpenConnection(), "GetSchemaRowset closed"); return GetOpenConnection().GetSchemaRowset(schema, restrictions); } internal bool HasLiveReader(OleDbCommand cmd) { bool result = false; OleDbConnectionInternal openConnection = GetOpenConnection(); if (null != openConnection) { result = openConnection.HasLiveReader(cmd); } return result; } internal void OnInfoMessage(UnsafeNativeMethods.IErrorInfo errorInfo, OleDbHResult errorCode) { OleDbInfoMessageEventHandler handler = (OleDbInfoMessageEventHandler) Events[EventInfoMessage]; if (null != handler) { try { OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null); OleDbInfoMessageEventArgs e = new OleDbInfoMessageEventArgs(exception); if (Bid.TraceOn) { Bid.Trace("<oledb.OledbConnection.OnInfoMessage|API|INFO> %d#, Message='%ls'\n", ObjectID, e.Message); } handler(this, e); } catch (Exception e) { // eat the exception // if (!ADP.IsCatchableOrSecurityExceptionType(e)) { throw; } ADP.TraceExceptionWithoutRethrow(e); } } #if DEBUG else { OleDbException exception = OleDbException.CreateException(errorInfo, errorCode, null); Bid.Trace("<oledb.OledbConnection.OnInfoMessage|API|INFO> %d#, Message='%ls'\n", ObjectID, exception.Message); } #endif } override public void Open() { InnerConnection.OpenConnection(this, ConnectionFactory); // SQLBUDT #276132 - need to manually enlist in some cases, because // native OLE DB doesn't know about SysTx transactions. if ((0!=(ODB.DBPROPVAL_OS_TXNENLISTMENT & ((OleDbConnectionString)(this.ConnectionOptions)).OleDbServices)) && ADP.NeedManualEnlistment()) { GetOpenConnection().EnlistTransactionInternal(SysTx.Transaction.Current); } } internal void SetDataSourcePropertyValue(Guid propertySet, int propertyID, string description, bool required, object value) { CheckStateOpen(ADP.SetProperties); OleDbHResult hr; using(IDBPropertiesWrapper idbProperties = IDBProperties()) { using(DBPropSet propSet = DBPropSet.CreateProperty(propertySet, propertyID, required, value)) { Bid.Trace("<oledb.IDBProperties.SetProperties|API|OLEDB> %d#\n", ObjectID); hr = idbProperties.Value.SetProperties(propSet.PropertySetCount, propSet); Bid.Trace("<oledb.IDBProperties.SetProperties|API|OLEDB|RET> %08X{HRESULT}\n", hr); if (hr < 0) { Exception e = OleDbConnection.ProcessResults(hr, null, this); if (OleDbHResult.DB_E_ERRORSOCCURRED == hr) { StringBuilder builder = new StringBuilder(); Debug.Assert(1 == propSet.PropertySetCount, "too many PropertySets"); tagDBPROP[] dbprops = propSet.GetPropertySet(0, out propertySet); Debug.Assert(1 == dbprops.Length, "too many Properties"); ODB.PropsetSetFailure(builder, description, dbprops[0].dwStatus); e = ODB.PropsetSetFailure(builder.ToString(), e); } if (null != e) { throw e; } } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } } internal bool SupportSchemaRowset(Guid schema) { return GetOpenConnection().SupportSchemaRowset(schema); } internal OleDbTransaction ValidateTransaction(OleDbTransaction transaction, string method) { return GetOpenConnection().ValidateTransaction(transaction, method); } static internal Exception ProcessResults(OleDbHResult hresult, OleDbConnection connection, object src) { if ((0 <= (int)hresult) && ((null == connection) || (null == connection.Events[EventInfoMessage]))) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return null; } // ErrorInfo object is to be checked regardless the hresult returned by the function called Exception e = null; UnsafeNativeMethods.IErrorInfo errorInfo = null; OleDbHResult hr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((OleDbHResult.S_OK == hr) && (null != errorInfo)) { if (hresult < 0) { // e = OleDbException.CreateException(errorInfo, hresult, null); //} if (OleDbHResult.DB_E_OBJECTOPEN == hresult) { e = ADP.OpenReaderExists(e); } ResetState(connection); } else if (null != connection) { connection.OnInfoMessage(errorInfo, hresult); } else { Bid.Trace("<oledb.OledbConnection|WARN|INFO> ErrorInfo available, but not connection %08X{HRESULT}\n", hresult); } Marshal.ReleaseComObject(errorInfo); } else if (0 < hresult) { // @devnote: OnInfoMessage with no ErrorInfo Bid.Trace("<oledb.OledbConnection|ERR|INFO> ErrorInfo not available %08X{HRESULT}\n", hresult); } else if ((int)hresult < 0) { e = ODB.NoErrorInformation((null != connection) ? connection.Provider : null, hresult, null); // OleDbException ResetState(connection); } if (null != e) { ADP.TraceExceptionAsReturnValue(e); } return e; } // @devnote: should be multithread safe static public void ReleaseObjectPool() { (new OleDbPermission(PermissionState.Unrestricted)).Demand(); IntPtr hscp; Bid.ScopeEnter(out hscp, "<oledb.OleDbConnection.ReleaseObjectPool|API>\n"); try { OleDbConnectionString.ReleaseObjectPool(); OleDbConnectionInternal.ReleaseObjectPool(); OleDbConnectionFactory.SingletonInstance.ClearAllPools(); } finally { Bid.ScopeLeave(ref hscp); } } static private void ResetState(OleDbConnection connection) { if (null != connection) { connection.ResetState(); } } } }
using System; namespace WeifenLuo.WinFormsUI.Docking.Win32 { [Flags] internal enum FlagsSetWindowPos : uint { SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOREDRAW = 0x0008, SWP_NOACTIVATE = 0x0010, SWP_FRAMECHANGED = 0x0020, SWP_SHOWWINDOW = 0x0040, SWP_HIDEWINDOW = 0x0080, SWP_NOCOPYBITS = 0x0100, SWP_NOOWNERZORDER = 0x0200, SWP_NOSENDCHANGING = 0x0400, SWP_DRAWFRAME = 0x0020, SWP_NOREPOSITION = 0x0200, SWP_DEFERERASE = 0x2000, SWP_ASYNCWINDOWPOS = 0x4000 } internal enum ShowWindowStyles : short { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_FORCEMINIMIZE = 11, SW_MAX = 11 } internal enum WindowStyles : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_TILED = 0x00000000, WS_ICONIC = 0x20000000, WS_SIZEBOX = 0x00040000, WS_POPUPWINDOW = 0x80880000, WS_OVERLAPPEDWINDOW = 0x00CF0000, WS_TILEDWINDOW = 0x00CF0000, WS_CHILDWINDOW = 0x40000000 } internal enum WindowExStyles { WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_TOPMOST = 0x00000008, WS_EX_ACCEPTFILES = 0x00000010, WS_EX_TRANSPARENT = 0x00000020, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_WINDOWEDGE = 0x00000100, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LTRREADING = 0x00000000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_RIGHTSCROLLBAR = 0x00000000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_OVERLAPPEDWINDOW = 0x00000300, WS_EX_PALETTEWINDOW = 0x00000188, WS_EX_LAYERED = 0x00080000, WS_EX_NOACTIVATE = 0x08000000 } internal enum Msgs { WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_DELETEITEM = 0x002D, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044 , WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_SYNCPAINT = 0x0088, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_MENURBUTTONUP = 0x0122, WM_MENUDRAG = 0x0123, WM_MENUGETOBJECT = 0x0124, WM_UNINITMENUPOPUP = 0x0125, WM_MENUCOMMAND = 0x0126, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_MOUSEWHEEL = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_DEVICECHANGE = 0x0219, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_REQUEST = 0x0288, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = 0x8000, WM_USER = 0x0400 } internal enum HitTest { HTERROR = -2, HTTRANSPARENT = -1, HTNOWHERE = 0, HTCLIENT = 1, HTCAPTION = 2, HTSYSMENU = 3, HTGROWBOX = 4, HTSIZE = 4, HTMENU = 5, HTHSCROLL = 6, HTVSCROLL = 7, HTMINBUTTON = 8, HTMAXBUTTON = 9, HTLEFT = 10, HTRIGHT = 11, HTTOP = 12, HTTOPLEFT = 13, HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17, HTBORDER = 18, HTREDUCE = 8, HTZOOM = 9 , HTSIZEFIRST = 10, HTSIZELAST = 17, HTOBJECT = 19, HTCLOSE = 20, HTHELP = 21 } internal enum ScrollBars : uint { SB_HORZ = 0, SB_VERT = 1, SB_CTL = 2, SB_BOTH = 3 } internal enum GetWindowLongIndex : int { GWL_STYLE = -16, GWL_EXSTYLE = -20 } // Hook Types internal enum HookType : int { WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, WH_KEYBOARD = 2, WH_GETMESSAGE = 3, WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, WH_CALLWNDPROCRET = 12, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } internal enum MenuCommand : int { MF_UNCHECKED = 0, MF_CHECKED = 0x0008, MF_SEPARATOR = 0x0800, MF_BYPOSITION = 0x0400 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Provides some basic access to some environment ** functionality. ** ** ============================================================*/ namespace System { using System.Buffers; using System.IO; using System.Security; using System.Resources; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Threading; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; public enum EnvironmentVariableTarget { Process = 0, User = 1, Machine = 2, } internal static partial class Environment { // Assume the following constants include the terminating '\0' - use <, not <= // System environment variables are stored in the registry, and have // a size restriction that is separate from both normal environment // variables and registry value name lengths, according to MSDN. // MSDN doesn't detail whether the name is limited to 1024, or whether // that includes the contents of the environment variable. private const int MaxSystemEnvVariableLength = 1024; private const int MaxUserEnvVariableLength = 255; private const int MaxMachineNameLength = 256; // Looks up the resource string value for key. // // if you change this method's signature then you must change the code that calls it // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature // as well as metasig.h to create the new signature type internal static String GetResourceStringLocal(String key) { return SR.GetResourceString(key); } /*==================================TickCount=================================== **Action: Gets the number of ticks since the system was started. **Returns: The number of ticks since the system was started. **Arguments: None **Exceptions: None ==============================================================================*/ public static extern int TickCount { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // Terminates this process with the given exit code. [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] internal static extern void _Exit(int exitCode); public static void Exit(int exitCode) { _Exit(exitCode); } public static extern int ExitCode { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } // Note: The CLR's Watson bucketization code looks at the caller of the FCALL method // to assign blame for crashes. Don't mess with this, such as by making it call // another managed helper method, unless you consult with some CLR Watson experts. [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message); // This overload of FailFast will allow you to specify the exception object // whose bucket details *could* be used when undergoing the failfast process. // To be specific: // // 1) When invoked from within a managed EH clause (fault/finally/catch), // if the exception object is preallocated, the runtime will try to find its buckets // and use them. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). // // 2) When invoked from outside the managed EH clauses (fault/finally/catch), // if the exception object is preallocated, the runtime will use the callsite's // IP for bucketing. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message, Exception exception); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message, Exception exception, String errorMessage); #if FEATURE_WIN32_REGISTRY // This is only used by RegistryKey on Windows. public static String ExpandEnvironmentVariables(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) { return name; } int currentSize = 100; StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size int size; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); while (size > currentSize) { currentSize = size; blob.Capacity = currentSize; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } return blob.ToString(); } #endif // FEATURE_WIN32_REGISTRY [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern Int32 GetProcessorCount(); public static int ProcessorCount { get { return GetProcessorCount(); } } /*==============================GetCommandLineArgs============================== **Action: Gets the command line and splits it appropriately to deal with whitespace, ** quotes, and escape characters. **Returns: A string array containing your command line arguments. **Arguments: None **Exceptions: None. ==============================================================================*/ public static String[] GetCommandLineArgs() { /* * There are multiple entry points to a hosted app. * The host could use ::ExecuteAssembly() or ::CreateDelegate option * ::ExecuteAssembly() -> In this particular case, the runtime invokes the main method based on the arguments set by the host, and we return those arguments * * ::CreateDelegate() -> In this particular case, the host is asked to create a * delegate based on the appDomain, assembly and methodDesc passed to it. * which the caller uses to invoke the method. In this particular case we do not have * any information on what arguments would be passed to the delegate. * So our best bet is to simply use the commandLine that was used to invoke the process. * in case it is present. */ if (s_CommandLineArgs != null) return (string[])s_CommandLineArgs.Clone(); return GetCommandLineArgsNative(); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetCommandLineArgsNative(); private static string[] s_CommandLineArgs = null; private static void SetCommandLineArgs(string[] cmdLineArgs) { s_CommandLineArgs = cmdLineArgs; } private unsafe static char[] GetEnvironmentCharArray() { char[] block = null; RuntimeHelpers.PrepareConstrainedRegions(); char* pStrings = null; try { pStrings = Win32Native.GetEnvironmentStrings(); if (pStrings == null) { throw new OutOfMemoryException(); } // Format for GetEnvironmentStrings is: // [=HiddenVar=value\0]* [Variable=value\0]* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Search for terminating \0\0 (two unicode \0's). char* p = pStrings; while (!(*p == '\0' && *(p + 1) == '\0')) p++; int len = (int)(p - pStrings + 1); block = new char[len]; fixed (char* pBlock = block) string.wstrcpy(pBlock, pStrings, len); } finally { if (pStrings != null) Win32Native.FreeEnvironmentStrings(pStrings); } return block; } /*===================================NewLine==================================== **Action: A property which returns the appropriate newline string for the given ** platform. **Returns: \r\n on Win32. **Arguments: None. **Exceptions: None. ==============================================================================*/ public static String NewLine { get { #if PLATFORM_WINDOWS return "\r\n"; #else return "\n"; #endif // PLATFORM_WINDOWS } } /*===================================Version==================================== **Action: Returns the COM+ version struct, describing the build number. **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static Version Version { get { // Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version // remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning // scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded. return new Version(4, 0, 30319, 42000); } } #if !FEATURE_PAL private static Lazy<bool> s_IsWindows8OrAbove = new Lazy<bool>(() => { ulong conditionMask = Win32Native.VerSetConditionMask(0, Win32Native.VER_MAJORVERSION, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_MINORVERSION, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMAJOR, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMINOR, Win32Native.VER_GREATER_EQUAL); // Windows 8 version is 6.2 var version = new Win32Native.OSVERSIONINFOEX { MajorVersion = 6, MinorVersion = 2, ServicePackMajor = 0, ServicePackMinor = 0 }; return Win32Native.VerifyVersionInfoW(version, Win32Native.VER_MAJORVERSION | Win32Native.VER_MINORVERSION | Win32Native.VER_SERVICEPACKMAJOR | Win32Native.VER_SERVICEPACKMINOR, conditionMask); }); internal static bool IsWindows8OrAbove => s_IsWindows8OrAbove.Value; #endif #if FEATURE_COMINTEROP // Does the current version of Windows have Windows Runtime suppport? private static Lazy<bool> s_IsWinRTSupported = new Lazy<bool>(() => { return WinRTSupported(); }); internal static bool IsWinRTSupported => s_IsWinRTSupported.Value; [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool WinRTSupported(); #endif // FEATURE_COMINTEROP /*==================================StackTrace================================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static String StackTrace { [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts get { return Internal.Runtime.Augments.EnvironmentAugments.StackTrace; } } internal static String GetStackTrace(Exception e, bool needFileInfo) { // Note: Setting needFileInfo to true will start up COM and set our // apartment state. Try to not call this when passing "true" // before the EE's ExecuteMainMethod has had a chance to set up the // apartment state. -- StackTrace st; if (e == null) st = new StackTrace(needFileInfo); else st = new StackTrace(e, needFileInfo); // Do no include a trailing newline for backwards compatibility return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } public static extern bool HasShutdownStarted { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } internal static bool UserInteractive { get { return true; } } public static int CurrentManagedThreadId { get { return Thread.CurrentThread.ManagedThreadId; } } public static string GetEnvironmentVariable(string variable) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case return GetEnvironmentVariableCore(variable); } internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } ValidateTarget(target); return GetEnvironmentVariableCore(variable, target); } public static void SetEnvironmentVariable(string variable, string value) { ValidateVariableAndValue(variable, ref value); // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case SetEnvironmentVariableCore(variable, value); } internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) { ValidateVariableAndValue(variable, ref value); ValidateTarget(target); SetEnvironmentVariableCore(variable, value, target); } private static void ValidateVariableAndValue(string variable, ref string value) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } if (variable.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable)); } if (variable[0] == '\0') { throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable)); } if (variable.IndexOf('=') != -1) { throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable)); } if (string.IsNullOrEmpty(value) || value[0] == '\0') { // Explicitly null out value if it's empty value = null; } } private static void ValidateTarget(EnvironmentVariableTarget target) { if (target != EnvironmentVariableTarget.Process && target != EnvironmentVariableTarget.Machine && target != EnvironmentVariableTarget.User) { throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } } private static string GetEnvironmentVariableCore(string variable) { Span<char> buffer = stackalloc char[128]; // A somewhat reasonable default size return GetEnvironmentVariableCoreHelper(variable, buffer); } private static string GetEnvironmentVariableCoreHelper(string variable, Span<char> buffer) { int requiredSize = Win32Native.GetEnvironmentVariable(variable, buffer); if (requiredSize == 0 && Marshal.GetLastWin32Error() == Interop.Errors.ERROR_ENVVAR_NOT_FOUND) { return null; } if (requiredSize > buffer.Length) { char[] chars = ArrayPool<char>.Shared.Rent(requiredSize); try { return GetEnvironmentVariableCoreHelper(variable, chars); } finally { ArrayPool<char>.Shared.Return(chars); } } return new string(buffer.Slice(0, requiredSize)); } private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariableCore(variable); #if FEATURE_WIN32_REGISTRY if (AppDomain.IsAppXModel()) #endif { return null; } #if FEATURE_WIN32_REGISTRY RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { return environmentKey?.GetValue(variable) as string; } #endif } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables() { // Format for GetEnvironmentStrings is: // (=HiddenVar=value\0 | Variable=value\0)* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Note the =HiddenVar's aren't always at the beginning. // Copy strings out, parsing into pairs and inserting into the table. // The first few environment variable entries start with an '='. // The current working directory of every drive (except for those drives // you haven't cd'ed into in your DOS window) are stored in the // environment block (as =C:=pwd) and the program's exit code is // as well (=ExitCode=00000000). char[] block = GetEnvironmentCharArray(); for (int i = 0; i < block.Length; i++) { int startKey = i; // Skip to key. On some old OS, the environment block can be corrupted. // Some will not have '=', so we need to check for '\0'. while (block[i] != '=' && block[i] != '\0') i++; if (block[i] == '\0') continue; // Skip over environment variables starting with '=' if (i - startKey == 0) { while (block[i] != 0) i++; continue; } string key = new string(block, startKey, i - startKey); i++; // skip over '=' int startValue = i; while (block[i] != 0) i++; // Read to end of this entry string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++ yield return new KeyValuePair<string, string>(key, value); } } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return EnumerateEnvironmentVariables(); return EnumerateEnvironmentVariablesFromRegistry(target); } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariablesFromRegistry(EnvironmentVariableTarget target) { #if FEATURE_WIN32_REGISTRY if (AppDomain.IsAppXModel()) #endif { // Without registry support we have nothing to return ValidateTarget(target); yield break; } #if FEATURE_WIN32_REGISTRY RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { baseKey = Registry.CurrentUser; keyName = @"Environment"; } else { throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { if (environmentKey != null) { foreach (string name in environmentKey.GetValueNames()) { string value = environmentKey.GetValue(name, "").ToString(); yield return new KeyValuePair<string, string>(name, value); } } } #endif // FEATURE_WIN32_REGISTRY } private static void SetEnvironmentVariableCore(string variable, string value) { // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; if (!Win32Native.SetEnvironmentVariable(variable, value)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Interop.Errors.ERROR_ENVVAR_NOT_FOUND: // Allow user to try to clear a environment variable return; case Interop.Errors.ERROR_FILENAME_EXCED_RANGE: // The error message from Win32 is "The filename or extension is too long", // which is not accurate. throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue)); case Interop.Errors.ERROR_NOT_ENOUGH_MEMORY: case Interop.Errors.ERROR_NO_SYSTEM_RESOURCES: throw new OutOfMemoryException(Interop.Kernel32.GetMessage(errorCode)); default: throw new ArgumentException(Interop.Kernel32.GetMessage(errorCode)); } } } private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if FEATURE_WIN32_REGISTRY if (AppDomain.IsAppXModel()) #endif { // other targets ignored return; } #if FEATURE_WIN32_REGISTRY // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name. const int MaxUserEnvVariableLength = 255; if (variable.Length >= MaxUserEnvVariableLength) { throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable)); } baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true)) { if (environmentKey != null) { if (value == null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } else { environmentKey.SetValue(variable, value); } } } // send a WM_SETTINGCHANGE message to all windows IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); #endif // FEATURE_WIN32_REGISTRY } } }
using System; namespace Memcached.ClientLibrary { /// <summary> /// Tool to calculate and add CRC codes to a string /// Code found posted on CodeProject.com: /// http://www.codeproject.com/csharp/marcelcrcencoding.asp /// /// *************************************************************************** /// Copyright (c) 2003 Thoraxcentrum, Erasmus MC, The Netherlands. /// /// Written by Marcel de Wijs with help from a lot of others, /// especially Stefan Nelwan /// /// This code is for free. I ported it from several different sources to C#. /// /// For comments: [email protected] /// *************************************************************************** /// </summary> public class CRCTool { // 'order' [1..32] is the CRC polynom order, counted without the leading '1' bit // 'polynom' is the CRC polynom without leading '1' bit // 'direct' [0,1] specifies the kind of algorithm: 1=direct, no augmented zero bits // 'crcinit' is the initial CRC value belonging to that algorithm // 'crcxor' is the final XOR value // 'refin' [0,1] specifies if a data byte is reflected before processing (UART) or not // 'refout' [0,1] specifies if the CRC will be reflected before XOR // Data character string // For CRC-CCITT : order = 16, direct=1, poly=0x1021, CRCinit = 0xFFFF, crcxor=0; refin =0, refout=0 // For CRC16: order = 16, direct=1, poly=0x8005, CRCinit = 0x0, crcxor=0x0; refin =1, refout=1 // For CRC32: order = 32, direct=1, poly=0x4c11db7, CRCinit = 0xFFFFFFFF, crcxor=0xFFFFFFFF; refin =1, refout=1 // Default : CRC-CCITT private int order = 16; private ulong polynom = 0x1021; private int direct = 1; private ulong crcinit = 0xFFFF; private ulong crcxor = 0x0; private int refin = 0; private int refout = 0; private ulong crcmask; private ulong crchighbit; private ulong crcinit_direct; private ulong crcinit_nondirect; private ulong [] crctab = new ulong[256]; // Enumeration used in the init function to specify which CRC algorithm to use public enum CRCCode{CRC_CCITT, CRC16, CRC32}; public CRCTool() { // // TODO: Add constructor logic here // } public void Init(CRCCode CodingType) { switch(CodingType) { case CRCCode.CRC_CCITT: order = 16; direct=1; polynom=0x1021; crcinit = 0xFFFF; crcxor=0; refin =0; refout=0; break; case CRCCode.CRC16: order = 16; direct=1; polynom=0x8005; crcinit = 0x0; crcxor=0x0; refin =1; refout=1; break; case CRCCode.CRC32: order = 32; direct=1; polynom=0x4c11db7; crcinit = 0xFFFFFFFF; crcxor=0xFFFFFFFF; refin =1; refout=1; break; } // Initialize all variables for seeding and builing based upon the given coding type // at first, compute constant bit masks for whole CRC and CRC high bit crcmask = ((((ulong)1<<(order-1))-1)<<1)|1; crchighbit = (ulong)1<<(order-1); // generate lookup table generate_crc_table(); ulong bit, crc; int i; if (direct == 0) { crcinit_nondirect = crcinit; crc = crcinit; for (i=0; i<order; i++) { bit = crc & crchighbit; crc<<= 1; if (bit != 0) { crc^= polynom; } } crc&= crcmask; crcinit_direct = crc; } else { crcinit_direct = crcinit; crc = crcinit; for (i=0; i<order; i++) { bit = crc & 1; if (bit != 0) { crc^= polynom; } crc >>= 1; if (bit != 0) { crc|= crchighbit; } } crcinit_nondirect = crc; } } /// <summary> /// 4 ways to calculate the crc checksum. If you have to do a lot of encoding /// you should use the table functions. Since they use precalculated values, which /// saves some calculating. /// </summary>. [CLSCompliant(false)] public ulong crctablefast (byte[] p) { // fast lookup table algorithm without augmented zero bytes, e.g. used in pkzip. // only usable with polynom orders of 8, 16, 24 or 32. ulong crc = crcinit_direct; if (refin != 0) { crc = reflect(crc, order); } if (refin == 0) { for (int i = 0; i < p.Length; i++) { crc = (crc << 8) ^ crctab[ ((crc >> (order-8)) & 0xff) ^ p[i]]; } } else { for (int i = 0; i < p.Length; i++) { crc = (crc >> 8) ^ crctab[ (crc & 0xff) ^ p[i]]; } } if ((refout^refin) != 0) { crc = reflect(crc, order); } crc^= crcxor; crc&= crcmask; return(crc); } [CLSCompliant(false)] public ulong crctable (byte[] p) { // normal lookup table algorithm with augmented zero bytes. // only usable with polynom orders of 8, 16, 24 or 32. ulong crc = crcinit_nondirect; if (refin != 0) { crc = reflect(crc, order); } if (refin == 0) { for (int i = 0; i < p.Length; i++) { crc = ((crc << 8) | p[i]) ^ crctab[ (crc >> (order-8)) & 0xff ]; } } else { for (int i = 0; i < p.Length; i++) { crc = (ulong)(((int)(crc >> 8) | (p[i] << (order-8))) ^ (int)crctab[ crc & 0xff ]); } } if (refin == 0) { for (int i = 0; i < order/8; i++) { crc = (crc << 8) ^ crctab[ (crc >> (order-8)) & 0xff]; } } else { for (int i = 0; i < order/8; i++) { crc = (crc >> 8) ^ crctab[crc & 0xff]; } } if ((refout^refin) != 0) { crc = reflect(crc, order); } crc^= crcxor; crc&= crcmask; return(crc); } [CLSCompliant(false)] public ulong crcbitbybit(byte[] p) { // bit by bit algorithm with augmented zero bytes. // does not use lookup table, suited for polynom orders between 1...32. int i; ulong j, c, bit; ulong crc = crcinit_nondirect; for (i=0; i<p.Length; i++) { c = (ulong)p[i]; if (refin != 0) { c = reflect(c, 8); } for (j=0x80; j != 0; j>>=1) { bit = crc & crchighbit; crc<<= 1; if ((c & j) != 0) { crc|= 1; } if (bit != 0) { crc^= polynom; } } } for (i=0; (int)i < order; i++) { bit = crc & crchighbit; crc<<= 1; if (bit != 0) crc^= polynom; } if (refout != 0) { crc=reflect(crc, order); } crc^= crcxor; crc&= crcmask; return(crc); } [CLSCompliant(false)] public ulong crcbitbybitfast(byte[] p) { // fast bit by bit algorithm without augmented zero bytes. // does not use lookup table, suited for polynom orders between 1...32. int i; ulong j, c, bit; ulong crc = crcinit_direct; for (i = 0; i < p.Length; i++) { c = (ulong)p[i]; if (refin != 0) { c = reflect(c, 8); } for (j = 0x80; j > 0; j >>= 1) { bit = crc & crchighbit; crc <<= 1; if ((c & j) > 0) bit^= crchighbit; if (bit > 0) crc^= polynom; } } if (refout > 0) { crc=reflect(crc, order); } crc^= crcxor; crc&= crcmask; return(crc); } /// <summary> /// CalcCRCITT is an algorithm found on the web for calculating the CRCITT checksum /// It is included to demonstrate that although it looks different it is the same /// routine as the crcbitbybit* functions. But it is optimized and preconfigured for CRCITT. /// </summary> [CLSCompliant(false)] public ushort CalcCRCITT(byte[] p) { uint uiCRCITTSum = 0xFFFF; uint uiByteValue; for (int iBufferIndex = 0; iBufferIndex < p.Length; iBufferIndex++) { uiByteValue = ((uint) p[iBufferIndex] << 8); for (int iBitIndex = 0; iBitIndex < 8; iBitIndex++) { if (((uiCRCITTSum^uiByteValue) & 0x8000) != 0) { uiCRCITTSum = (uiCRCITTSum <<1) ^ 0x1021; } else { uiCRCITTSum <<= 1; } uiByteValue <<=1; } } return (ushort)uiCRCITTSum; } #region subroutines private ulong reflect (ulong crc, int bitnum) { // reflects the lower 'bitnum' bits of 'crc' ulong i, j=1, crcout = 0; for (i = (ulong)1 <<(bitnum-1); i != 0; i>>=1) { if ((crc & i) != 0) { crcout |= j; } j<<= 1; } return (crcout); } private void generate_crc_table() { // make CRC lookup table used by table algorithms int i, j; ulong bit, crc; for (i=0; i<256; i++) { crc=(ulong)i; if (refin !=0) { crc=reflect(crc, 8); } crc<<= order-8; for (j=0; j<8; j++) { bit = crc & crchighbit; crc<<= 1; if (bit !=0) crc^= polynom; } if (refin != 0) { crc = reflect(crc, order); } crc&= crcmask; crctab[i]= crc; } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Data.MySQL { public class MySQLGenericTableHandler<T> : MySqlFramework where T: class, new() { protected Dictionary<string, FieldInfo> m_Fields = new Dictionary<string, FieldInfo>(); protected List<string> m_ColumnNames = null; protected string m_Realm; protected FieldInfo m_DataField = null; public MySQLGenericTableHandler(string connectionString, string realm, string storeName) : base(connectionString) { m_Realm = realm; m_connectionString = connectionString; if (storeName != String.Empty) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, GetType().Assembly, storeName); m.Update(); } } Type t = typeof(T); FieldInfo[] fields = t.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (fields.Length == 0) return; foreach (FieldInfo f in fields) { if (f.Name != "Data") m_Fields[f.Name] = f; else m_DataField = f; } } private void CheckColumnNames(IDataReader reader) { if (m_ColumnNames != null) return; m_ColumnNames = new List<string>(); DataTable schemaTable = reader.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) { if (row["ColumnName"] != null && (!m_Fields.ContainsKey(row["ColumnName"].ToString()))) m_ColumnNames.Add(row["ColumnName"].ToString()); } } public T[] Get(string field, string key) { return Get(new string[] { field }, new string[] { key }); } public T[] Get(string[] fields, string[] keys) { if (fields.Length != keys.Length) return new T[0]; List<string> terms = new List<string>(); using (MySqlCommand cmd = new MySqlCommand()) { for (int i = 0 ; i < fields.Length ; i++) { cmd.Parameters.AddWithValue(fields[i], keys[i]); terms.Add("`" + fields[i] + "` = ?" + fields[i]); } string where = String.Join(" and ", terms.ToArray()); string query = String.Format("select * from {0} where {1}", m_Realm, where); cmd.CommandText = query; return DoQuery(cmd); } } protected T[] DoQuery(MySqlCommand cmd) { List<T> result = new List<T>(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); cmd.Connection = dbcon; using (IDataReader reader = cmd.ExecuteReader()) { if (reader == null) return new T[0]; CheckColumnNames(reader); while (reader.Read()) { T row = new T(); foreach (string name in m_Fields.Keys) { if (m_Fields[name].GetValue(row) is bool) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v != 0 ? true : false); } else if (m_Fields[name].GetValue(row) is UUID) { UUID uuid = UUID.Zero; UUID.TryParse(reader[name].ToString(), out uuid); m_Fields[name].SetValue(row, uuid); } else if (m_Fields[name].GetValue(row) is int) { int v = Convert.ToInt32(reader[name]); m_Fields[name].SetValue(row, v); } else { m_Fields[name].SetValue(row, reader[name]); } } if (m_DataField != null) { Dictionary<string, string> data = new Dictionary<string, string>(); foreach (string col in m_ColumnNames) { data[col] = reader[col].ToString(); if (data[col] == null) data[col] = String.Empty; } m_DataField.SetValue(row, data); } result.Add(row); } } } return result.ToArray(); } public T[] Get(string where) { using (MySqlCommand cmd = new MySqlCommand()) { string query = String.Format("select * from {0} where {1}", m_Realm, where); cmd.CommandText = query; return DoQuery(cmd); } } public bool Store(T row) { using (MySqlCommand cmd = new MySqlCommand()) { string query = ""; List<String> names = new List<String>(); List<String> values = new List<String>(); foreach (FieldInfo fi in m_Fields.Values) { names.Add(fi.Name); values.Add("?" + fi.Name); cmd.Parameters.AddWithValue(fi.Name, fi.GetValue(row).ToString()); } if (m_DataField != null) { Dictionary<string, string> data = (Dictionary<string, string>)m_DataField.GetValue(row); foreach (KeyValuePair<string, string> kvp in data) { names.Add(kvp.Key); values.Add("?" + kvp.Key); cmd.Parameters.AddWithValue("?" + kvp.Key, kvp.Value); } } query = String.Format("replace into {0} (`", m_Realm) + String.Join("`,`", names.ToArray()) + "`) values (" + String.Join(",", values.ToArray()) + ")"; cmd.CommandText = query; if (ExecuteNonQuery(cmd) > 0) return true; return false; } } public bool Delete(string field, string val) { using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("delete from {0} where `{1}` = ?{1}", m_Realm, field); cmd.Parameters.AddWithValue(field, val); if (ExecuteNonQuery(cmd) > 0) return true; return false; } } } }
// 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.Sql { using Microsoft.Azure; using Microsoft.Azure.Management; 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> /// Operations operations. /// </summary> internal partial class Operations : IServiceOperations<SqlManagementClient>, IOperations { /// <summary> /// Initializes a new instance of the Operations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal Operations(SqlManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the SqlManagementClient /// </summary> public SqlManagementClient Client { get; private set; } /// <summary> /// Lists all of the available SQL Rest API operations. /// </summary> /// <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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<OperationListResult>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2014-04-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("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Sql/operations").ToString(); 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 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<OperationListResult>(); _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<OperationListResult>(_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; } } }
#region Copyright // // Nini Configuration Project. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.Collections; using System.Globalization; using Nini.Util; namespace Nini.Config { #region ConfigKeyEventArgs class /// <include file='ConfigKeyEventArgs.xml' path='//Delegate[@name="ConfigKeyEventHandler"]/docs/*' /> public delegate void ConfigKeyEventHandler (object sender, ConfigKeyEventArgs e); /// <include file='ConfigEventArgs.xml' path='//Class[@name="ConfigEventArgs"]/docs/*' /> public class ConfigKeyEventArgs : EventArgs { string keyName = null; string keyValue = null; /// <include file='ConfigEventArgs.xml' path='//Constructor[@name="Constructor"]/docs/*' /> public ConfigKeyEventArgs (string keyName, string keyValue) { this.keyName = keyName; this.keyValue = keyValue; } /// <include file='ConfigEventArgs.xml' path='//Property[@name="KeyName"]/docs/*' /> public string KeyName { get { return keyName; } } /// <include file='ConfigEventArgs.xml' path='//Property[@name="KeyValue"]/docs/*' /> public string KeyValue { get { return keyValue; } } } #endregion /// <include file='IConfig.xml' path='//Interface[@name="IConfig"]/docs/*' /> public class ConfigBase : IConfig { #region Private variables string configName = null; IConfigSource configSource = null; AliasText aliasText = null; IFormatProvider format = NumberFormatInfo.CurrentInfo; #endregion #region Protected variables protected OrderedList keys = new OrderedList (); #endregion #region Constructors /// <include file='ConfigBase.xml' path='//Constructor[@name="ConfigBase"]/docs/*' /> public ConfigBase (string name, IConfigSource source) { configName = name; configSource = source; aliasText = new AliasText (); } #endregion #region Public properties /// <include file='IConfig.xml' path='//Property[@name="Name"]/docs/*' /> public string Name { get { return configName; } set { if (configName != value) { Rename (value); } } } /// <include file='IConfig.xml' path='//Property[@name="ConfigSource"]/docs/*' /> public IConfigSource ConfigSource { get { return configSource; } } /// <include file='IConfig.xml' path='//Property[@name="Alias"]/docs/*' /> public AliasText Alias { get { return aliasText; } } #endregion #region Public methods /// <include file='IConfig.xml' path='//Method[@name="Contains"]/docs/*' /> public bool Contains (string key) { return (Get (key) != null); } /// <include file='IConfig.xml' path='//Method[@name="Get"]/docs/*' /> public virtual string Get (string key) { string result = null; if (keys.Contains (key)) { result = keys[key].ToString (); } return result; } /// <include file='IConfig.xml' path='//Method[@name="GetDefault"]/docs/*' /> public string Get (string key, string defaultValue) { string result = Get (key); return (result == null) ? defaultValue : result; } /// <include file='IConfig.xml' path='//Method[@name="GetExpanded"]/docs/*' /> public string GetExpanded (string key) { return this.ConfigSource.GetExpanded(this, key); } /// <include file='IConfig.xml' path='//Method[@name="Get"]/docs/*' /> public string GetString (string key) { return Get (key); } /// <include file='IConfig.xml' path='//Method[@name="GetDefault"]/docs/*' /> public string GetString (string key, string defaultValue) { return Get (key, defaultValue); } /// <include file='IConfig.xml' path='//Method[@name="GetInt"]/docs/*' /> public int GetInt (string key) { string text = Get (key); if (text == null) { throw new ArgumentException ("Value not found: " + key); } return Convert.ToInt32 (text, format); } /// <include file='IConfig.xml' path='//Method[@name="GetIntAlias"]/docs/*' /> public int GetInt (string key, bool fromAlias) { if (!fromAlias) { return GetInt (key); } string result = Get (key); if (result == null) { throw new ArgumentException ("Value not found: " + key); } return GetIntAlias (key, result); } /// <include file='IConfig.xml' path='//Method[@name="GetIntDefault"]/docs/*' /> public int GetInt (string key, int defaultValue) { string result = Get (key); return (result == null) ? defaultValue : Convert.ToInt32 (result, format); } /// <include file='IConfig.xml' path='//Method[@name="GetIntDefaultAlias"]/docs/*' /> public int GetInt (string key, int defaultValue, bool fromAlias) { if (!fromAlias) { return GetInt (key, defaultValue); } string result = Get (key); return (result == null) ? defaultValue : GetIntAlias (key, result); } /// <include file='IConfig.xml' path='//Method[@name="GetLong"]/docs/*' /> public long GetLong (string key) { string text = Get (key); if (text == null) { throw new ArgumentException ("Value not found: " + key); } return Convert.ToInt64 (text, format); } /// <include file='IConfig.xml' path='//Method[@name="GetLongDefault"]/docs/*' /> public long GetLong (string key, long defaultValue) { string result = Get (key); return (result == null) ? defaultValue : Convert.ToInt64 (result, format); } /// <include file='IConfig.xml' path='//Method[@name="GetBoolean"]/docs/*' /> public bool GetBoolean (string key) { string text = Get (key); if (text == null) { throw new ArgumentException ("Value not found: " + key); } return GetBooleanAlias (text); } /// <include file='IConfig.xml' path='//Method[@name="GetBooleanDefault"]/docs/*' /> public bool GetBoolean (string key, bool defaultValue) { string text = Get (key); return (text == null) ? defaultValue : GetBooleanAlias (text); } /// <include file='IConfig.xml' path='//Method[@name="GetFloat"]/docs/*' /> public float GetFloat (string key) { string text = Get (key); if (text == null) { throw new ArgumentException ("Value not found: " + key); } return Convert.ToSingle (text, format); } /// <include file='IConfig.xml' path='//Method[@name="GetFloatDefault"]/docs/*' /> public float GetFloat (string key, float defaultValue) { string result = Get (key); return (result == null) ? defaultValue : Convert.ToSingle (result, format); } /// <include file='IConfig.xml' path='//Method[@name="GetDouble"]/docs/*' /> public double GetDouble (string key) { string text = Get (key); if (text == null) { throw new ArgumentException ("Value not found: " + key); } return Convert.ToDouble (text, format); } /// <include file='IConfig.xml' path='//Method[@name="GetDoubleDefault"]/docs/*' /> public double GetDouble (string key, double defaultValue) { string result = Get (key); return (result == null) ? defaultValue : Convert.ToDouble (result, format); } /// <include file='IConfig.xml' path='//Method[@name="GetKeys"]/docs/*' /> public string[] GetKeys () { string[] result = new string[keys.Keys.Count]; keys.Keys.CopyTo (result, 0); return result; } /// <include file='IConfig.xml' path='//Method[@name="GetValues"]/docs/*' /> public string[] GetValues () { string[] result = new string[keys.Values.Count]; keys.Values.CopyTo (result, 0); return result; } /// <include file='ConfigBase.xml' path='//Method[@name="Add"]/docs/*' /> public void Add (string key, string value) { keys.Add (key, value); } /// <include file='IConfig.xml' path='//Method[@name="Set"]/docs/*' /> public virtual void Set (string key, object value) { if (value == null) { throw new ArgumentNullException ("Value cannot be null"); } if (Get (key) == null) { this.Add (key, value.ToString ()); } else { keys[key] = value.ToString (); } if (ConfigSource.AutoSave) { ConfigSource.Save (); } OnKeySet (new ConfigKeyEventArgs (key, value.ToString ())); } /// <include file='IConfig.xml' path='//Method[@name="Remove"]/docs/*' /> public virtual void Remove (string key) { if (key == null) { throw new ArgumentNullException ("Key cannot be null"); } if (Get (key) != null) { string keyValue = null; if (KeySet != null) { keyValue = Get (key); } keys.Remove (key); OnKeyRemoved (new ConfigKeyEventArgs (key, keyValue)); } } #endregion #region Public events /// <include file='IConfig.xml' path='//Event[@name="KeySet"]/docs/*' /> public event ConfigKeyEventHandler KeySet; /// <include file='IConfig.xml' path='//Event[@name="KeyRemoved"]/docs/*' /> public event ConfigKeyEventHandler KeyRemoved; #endregion #region Protected methods /// <include file='ConfigBase.xml' path='//Method[@name="OnKeySet"]/docs/*' /> protected void OnKeySet (ConfigKeyEventArgs e) { if (KeySet != null) { KeySet (this, e); } } /// <include file='ConfigBase.xml' path='//Method[@name="OnKeyRemoved"]/docs/*' /> protected void OnKeyRemoved (ConfigKeyEventArgs e) { if (KeyRemoved != null) { KeyRemoved (this, e); } } #endregion #region Private methods /// <summary> /// Renames the config to the new name. /// </summary> private void Rename (string name) { this.ConfigSource.Configs.Remove (this); configName = name; this.ConfigSource.Configs.Add (this); } /// <summary> /// Returns the integer alias first from this IConfig then /// the parent if there is none. /// </summary> private int GetIntAlias (string key, string alias) { int result = -1; if (aliasText.ContainsInt (key, alias)) { result = aliasText.GetInt (key, alias); } else { result = ConfigSource.Alias.GetInt (key, alias); } return result; } /// <summary> /// Returns the boolean alias first from this IConfig then /// the parent if there is none. /// </summary> private bool GetBooleanAlias (string key) { bool result = false; if (aliasText.ContainsBoolean (key)) { result = aliasText.GetBoolean (key); } else { if (ConfigSource.Alias.ContainsBoolean (key)) { result = ConfigSource.Alias.GetBoolean (key); } else { throw new ArgumentException ("Alias value not found: " + key + ". Add it to the Alias property."); } } return result; } #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 MultiplyAddAdjacentInt16() { var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt16(); 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(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } 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__MultiplyAddAdjacentInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Byte[] inArray1, SByte[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Byte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Byte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Byte> _fld1; public Vector256<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref testStruct._fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyAddAdjacentInt16 testClass) { var result = Avx2.MultiplyAddAdjacent(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyAddAdjacentInt16 testClass) { fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Byte>>() / sizeof(Byte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<SByte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MultiplyAddAdjacentInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); } public SimpleBinaryOpTest__MultiplyAddAdjacentInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Byte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.MultiplyAddAdjacent( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.MultiplyAddAdjacent( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyAddAdjacent), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyAddAdjacent), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyAddAdjacent), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<SByte>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.MultiplyAddAdjacent( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Byte>* pClsVar1 = &_clsVar1) fixed (Vector256<SByte>* pClsVar2 = &_clsVar2) { var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(pClsVar1)), Avx.LoadVector256((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<SByte>>(_dataTable.inArray2Ptr); var result = Avx2.MultiplyAddAdjacent(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.MultiplyAddAdjacent(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((SByte*)(_dataTable.inArray2Ptr)); var result = Avx2.MultiplyAddAdjacent(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt16(); var result = Avx2.MultiplyAddAdjacent(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MultiplyAddAdjacentInt16(); fixed (Vector256<Byte>* pFld1 = &test._fld1) fixed (Vector256<SByte>* pFld2 = &test._fld2) { var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.MultiplyAddAdjacent(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Byte>* pFld1 = &_fld1) fixed (Vector256<SByte>* pFld2 = &_fld2) { var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(pFld1)), Avx.LoadVector256((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.MultiplyAddAdjacent(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.MultiplyAddAdjacent( Avx.LoadVector256((Byte*)(&test._fld1)), Avx.LoadVector256((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Byte> op1, Vector256<SByte> op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Byte[] left, SByte[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != Math.Clamp(((right[1] * left[1]) + (right[0] * left[0])), short.MinValue, short.MaxValue)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != Math.Clamp(((right[(i * 2) + 1] * left[(i * 2) + 1]) + (right[i * 2] * left[i * 2])), short.MinValue, short.MaxValue)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MultiplyAddAdjacent)}<Int16>(Vector256<Byte>, Vector256<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Linq.Expressions { /// <summary> /// Represents a constructor call that has a collection initializer. /// </summary> /// <remarks> /// Use the <see cref="M:ListInit"/> factory methods to create a ListInitExpression. /// The value of the NodeType property of a ListInitExpression is ListInit. /// </remarks> [DebuggerTypeProxy(typeof(Expression.ListInitExpressionProxy))] public sealed class ListInitExpression : Expression { private readonly NewExpression _newExpression; private readonly ReadOnlyCollection<ElementInit> _initializers; internal ListInitExpression(NewExpression newExpression, ReadOnlyCollection<ElementInit> initializers) { _newExpression = newExpression; _initializers = initializers; } /// <summary> /// Returns the node type of this <see cref="Expression"/>. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.ListInit; } } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _newExpression.Type; } } /// <summary> /// Gets a value that indicates whether the expression tree node can be reduced. /// </summary> public override bool CanReduce { get { return true; } } /// <summary> /// Gets the expression that contains a call to the constructor of a collection type. /// </summary> public NewExpression NewExpression { get { return _newExpression; } } /// <summary> /// Gets the element initializers that are used to initialize a collection. /// </summary> public ReadOnlyCollection<ElementInit> Initializers { get { return _initializers; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitListInit(this); } /// <summary> /// Reduces the binary expression node to a simpler expression. /// If CanReduce returns true, this should return a valid expression. /// This method is allowed to return another node which itself /// must be reduced. /// </summary> /// <returns>The reduced expression.</returns> public override Expression Reduce() { return MemberInitExpression.ReduceListInit(_newExpression, _initializers, true); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="newExpression">The <see cref="NewExpression" /> property of the result.</param> /// <param name="initializers">The <see cref="Initializers" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public ListInitExpression Update(NewExpression newExpression, IEnumerable<ElementInit> initializers) { if (newExpression == NewExpression && initializers == Initializers) { return this; } return Expression.ListInit(newExpression, initializers); } } public partial class Expression { /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param> /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns> public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers) { return ListInit(newExpression, initializers as IEnumerable<Expression>); } /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses a method named "Add" to add elements to a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param> /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns> public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers) { ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); var initializerlist = initializers.ToReadOnly(); if (initializerlist.Count == 0) { throw Error.ListInitializerWithZeroMembers(); } MethodInfo addMethod = FindMethod(newExpression.Type, "Add", null, new Expression[] { initializerlist[0] }, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); return ListInit(newExpression, addMethod, initializers); } /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param> /// <param name="initializers">An array of <see cref="Expression"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param> /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns> public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, params Expression[] initializers) { return ListInit(newExpression, addMethod, initializers as IEnumerable<Expression>); } /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses a specified method to add elements to a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="addMethod">A <see cref="MethodInfo"/> that represents an instance method named "Add" (case insensitive), that adds an element to a collection. </param> /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="Expression"/> objects to use to populate the Initializers collection.</param> /// <returns>A <see cref="ListInitExpression"/> that has the <see cref="P:ListInitExpression.NodeType"/> property equal to ListInit and the <see cref="P:ListInitExpression.NewExpression"/> property set to the specified value.</returns> public static ListInitExpression ListInit(NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers) { if (addMethod == null) { return ListInit(newExpression, initializers); } ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); var initializerlist = initializers.ToReadOnly(); if (initializerlist.Count == 0) { throw Error.ListInitializerWithZeroMembers(); } ElementInit[] initList = new ElementInit[initializerlist.Count]; for (int i = 0; i < initializerlist.Count; i++) { initList[i] = ElementInit(addMethod, initializerlist[i]); } return ListInit(newExpression, new TrueReadOnlyCollection<ElementInit>(initList)); } /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="initializers">An array that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param> /// <returns> /// A <see cref="ListInitExpression"/> that has the <see cref="P:Expressions.NodeType"/> property equal to ListInit /// and the <see cref="P:ListInitExpression.NewExpression"/> and <see cref="P:ListInitExpression.Initializers"/> properties set to the specified values. /// </returns> /// <remarks> /// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>. /// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type. /// </remarks> public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers) { return ListInit(newExpression, (IEnumerable<ElementInit>)initializers); } /// <summary> /// Creates a <see cref="ListInitExpression"/> that uses specified <see cref="M:ElementInit"/> objects to initialize a collection. /// </summary> /// <param name="newExpression">A <see cref="NewExpression"/> to set the <see cref="P:ListInitExpression.NewExpression"/> property equal to.</param> /// <param name="initializers">An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains <see cref="M:ElementInit"/> objects to use to populate the <see cref="ListInitExpression.Initializers"/> collection.</returns> /// <remarks> /// The <see cref="P:Expressions.Type"/> property of <paramref name="newExpression"/> must represent a type that implements <see cref="System.Collections.IEnumerable"/>. /// The <see cref="P:Expressions.Type"/> property of the resulting <see cref="ListInitExpression"/> is equal to newExpression.Type. /// </remarks> public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers) { ContractUtils.RequiresNotNull(newExpression, nameof(newExpression)); ContractUtils.RequiresNotNull(initializers, nameof(initializers)); var initializerlist = initializers.ToReadOnly(); if (initializerlist.Count == 0) { throw Error.ListInitializerWithZeroMembers(); } ValidateListInitArgs(newExpression.Type, initializerlist); return new ListInitExpression(newExpression, initializerlist); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is DotSpatial.dll for the DotSpatial project // // The Initial Developer of this Original Code is Ted Dunsford. Created in January 2008. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.Drawing; namespace DotSpatial.Data { public interface IRaster : IRasterBoundDataSet, ICloneable { #region Methods /// <summary> /// This only works for in-ram rasters. This basically makes a new raster that has all the same /// in memory values /// </summary> /// <returns>An IRaster that is a duplicate of this class</returns> IRaster Copy(); /// <summary> /// Creates a duplicate version of this file. If copyValues is set to false, then a raster of NoData values is created /// that has the same georeferencing information as the source file of this Raster, even if this raster is just a window. /// </summary> /// <param name="fileName">The string fileName specifying where to create the new file.</param> /// <param name="copyValues">If this is false, the same size and georeferencing values are used, but they are all set to NoData.</param> void Copy(string fileName, bool copyValues); /// <summary> /// Even if this is a window, this will cause this raster to show statistics calculated from the entire file. /// </summary> void GetStatistics(); /// <summary> /// Most raster methods are optimized for reading in lines or blocks at a time. This one is designed /// to be used for scattered points. /// </summary> /// <param name="indices">The zero based integer index that is Row * NumColumnsInFile + Column</param> /// <returns>The list of double values</returns> List<double> GetValues(IEnumerable<long> indices); /// <summary> /// Returns a subset from the file that includes only the specified offsets. The result is a raster, /// and the extents are calculated, but the row and column values are in terms of the window, /// not the original raster. The band can be controlled by setting the "Current Band" first. /// </summary> /// <param name="xOff">X axis or horizontal offset (0 based from left)</param> /// <param name="yOff">Y axis or vertical offset (0 based from top)</param> /// <param name="sizeX">Number of columns</param> /// <param name="sizeY">Number of rows</param> /// <returns>An IRaster created from the appropriate type;.</returns> IRaster ReadBlock(int xOff, int yOff, int sizeX, int sizeY); /// <summary> /// This writes the values to the file, even if the IRaster has more values than the xSize or ySize /// stipulate, and even if the source raster has values of a different type. /// </summary> /// <param name="blockValues">The IRaster that contains data values to write to the file</param> /// <param name="xOff">The 0 based integer horizontal offset from the left</param> /// <param name="yOff">The 0 based integer vertical offset from the top</param> /// <param name="xSize">The integer number of columns to write</param> /// <param name="ySize">The integer number of rows to write</param> void WriteBlock(IRaster blockValues, int xOff, int yOff, int xSize, int ySize); /// <summary> /// Saves changes from any values that are in memory to the file. This will preserve the existing /// structure and attempt to only write values to the parts of the file that match the loaded window. /// </summary> void Save(); /// <summary> /// This will save whatever is specified in the startRow, endRow, startColumn, endColumn bounds /// to a new file with the specified fileName. /// </summary> /// <param name="fileName">The string fileName to save the current raster to.</param> void SaveAs(string fileName); /// <summary> /// This code is required to allow a new format to save data from an old format quickly. /// It essentially quickly transfers the underlying data values to the new raster. /// </summary> /// <param name="original"></param> void SetData(IRaster original); /// <summary> /// Gets this raster (or its Internal Raster) as the appropriately typed raster /// so that strong typed access methods are available, instead of just the /// regular methods, or null if the type is incorrect. (Check datatype property). /// </summary> /// <typeparam name="T">The type (int, short, float, etc.)</typeparam> /// <returns>The Raster&lt;T&gt; where T are value types like int, short and float. Returns null if the type is wrong.</returns> Raster<T> ToRaster<T>() where T : IEquatable<T>, IComparable<T>; /// <summary> /// Instructs the raster to write only the header content. This is especially useful if you just want to update /// the extents or the projection of the raster, without changing the data values. /// </summary> void WriteHeader(); #endregion #region Properties /// <summary> /// Gets the integer size of each data member of the raster in bytes. /// </summary> int ByteSize { get; } /// <summary> /// Gets or sets the list of bands, which are in turn rasters. The rasters /// contain only one band each, instead of the list of all the bands like the /// parent raster. /// </summary> IList<IRaster> Bands { get; set; } /// <summary> /// The geographic height of a cell the projected units. Setting this will /// automatically adjust the affine coefficient to a negative value. /// </summary> double CellHeight { get; set; } /// <summary> /// The geographic width of a cell in the projected units /// </summary> double CellWidth { get; set; } /// <summary> /// This provides a zero-based integer band index that specifies which of the internal bands /// is currently being used for requests for data. /// </summary> int CurrentBand { get; } /// <summary> /// This does nothing unless the FileType property is set to custom. /// In such a case, this string allows new file types to be managed. /// </summary> string CustomFileType { get; } /// <summary> /// This reveals the underlying data type /// </summary> Type DataType { get; set; } /// <summary> /// Gets or sets a short string to identify which driver to use. This is primarilly used by GDAL rasters. /// </summary> string DriverCode { get; set; } /// <summary> /// The integer column index for the right column of this raster. Most of the time this will /// be NumColumns - 1. However, if this raster is a window taken from a larger raster, then /// it will be the index of the endColumn from the window. /// </summary> int EndColumn { get; } /// <summary> /// The integer row index for the end row of this raster. Most of the time this will /// be numRows - 1. However, if this raster is a window taken from a larger raster, then /// it will be the index of the endRow from the window. /// </summary> int EndRow { get; } /// <summary> /// Gets the file type of this grid. /// </summary> RasterFileType FileType { get; set; } /// <summary> /// Gets a boolean that is true if the data for this raster is in memory. /// </summary> bool IsInRam { get; } /// <summary> /// Gets the maximum data value, not counting no-data values in the grid. /// </summary> double Maximum { get; } /// <summary> /// Gets the mean of the non-NoData values in this grid. If the data is not InRam, then /// the GetStatistics method must be called before these values will be correct. /// </summary> double Mean { get; } /// <summary> /// Gets the minimum data value that is not classified as a no data value in this raster. /// </summary> double Minimum { get; } /// <summary> /// A float showing the no-data values /// </summary> double NoDataValue { get; set; } /// <summary> /// For binary rasters this will get cut to only 256 characters. /// </summary> string Notes { get; set; } /// <summary> /// Gets the number of bands. In most traditional grid formats, this is 1. For RGB images, /// this would be 3. Some formats may have many bands. /// </summary> int NumBands { get; } /// <summary> /// Gets the horizontal count of the cells in the raster. /// </summary> int NumColumns { get; } /// <summary> /// Gets the integer count of columns in the file, as opposed to the /// number represented by this raster, which might just represent a window. /// </summary> int NumColumnsInFile { get; } /// <summary> /// Gets the vertical count of the cells in the raster. /// </summary> int NumRows { get; } /// <summary> /// Gets the number of rows in the source file, as opposed to the number /// represented by this raster, which might just represent part of a file. /// </summary> int NumRowsInFile { get; } /// <summary> /// Gets the count of the cells that are not no-data. If the data is not InRam, then /// you will have to first call the GetStatistics() method to gain meaningul values. /// </summary> long NumValueCells { get; } /// <summary> /// Gets or sets the string array of options to use when saving this raster. /// </summary> string[] Options { get; set; } /// <summary> /// Gets a list of the rows in this raster that can be accessed independantly. /// </summary> List<IValueRow> Rows { get; } /// <summary> /// The integer column index for the left column of this raster. Most of the time this will /// be 0. However, if this raster is a window taken from a file, then /// it will be the row index in the file for the top row of this raster. /// </summary> int StartColumn { get; } /// <summary> /// The integer row index for the top row of this raster. Most of the time this will /// be 0. However, if this raster is a window taken from a file, then /// it will be the row index in the file for the left row of this raster. /// </summary> int StartRow { get; } /// <summary> /// Gets the standard deviation of all the Non-nodata cells. If the data is not InRam, /// then you will have to first call the GetStatistics() method to get meaningful values. /// </summary> double StdDeviation { get; } /// <summary> /// This is provided for future developers to link this raster to other entities. /// It has no function internally, so it can be manipulated safely. /// </summary> object Tag { get; set; } /// <summary> /// Gets or sets the value on the CurrentBand given a row and column undex /// </summary> IValueGrid Value { get; set; } /// <summary> /// The horizontal or longitude coordinate for the lower left cell in the grid /// </summary> double Xllcenter { get; set; } /// <summary> /// The vertical or latitude coordinate for the lower left cell in the grid /// </summary> double Yllcenter { get; set; } /// <summary> /// This doesn't perform calculations, but is simply a place holder where sample /// values can be stored and retrieved as a cache. /// </summary> IEnumerable<double> Sample { get; set; } /// <summary> /// A raster can contain predefined names for its categories /// </summary> /// <returns>null if raster has no category names</returns> String[] CategoryNames(); /// <summary> /// A raster can contain predefined colors for its categories, for example NLCD GeoTIFF has a palette /// </summary> /// <returns>null if raster has no category colors</returns> Color[] CategoryColors(); #endregion #region Events /// <summary> /// Occurs when attempting to copy or save to a fileName that already exists. A developer can tap into this event /// in order to display an appropriate message. A cancel property allows the developer (and ultimately the user) /// decide if the specified event should ultimately be cancelled. /// </summary> event EventHandler<MessageCancelEventArgs> FileExists; #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml.Linq; using StyleCop; namespace StyleCopAutoFix { class Program { static void Main(string[] args) { if (args.Length == 0) { Console.WriteLine("USAGE: StyleCopAutoFix sln_filepath|csproj_filepath|cs_filepath"); return; } //fix rules one by one //same line number can be reported several times by StyleCop (but for different rules), it is important to fix rules one by one. string[] rules = new string[] { "SA1514", "SA1512", "SA1516", "SA1507", "SA1508", "SA1518", "SA1505", "SA1513", "SA1515", "SA1517" }; int totalViolationsFound = 0, totalViolationsFixed = 0; bool countViolations = true; foreach (string rule in rules) { FixStyleCopRule(args[0], rule, (sender, e) => { if(countViolations) { totalViolationsFound++; } if (e.Violation.Rule.CheckId == rule) { totalViolationsFixed++; } }); countViolations = false; } Console.WriteLine("StyleCop violations found : {0}", totalViolationsFound); Console.WriteLine("StyleCop violations fixed : {0}", totalViolationsFixed); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } private static void FixStyleCopRule(string projectFilePath, string rule, EventHandler<ViolationEventArgs> onViolationEncountered) { foreach (string filePath in GetCSharpFiles(projectFilePath)) { StyleCopConsole console = new StyleCopConsole(null, false, null, null, true); CodeProject project = new CodeProject(0, Path.GetDirectoryName(projectFilePath), new Configuration(null)); bool fileHasBeenFixed = false; List<Tuple<int, string>> sourceCode = File.ReadAllText(filePath).Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None) .Select((line, index) => new Tuple<int, string>(index + 1, line)).ToList(); if (console.Core.Environment.AddSourceCode(project, filePath, null)) { console.ViolationEncountered += onViolationEncountered; console.ViolationEncountered += (sender, e) => { if (e.Violation.Rule.CheckId == rule) { FixStyleCopViolation(sourceCode, e); Console.WriteLine("{0}({1}): {2}", rule, e.LineNumber, filePath); fileHasBeenFixed = true; } }; console.Start(new[] { project }, true); } if (fileHasBeenFixed) { //preserve text encoding System.Text.Encoding encoding; using (StreamReader reader = new StreamReader(filePath, true)) { encoding = reader.CurrentEncoding; } File.WriteAllText(filePath, string.Join(Environment.NewLine, sourceCode.Select(x => x.Item2)), encoding); } } } private static IEnumerable<string> GetCSharpFiles(string filePath) { switch (Path.GetExtension(filePath)) { case ".sln": return GetCSharpFilesInSolution(filePath); case ".csproj": return GetCSharpFilesInProject(filePath); case ".cs": return new string[] { filePath }; default: throw new Exception("Invalid command line argument: " + filePath); } } private static IEnumerable<string> GetCSharpFilesInSolution(string filePath) { string directoryName = Path.GetDirectoryName(filePath); Regex r = new Regex("^Project\\(\"(.*)\"\\) = \"(.*)\", \"(.*)\", \"(.*)\"$", RegexOptions.Multiline); return File.ReadAllLines(filePath).SelectMany(x => r.Matches(x).Cast<Match>().SelectMany(y => GetCSharpFilesInProject(Path.Combine(directoryName, y.Groups[3].Value)))); } private static IEnumerable<string> GetCSharpFilesInProject(string filePath) { string directoryName = Path.GetDirectoryName(filePath); XDocument project = XDocument.Load(filePath); XNamespace ns = XNamespace.Get(@"http://schemas.microsoft.com/developer/msbuild/2003"); return from el in project.Root .Elements(ns + "ItemGroup") .Elements(ns + "Compile") .Where(x => x.Element(ns + "ExcludeFromStyleCop") == null && x.Element(ns + "ExcludeFromSourceAnalysis") == null) select Path.Combine(directoryName, el.Attribute("Include").Value); } private static void AddEmptyLine(List<Tuple<int, string>> sourceCode, int lineNumber) { sourceCode.Insert(sourceCode.FindIndex(x => x.Item1 == lineNumber), new Tuple<int, string>(-1, string.Empty)); } private static void RemoveEmptyLine(List<Tuple<int, string>> sourceCode, int lineNumber) { Debug.Assert(string.IsNullOrEmpty(sourceCode[sourceCode.FindIndex(x => x.Item1 == lineNumber)].Item2.Trim())); sourceCode.RemoveAt(sourceCode.FindIndex(x => x.Item1 == lineNumber)); } private static void FixStyleCopViolation(List<Tuple<int, string>> sourceCode, ViolationEventArgs e) { switch (e.Violation.Rule.CheckId) { //ElementsMustBeSeparatedByBlankLine case "SA1516": AddEmptyLine(sourceCode, e.LineNumber); break; //CodeMustNotContainMultipleBlankLinesInARow case "SA1507": RemoveEmptyLine(sourceCode, e.LineNumber); break; //ClosingCurlyBracketsMustNotBePrecededByBlankLine case "SA1508": RemoveEmptyLine(sourceCode, e.LineNumber - 1); break; //CodeMustNotContainBlankLinesAtEndOfFile case "SA1518": RemoveEmptyLine(sourceCode, e.LineNumber); break; //OpeningCurlyBracketsMustNotBeFollowedByBlankLine case "SA1505": RemoveEmptyLine(sourceCode, e.LineNumber+1); break; //ClosingCurlyBracketMustBeFollowedByBlankLine case "SA1513": AddEmptyLine(sourceCode, e.LineNumber + 1); break; //SingleLineCommentsMustBePrecededByBlankLine case "SA1515": AddEmptyLine(sourceCode, e.LineNumber); break; //ElementDocumentationHeadersMustBePrecededByBlankLine case "SA1514": AddEmptyLine(sourceCode, e.LineNumber); break; //SingleLineCommentsMustNotBeFollowedByBlankLine case "SA1512": RemoveEmptyLine(sourceCode, e.LineNumber + 1); break; //CodeMustNotContainBlankLinesAtStartOfFile case "SA1517": RemoveEmptyLine(sourceCode, e.LineNumber); break; default: throw new NotImplementedException(); } } } }
// 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.Reflection; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { internal class DebuggerBrowsableAttributeTests : CSharpResultProviderTestBase { [Fact] public void Never() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class C { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object F = 1; object P { get { return 3; } } } class P { public P(C c) { } public object G = 2; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public object Q { get { return 4; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("new C()", value); Verify(evalResult, EvalResult("new C()", "{C}", "C", "new C()", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("G", "2", "object {int}", "new P(new C()).G"), EvalResult("Raw View", null, "", "new C(), raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); children = GetChildren(children[1]); Verify(children, EvalResult("P", "3", "object {int}", "(new C()).P", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DebuggerBrowsableAttributes are not inherited. /// </summary> [Fact] public void Never_OverridesAndImplements() { var source = @"using System.Diagnostics; interface I { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P1 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object P2 { get; } object P3 { get; } object P4 { get; } } abstract class A { [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P5 { get; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal virtual object P6 { get { return 0; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal abstract object P7 { get; } internal abstract object P8 { get; } } class B : A, I { public object P1 { get { return 1; } } object I.P2 { get { return 2; } } object I.P3 { get { return 3; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] object I.P4 { get { return 4; } } internal override object P5 { get { return 5; } } internal override object P6 { get { return 6; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P7 { get { return 7; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal override object P8 { get { return 8; } } } class C { I o = new B(); }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("c", value); Verify(evalResult, EvalResult("c", "{C}", "C", "c", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("o", "{B}", "I {B}", "c.o", DkmEvaluationResultFlags.Expandable)); children = GetChildren(children[0]); Verify(children, EvalResult("I.P2", "2", "object {int}", "c.o.P2", DkmEvaluationResultFlags.ReadOnly), EvalResult("I.P3", "3", "object {int}", "c.o.P3", DkmEvaluationResultFlags.ReadOnly), EvalResult("P1", "1", "object {int}", "((B)c.o).P1", DkmEvaluationResultFlags.ReadOnly), EvalResult("P5", "5", "object {int}", "((B)c.o).P5", DkmEvaluationResultFlags.ReadOnly), EvalResult("P6", "6", "object {int}", "((B)c.o).P6", DkmEvaluationResultFlags.ReadOnly)); } /// <summary> /// DkmClrDebuggerBrowsableAttributes are obtained from the /// containing type and associated with the member name. For /// explicit interface implementations, the name will include /// namespace and type. /// </summary> [Fact] public void Never_ExplicitNamespaceGeneric() { var source = @"using System.Diagnostics; namespace N1 { namespace N2 { class A<T> { internal interface I<U> { T P { get; } U Q { get; } } } } class B : N2.A<object>.I<int> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] object N2.A<object>.I<int>.P { get { return 1; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public int Q { get { return 2; } } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("N1.B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{N1.B}", "N1.B", "o")); } [Fact] public void RootHidden() { var source = @"using System.Diagnostics; struct S { internal S(int[] x, object[] y) : this() { this.F = x; this.Q = y; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int[] F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal int P { get { return this.F.Length; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object[] Q { get; private set; } } class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly B G = new B { H = 4 }; } class B { internal object H; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeA = assembly.GetType("A"); var value = CreateDkmClrValue( value: typeS.Instantiate(new int[] { 1, 2 }, new object[] { 3, typeA.Instantiate() }), type: new DkmClrType((TypeImpl)typeS), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{S}", "S", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.F[0]"), EvalResult("[1]", "2", "int", "o.F[1]"), EvalResult("[0]", "3", "object {int}", "o.Q[0]"), EvalResult("[1]", "{A}", "object {A}", "o.Q[1]", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[3]), EvalResult("H", "4", "object {int}", "((A)o.Q[1]).G.H")); } [Fact] public void RootHidden_Exception() { var source = @"using System; using System.Diagnostics; class E : Exception { } class F : E { object G = 1; } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] object P { get { throw new F(); } } }"; using (new EnsureEnglishUICulture()) { var runtime = new DkmClrRuntimeInstance(ReflectionUtilities.GetMscorlib(GetAssembly(source))); using (runtime.Load()) { var type = runtime.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children[1], EvalResult("G", "1", "object {int}", null)); Verify(children[7], EvalResult("Message", "\"Exception of type 'F' was thrown.\"", "string", null, DkmEvaluationResultFlags.RawString | DkmEvaluationResultFlags.ReadOnly)); } } } /// <summary> /// Instance of type where all members are marked /// [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]. /// </summary> [WorkItem(934800, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/934800")] [Fact] public void RootHidden_Empty() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F1 = new C(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F2 = new C(); } class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F3 = new object(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly object F4 = null; }"; var assembly = GetAssembly(source); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); // Ideally, not expandable. var children = GetChildren(evalResult); Verify(children); // No children. } [Fact] public void DebuggerBrowsable_GenericType() { var source = @"using System.Diagnostics; class C<T> { internal C(T f, T g) { this.F = f; this.G = g; } [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal readonly T F; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal readonly T G; } struct S { internal S(object o) { this.O = o; } internal readonly object O; }"; var assembly = GetAssembly(source); var typeS = assembly.GetType("S"); var typeC = assembly.GetType("C`1").MakeGenericType(typeS); var value = CreateDkmClrValue( value: typeC.Instantiate(typeS.Instantiate(1), typeS.Instantiate(2)), type: new DkmClrType((TypeImpl)typeC), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<S>}", "C<S>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("O", "2", "object {int}", "o.G.O", DkmEvaluationResultFlags.ReadOnly)); } [Fact] public void RootHidden_ExplicitImplementation() { var source = @"using System.Diagnostics; interface I<T> { T P { get; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] T Q { get; } } class A { internal object F; } class B : I<A> { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] A I<A>.P { get { return new A() { F = 1 }; } } A I<A>.Q { get { return new A() { F = 2 }; } } }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "1", "object {int}", "((I<A>)o).P.F"), EvalResult("I<A>.Q", "{A}", "A", "((I<A>)o).Q", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("F", "2", "object {int}", "((I<A>)o).Q.F")); } [Fact] public void RootHidden_ProxyType() { var source = @"using System.Diagnostics; [DebuggerTypeProxy(typeof(P))] class A { internal A(int f) { this.F = f; } internal int F; } class P { private readonly A a; public P(A a) { this.a = a; } public object Q { get { return this.a.F; } } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object R { get { return this.a.F + 1; } } } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F = new A(1); internal object G = new A(3); }"; var assembly = GetAssembly(source); var type = assembly.GetType("B"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{B}", "B", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Q", "1", "object {int}", "new P(o.F).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.F, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("G", "{A}", "object {A}", "o.G", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(children[1]), EvalResult("F", "1", "int", "((A)o.F).F")); Verify(GetChildren(children[2]), EvalResult("Q", "3", "object {int}", "new P(o.G).Q", DkmEvaluationResultFlags.ReadOnly), EvalResult("Raw View", null, "", "o.G, raw", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); } [Fact] public void RootHidden_Recursive() { var source = @"using System.Diagnostics; class A { internal A(object o) { this.F = o; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal object F; } class B { internal B(object o) { this.F = o; } internal object F; }"; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = assembly.GetType("B"); var value = CreateDkmClrValue( value: typeA.Instantiate(typeA.Instantiate(typeA.Instantiate(typeB.Instantiate(4)))), type: new DkmClrType((TypeImpl)typeA), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("F", "4", "object {int}", "((B)((A)((A)o.F).F).F).F")); } [Fact] public void RootHidden_OnStaticMembers() { var source = @"using System.Diagnostics; class A { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object F = new B(); } class B { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] internal static object P { get { return new C(); } } internal static object G = 1; } class C { internal static object Q { get { return 3; } } internal object H = 2; }"; var assembly = GetAssembly(source); var type = assembly.GetType("A"); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{A}", "A", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[0]); Verify(children, EvalResult("G", "1", "object {int}", "B.G"), EvalResult("H", "2", "object {int}", "((C)B.P).H"), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class)); children = GetChildren(children[2]); Verify(children, EvalResult("Q", "3", "object {int}", "C.Q", DkmEvaluationResultFlags.ReadOnly)); } // Dev12 exposes the contents of RootHidden members even // if the members are private (e.g.: ImmutableArray<T>). [Fact] public void RootHidden_OnNonPublicMembers() { var source = @"using System.Diagnostics; public class C<T> { public C(params T[] items) { this.items = items; } [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] private T[] items; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(1, 2, 3), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("[0]", "1", "int", "o.items[0]"), EvalResult("[1]", "2", "int", "o.items[1]"), EvalResult("[2]", "3", "int", "o.items[2]")); } // Dev12 does not merge "Static members" (or "Non-Public // members") across multiple RootHidden members. In // other words, there may be multiple "Static members" (or // "Non-Public members") rows within the same container. [Fact] public void RootHidden_WithStaticAndNonPublicMembers() { var source = @"using System.Diagnostics; public class A { public static int PA { get { return 1; } } internal int FA = 2; } public class B { internal int PB { get { return 3; } } public static int FB = 4; } public class C { [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public readonly object FA = new A(); [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public object PB { get { return new B(); } } public static int PC { get { return 5; } } internal int FC = 6; }"; var assembly = GetAssembly(source); var runtime = new DkmClrRuntimeInstance(new Assembly[0]); var type = assembly.GetType("C"); var value = CreateDkmClrValue( value: type.Instantiate(), type: new DkmClrType(runtime.DefaultModule, runtime.DefaultAppDomain, (TypeImpl)type), evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value, inspectionContext: CreateDkmInspectionContext(DkmEvaluationFlags.HideNonPublicMembers)); Verify(evalResult, EvalResult("o", "{C}", "C", "o", DkmEvaluationResultFlags.Expandable)); var children = GetChildren(evalResult); Verify(children, EvalResult("Static members", null, "", "A", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.FA, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "B", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o.PB, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data), EvalResult("Static members", null, "", "C", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Class), EvalResult("Non-Public members", null, "", "o, hidden", DkmEvaluationResultFlags.Expandable | DkmEvaluationResultFlags.ReadOnly, DkmEvaluationResultCategory.Data)); Verify(GetChildren(children[0]), EvalResult("PA", "1", "int", "A.PA", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[1]), EvalResult("FA", "2", "int", "((A)o.FA).FA")); Verify(GetChildren(children[2]), EvalResult("FB", "4", "int", "B.FB")); Verify(GetChildren(children[3]), EvalResult("PB", "3", "int", "((B)o.PB).PB", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[4]), EvalResult("PC", "5", "int", "C.PC", DkmEvaluationResultFlags.ReadOnly)); Verify(GetChildren(children[5]), EvalResult("FC", "6", "int", "o.FC")); } [Fact] public void ConstructedGenericType() { var source = @" using System.Diagnostics; public class C<T> { public T X; [DebuggerBrowsable(DebuggerBrowsableState.Never)] public T Y; } "; var assembly = GetAssembly(source); var type = assembly.GetType("C`1").MakeGenericType(typeof(int)); var value = CreateDkmClrValue( value: type.Instantiate(), type: type, evalFlags: DkmEvaluationResultFlags.None); var evalResult = FormatResult("o", value); Verify(evalResult, EvalResult("o", "{C<int>}", "C<int>", "o", DkmEvaluationResultFlags.Expandable)); Verify(GetChildren(evalResult), EvalResult("X", "0", "int", "o.X")); } } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Android.Accounts; using Android.App; using Android.Content; using Java.IO; namespace Microsoft.IdentityModel.Clients.ActiveDirectory { [Android.Runtime.Preserve(AllMembers = true)] class BrokerHelper : IBrokerHelper { private static SemaphoreSlim readyForResponse = null; private static AuthenticationResultEx resultEx = null; private BrokerProxy mBrokerProxy = new BrokerProxy(Application.Context); public IPlatformParameters PlatformParameters { get; set; } private bool WillUseBroker() { PlatformParameters pp = PlatformParameters as PlatformParameters; if (pp != null) { return pp.UseBroker; } return false; } public bool CanInvokeBroker { get { return WillUseBroker() && mBrokerProxy.CanSwitchToBroker(); } } public async Task<AuthenticationResultEx> AcquireTokenUsingBroker(IDictionary<string, string> brokerPayload) { resultEx = null; readyForResponse = new SemaphoreSlim(0); try { await Task.Run(() => AcquireToken(brokerPayload)).ConfigureAwait(false); } catch (Exception exc) { PlatformPlugin.Logger.Error(null, exc); throw; } await readyForResponse.WaitAsync().ConfigureAwait(false); return resultEx; } public void AcquireToken(IDictionary<string, string> brokerPayload) { if (brokerPayload.ContainsKey("broker_install_url")) { string url = brokerPayload["broker_install_url"]; Uri uri = new Uri(url); string query = uri.Query; if (query.StartsWith("?")) { query = query.Substring(1); } Dictionary<string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null); PlatformParameters pp = PlatformParameters as PlatformParameters; pp.CallerActivity.StartActivity(new Intent(Intent.ActionView, Android.Net.Uri.Parse(keyPair["app_link"]))); throw new AdalException(AdalErrorAndroidEx.BrokerApplicationRequired, AdalErrorMessageAndroidEx.BrokerApplicationRequired); } Context mContext = Application.Context; AuthenticationRequest request = new AuthenticationRequest(brokerPayload); PlatformParameters platformParams = PlatformParameters as PlatformParameters; // BROKER flow intercepts here // cache and refresh call happens through the authenticator service if (mBrokerProxy.VerifyUser(request.LoginHint, request.UserId)) { PlatformPlugin.Logger.Verbose(null, "It switched to broker for context: " + mContext.PackageName); request.BrokerAccountName = request.LoginHint; // Don't send background request, if prompt flag is always or // refresh_session if (!string.IsNullOrEmpty(request.BrokerAccountName) || !string.IsNullOrEmpty(request.UserId)) { PlatformPlugin.Logger.Verbose(null, "User is specified for background token request"); resultEx = mBrokerProxy.GetAuthTokenInBackground(request, platformParams.CallerActivity); } else { PlatformPlugin.Logger.Verbose(null, "User is not specified for background token request"); } if (resultEx != null && resultEx.Result != null && !string.IsNullOrEmpty(resultEx.Result.AccessToken)) { PlatformPlugin.Logger.Verbose(null, "Token is returned from background call "); readyForResponse.Release(); return; } // Launch broker activity // if cache and refresh request is not handled. // Initial request to authenticator needs to launch activity to // record calling uid for the account. This happens for Prompt auto // or always behavior. PlatformPlugin.Logger.Verbose(null, "Token is not returned from backgroud call"); // Only happens with callback since silent call does not show UI PlatformPlugin.Logger.Verbose(null, "Launch activity for Authenticator"); PlatformPlugin.Logger.Verbose(null, "Starting Authentication Activity"); if (resultEx == null) { PlatformPlugin.Logger.Verbose(null, "Initial request to authenticator"); // Log the initial request but not force a prompt } if (brokerPayload.ContainsKey("silent_broker_flow")) { throw new AdalSilentTokenAcquisitionException(); } // onActivityResult will receive the response // Activity needs to launch to record calling app for this // account Intent brokerIntent = mBrokerProxy.GetIntentForBrokerActivity(request, platformParams.CallerActivity); if (brokerIntent != null) { try { PlatformPlugin.Logger.Verbose(null, "Calling activity pid:" + Android.OS.Process.MyPid() + " tid:" + Android.OS.Process.MyTid() + "uid:" + Android.OS.Process.MyUid()); platformParams.CallerActivity.StartActivityForResult(brokerIntent, 1001); } catch (ActivityNotFoundException e) { PlatformPlugin.Logger.Error(null, e); } } } else { throw new AdalException(AdalErrorAndroidEx.NoBrokerAccountFound, "Add requested account as a Workplace account via Settings->Accounts or set UseBroker=true."); } } internal static void SetBrokerResult(Intent data, int resultCode) { if (resultCode != BrokerResponseCode.ResponseReceived) { resultEx = new AuthenticationResultEx { Exception = new AdalException(data.GetStringExtra(BrokerConstants.ResponseErrorCode), data.GetStringExtra(BrokerConstants.ResponseErrorMessage)) }; } else { string accessToken = data.GetStringExtra(BrokerConstants.AccountAccessToken); DateTimeOffset expiresOn = BrokerProxy.ConvertFromTimeT(data.GetLongExtra(BrokerConstants.AccountExpireDate, 0)); UserInfo userInfo = BrokerProxy.GetUserInfoFromBrokerResult(data.Extras); resultEx = new AuthenticationResultEx { Result = new AuthenticationResult("Bearer", accessToken, expiresOn) { UserInfo = userInfo } }; } readyForResponse.Release(); } } internal class CallBackHandler : Java.Lang.Object, IAccountManagerCallback { public void Run(IAccountManagerFuture future) { } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Security.Cryptography.X509Certificates; using System.Xml; using ConfigDataInfo; using IaasCmdletInfo; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Management.Utilities.Common; using Model; using PaasCmdletInfo; using WindowsAzure.ServiceManagement; using Microsoft.WindowsAzure.Storage.Blob; public class ServiceManagementCmdletTestHelper { /// <summary> /// Run a powershell cmdlet that returns the first PSObject as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private T RunPSCmdletAndReturnFirst<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); if (result.Count == 1) { return (T) result[0].BaseObject; } return default(T); } /// <summary> /// Run a powershell cmdlet that returns a collection of PSObjects as a return value. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cmdlet"></param> /// <returns></returns> private Collection<T> RunPSCmdletAndReturnAll<T>(PowershellCore.CmdletsInfo cmdlet) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(cmdlet); Collection<PSObject> result = azurePowershellCmdlet.Run(); Collection<T> resultCollection = new Collection<T>(); foreach (PSObject re in result) { resultCollection.Add((T)re.BaseObject); } return resultCollection; } public Collection <PSObject> RunPSScript(string script) { List<string> st = new List<string>(); st.Add(script); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return azurePowershellCmdlet.Run(); } public CopyState CheckCopyBlobStatus(string destContainer, string destBlob) { List<string> st = new List<string>(); st.Add(string.Format("Get-AzureStorageBlobCopyState -Container {0} -Blob {1}", destContainer, destBlob)); WindowsAzurePowershellScript azurePowershellCmdlet = new WindowsAzurePowershellScript(st); return (CopyState)azurePowershellCmdlet.Run()[0].BaseObject; } public bool TestAzureServiceName(string serviceName) { return RunPSCmdletAndReturnFirst<bool>(new TestAzureNameCmdletInfo("Service", serviceName)); } public Collection<LocationsContext> GetAzureLocation() { return RunPSCmdletAndReturnAll<LocationsContext>(new GetAzureLocationCmdletInfo()); } public string GetAzureLocationName(string[] keywords) { Collection<LocationsContext> locations = GetAzureLocation(); if (keywords != null) { foreach (LocationsContext location in locations) { if (MatchExactWords(location.Name, keywords) >= 0) { return location.Name; } } } else { if (locations.Count == 1) { return locations[0].Name; } } return null; } private static int MatchExactWords(string input, string[] keywords) { //returns -1 for no match, 0 for exact match, and a positive number for how many keywords are matched. int result = 0; if (string.IsNullOrEmpty(input) || keywords.Length == 0) return -1; foreach (string keyword in keywords) { //For whole word match, modify pattern to be "\b{0}\b" if (!string.IsNullOrEmpty(keyword) && keyword.ToLowerInvariant().Equals(input.ToLowerInvariant())) { result++; } } if (result == keywords.Length) { return 0; } else if (result == 0) { return -1; } else { return result; } } public Collection<OSVersionsContext> GetAzureOSVersion() { return RunPSCmdletAndReturnAll<OSVersionsContext>(new GetAzureOSVersionCmdletInfo()); } #region CertificateSetting, VMConifig, ProvisioningConfig public CertificateSetting NewAzureCertificateSetting(string store, string thumbprint) { return RunPSCmdletAndReturnFirst<CertificateSetting>(new NewAzureCertificateSettingCmdletInfo(store, thumbprint)); } public PersistentVM NewAzureVMConfig(AzureVMConfigInfo vmConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new NewAzureVMConfigCmdletInfo(vmConfig)); } public PersistentVM AddAzureProvisioningConfig(AzureProvisioningConfigInfo provConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureProvisioningConfigCmdletInfo(provConfig)); } #endregion #region AzureAffinityGroup public ManagementOperationContext NewAzureAffinityGroup(string name, string location, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new NewAzureAffinityGroupCmdletInfo(name, location, label, description)); } public Collection<AffinityGroupContext> GetAzureAffinityGroup(string name) { return RunPSCmdletAndReturnAll<AffinityGroupContext>(new GetAzureAffinityGroupCmdletInfo(name)); } public ManagementOperationContext SetAzureAffinityGroup(string name, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext> (new SetAzureAffinityGroupCmdletInfo(name, label, description)); } public ManagementOperationContext RemoveAzureAffinityGroup(string name) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureAffinityGroupCmdletInfo(name)); } #endregion #region AzureAvailabilitySet public PersistentVM SetAzureAvailabilitySet(string vmName, string serviceName, string availabilitySetName) { if (!string.IsNullOrEmpty(availabilitySetName)) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureAvailabilitySetCmdletInfo(availabilitySetName, vm)); } else { return null; } } #endregion AzureAvailabilitySet #region AzureCertificate public ManagementOperationContext AddAzureCertificate(string serviceName, PSObject cert, string password = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new AddAzureCertificateCmdletInfo(serviceName, cert, password)); } public Collection <CertificateContext> GetAzureCertificate(string serviceName, string thumbprint = null, string algorithm = null) { return RunPSCmdletAndReturnAll<CertificateContext> (new GetAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } public ManagementOperationContext RemoveAzureCertificate(string serviceName, string thumbprint, string algorithm) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureCertificateCmdletInfo(serviceName, thumbprint, algorithm)); } #endregion #region AzureDataDisk public PersistentVM AddAzureDataDisk(AddAzureDataDiskConfig diskConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureDataDiskCmdletInfo(diskConfig)); } public void AddDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig [] diskConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AddAzureDataDiskConfig config in diskConfigs) { config.Vm = vm; vm = AddAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } public PersistentVM SetAzureDataDisk(SetAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureDataDiskCmdletInfo(discCfg)); } public void SetDataDisk(string vmName, string serviceName, HostCaching hc, int lun) { SetAzureDataDiskConfig config = new SetAzureDataDiskConfig(hc, lun); config.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureDataDisk(config)); } public Collection<DataVirtualHardDisk> GetAzureDataDisk(string vmName, string serviceName) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); return RunPSCmdletAndReturnAll<DataVirtualHardDisk>(new GetAzureDataDiskCmdletInfo(vmRolectx.VM)); } private PersistentVM RemoveAzureDataDisk(RemoveAzureDataDiskConfig discCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new RemoveAzureDataDiskCmdletInfo(discCfg)); } public void RemoveDataDisk(string vmName, string serviceName, int [] lunSlots) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (int lun in lunSlots) { RemoveAzureDataDiskConfig config = new RemoveAzureDataDiskConfig(lun, vm); RemoveAzureDataDisk(config); } UpdateAzureVM(vmName, serviceName, vm); } #endregion #region AzureDeployment public ManagementOperationContext NewAzureDeployment(string serviceName, string packagePath, string configPath, string slot, string label, string name, bool doNotStart, bool warning, ExtensionConfigurationInput config = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureDeploymentCmdletInfo(serviceName, packagePath, configPath, slot, label, name, doNotStart, warning, config)); } public DeploymentInfoContext GetAzureDeployment(string serviceName, string slot) { return RunPSCmdletAndReturnFirst<DeploymentInfoContext>(new GetAzureDeploymentCmdletInfo(serviceName, slot)); } public DeploymentInfoContext GetAzureDeployment(string serviceName) { return GetAzureDeployment(serviceName, DeploymentSlotType.Production); } private ManagementOperationContext SetAzureDeployment(SetAzureDeploymentCmdletInfo cmdletInfo) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(cmdletInfo); } public ManagementOperationContext SetAzureDeploymentStatus(string serviceName, string slot, string newStatus) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentStatusCmdletInfo(serviceName, slot, newStatus)); } public ManagementOperationContext SetAzureDeploymentConfig(string serviceName, string slot, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentConfigCmdletInfo(serviceName, slot, configPath)); } public ManagementOperationContext SetAzureDeploymentUpgrade(string serviceName, string slot, string mode, string packagePath, string configPath) { return SetAzureDeployment(SetAzureDeploymentCmdletInfo.SetAzureDeploymentUpgradeCmdletInfo(serviceName, slot, mode, packagePath, configPath)); } public ManagementOperationContext SetAzureDeployment(string option, string serviceName, string packagePath, string newStatus, string configName, string slot, string mode, string label, string roleName, bool force) { return SetAzureDeployment(new SetAzureDeploymentCmdletInfo(option, serviceName, packagePath, newStatus, configName, slot, mode, label, roleName, force)); } public ManagementOperationContext RemoveAzureDeployment(string serviceName, string slot, bool force) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDeploymentCmdletInfo(serviceName, slot, force)); } public ManagementOperationContext MoveAzureDeployment(string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new MoveAzureDeploymentCmdletInfo(serviceName)); } public ManagementOperationContext SetAzureWalkUpgradeDomain(string serviceName, string slot, int domainNumber) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureWalkUpgradeDomainCmdletInfo(serviceName, slot, domainNumber)); } #endregion #region AzureDisk // Add-AzureDisk public DiskContext AddAzureDisk(string diskName, string mediaPath, string label, string os) { return RunPSCmdletAndReturnFirst<DiskContext>(new AddAzureDiskCmdletInfo(diskName, mediaPath, label, os)); } // Get-AzureDisk public Collection<DiskContext> GetAzureDisk(string diskName) { return GetAzureDisk(new GetAzureDiskCmdletInfo(diskName)); } public Collection<DiskContext> GetAzureDisk() { return GetAzureDisk(new GetAzureDiskCmdletInfo((string)null)); } private Collection<DiskContext> GetAzureDisk(GetAzureDiskCmdletInfo getAzureDiskCmdletInfo) { return RunPSCmdletAndReturnAll<DiskContext>(getAzureDiskCmdletInfo); } public Collection<DiskContext> GetAzureDiskAttachedToRoleName(string[] roleName, bool exactMatch = true) { Collection<DiskContext> retDisks = new Collection<DiskContext>(); Collection<DiskContext> disks = GetAzureDisk(); foreach (DiskContext disk in disks) { if (disk.AttachedTo != null && disk.AttachedTo.RoleName != null) { if (Utilities.MatchKeywords(disk.AttachedTo.RoleName, roleName, exactMatch) >= 0) retDisks.Add(disk); } } return retDisks; } // Remove-AzureDisk public ManagementOperationContext RemoveAzureDisk(string diskName, bool deleteVhd) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureDiskCmdletInfo(diskName, deleteVhd)); } // Update-AzureDisk public DiskContext UpdateAzureDisk(string diskName, string label) { return RunPSCmdletAndReturnFirst<DiskContext>(new UpdateAzureDiskCmdletInfo(diskName, label)); } #endregion #region AzureDns public DnsServer NewAzureDns(string name, string ipAddress) { return RunPSCmdletAndReturnFirst<DnsServer>(new NewAzureDnsCmdletInfo(name, ipAddress)); } public DnsServerList GetAzureDns(DnsSettings settings) { GetAzureDnsCmdletInfo getAzureDnsCmdletInfo = new GetAzureDnsCmdletInfo(settings); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureDnsCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); DnsServerList dnsList = new DnsServerList(); foreach (PSObject re in result) { dnsList.Add((DnsServer)re.BaseObject); } return dnsList; } #endregion #region AzureEndpoint public PersistentVM AddAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new AddAzureEndpointCmdletInfo(endPointConfig)); } public void AddEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo [] endPointConfigs) { PersistentVM vm = GetAzureVM(vmName, serviceName).VM; foreach (AzureEndPointConfigInfo config in endPointConfigs) { config.Vm = vm; vm = AddAzureEndPoint(config); } UpdateAzureVM(vmName, serviceName, vm); } public Collection <InputEndpointContext> GetAzureEndPoint(PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnAll<InputEndpointContext>(new GetAzureEndpointCmdletInfo(vmRoleCtxt)); } public void SetEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; UpdateAzureVM(vmName, serviceName, SetAzureEndPoint(endPointConfig)); } public PersistentVM SetAzureEndPoint(AzureEndPointConfigInfo endPointConfig) { if (null != endPointConfig) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureEndpointCmdletInfo(endPointConfig)); } return null; } public void SetLBEndPoint(string vmName, string serviceName, AzureEndPointConfigInfo endPointConfig, AzureEndPointConfigInfo.ParameterSet paramset) { endPointConfig.Vm = GetAzureVM(vmName, serviceName).VM; SetAzureLoadBalancedEndPoint(endPointConfig, paramset); //UpdateAzureVM(vmName, serviceName, SetAzureLoadBalancedEndPoint(endPointConfig, paramset)); } private ManagementOperationContext SetAzureLoadBalancedEndPoint(AzureEndPointConfigInfo endPointConfig, AzureEndPointConfigInfo.ParameterSet paramset) { if (null != endPointConfig) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureLoadBalancedEndpointCmdletInfo(endPointConfig, paramset)); } return null; } public PersistentVMRoleContext RemoveAzureEndPoint(string epName, PersistentVMRoleContext vmRoleCtxt) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new RemoveAzureEndpointCmdletInfo(epName, vmRoleCtxt)); } public void RemoveEndPoint(string vmName, string serviceName, string [] epNames) { PersistentVMRoleContext vmRoleCtxt = GetAzureVM(vmName, serviceName); foreach (string ep in epNames) { vmRoleCtxt.VM = RemoveAzureEndPoint(ep, vmRoleCtxt).VM; } UpdateAzureVM(vmName, serviceName, vmRoleCtxt.VM); } #endregion #region AzureOSDisk public PersistentVM SetAzureOSDisk(HostCaching hc, PersistentVM vm) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureOSDiskCmdletInfo(hc, vm)); } public OSVirtualHardDisk GetAzureOSDisk(PersistentVM vm) { return RunPSCmdletAndReturnFirst<OSVirtualHardDisk>(new GetAzureOSDiskCmdletInfo(vm)); } #endregion #region AzureRole public ManagementOperationContext SetAzureRole(string serviceName, string slot, string roleName, int count) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureRoleCmdletInfo(serviceName, slot, roleName, count)); } public Collection<RoleContext> GetAzureRole(string serviceName, string slot, string roleName, bool details) { return RunPSCmdletAndReturnAll<RoleContext>(new GetAzureRoleCmdletInfo(serviceName, slot, roleName, details)); } #endregion #region AzureQuickVM public PersistentVMRoleContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName, InstanceSize? instanceSize) { NewAzureQuickVMCmdletInfo newAzureQuickVMCmdlet = new NewAzureQuickVMCmdletInfo(os, name, serviceName, imageName, userName, password, locationName, instanceSize); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(newAzureQuickVMCmdlet); SubscriptionData currentSubscription; if ((currentSubscription = GetCurrentAzureSubscription()) == null) { ImportAzurePublishSettingsFile(); currentSubscription = GetCurrentAzureSubscription(); } if (string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { StorageServicePropertiesOperationContext storageAccount = NewAzureStorageAccount(Utilities.GetUniqueShortName("storage"), locationName); if (storageAccount != null) { SetAzureSubscription(currentSubscription.SubscriptionName, storageAccount.StorageAccountName); currentSubscription = GetCurrentAzureSubscription(); } } if (!string.IsNullOrEmpty(currentSubscription.CurrentStorageAccount)) { azurePowershellCmdlet.Run(); return GetAzureVM(name, serviceName); } return null; } public PersistentVMRoleContext NewAzureQuickVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName) { return NewAzureQuickVM(os, name, serviceName, imageName, userName, password, locationName, null); } public PersistentVMRoleContext NewAzureQuickLinuxVM(OS os, string name, string serviceName, string imageName, string userName, string password, string locationName) { return NewAzureQuickVM(os, name, serviceName, imageName, userName, password, locationName); } #endregion #region AzurePublishSettingsFile internal void ImportAzurePublishSettingsFile() { this.ImportAzurePublishSettingsFile(CredentialHelper.PublishSettingsFile); } internal void ImportAzurePublishSettingsFile(string publishSettingsFile) { ImportAzurePublishSettingsFileCmdletInfo importAzurePublishSettingsFileCmdlet = new ImportAzurePublishSettingsFileCmdletInfo(publishSettingsFile); WindowsAzurePowershellCmdlet importAzurePublishSettingsFile = new WindowsAzurePowershellCmdlet(importAzurePublishSettingsFileCmdlet); var i = importAzurePublishSettingsFile.Run(); Console.WriteLine(i.ToString()); } #endregion #region AzureSubscription public Collection<SubscriptionData> GetAzureSubscription() { return RunPSCmdletAndReturnAll<SubscriptionData>(new GetAzureSubscriptionCmdletInfo()); } public SubscriptionData GetCurrentAzureSubscription() { Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.IsDefault) { return subscription; } } return null; } public SubscriptionData SetAzureSubscription(string subscriptionName, string currentStorageAccount) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName, currentStorageAccount); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } public SubscriptionData SetDefaultAzureSubscription(string subscriptionName) { SetAzureSubscriptionCmdletInfo setAzureSubscriptionCmdlet = new SetAzureSubscriptionCmdletInfo(subscriptionName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(setAzureSubscriptionCmdlet); azurePowershellCmdlet.Run(); Collection<SubscriptionData> subscriptions = GetAzureSubscription(); foreach (SubscriptionData subscription in subscriptions) { if (subscription.SubscriptionName == subscriptionName) { return subscription; } } return null; } #endregion #region AzureSubnet public SubnetNamesCollection GetAzureSubnet(PersistentVM vm) { GetAzureSubnetCmdletInfo getAzureSubnetCmdlet = new GetAzureSubnetCmdletInfo(vm); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(getAzureSubnetCmdlet); Collection <PSObject> result = azurePowershellCmdlet.Run(); SubnetNamesCollection subnets = new SubnetNamesCollection(); foreach (PSObject re in result) { subnets.Add((string)re.BaseObject); } return subnets; } public PersistentVM SetAzureSubnet(PersistentVM vm, string [] subnetNames) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureSubnetCmdletInfo(vm, subnetNames)); } #endregion #region AzureStorageAccount public ManagementOperationContext NewAzureStorageAccount(string storageName, string locationName, string affinity, string label, string description) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureStorageAccountCmdletInfo(storageName, locationName, affinity, label, description)); } public StorageServicePropertiesOperationContext NewAzureStorageAccount(string storageName, string locationName) { NewAzureStorageAccount(storageName, locationName, null, null, null); Collection<StorageServicePropertiesOperationContext> storageAccounts = GetAzureStorageAccount(null); foreach (StorageServicePropertiesOperationContext storageAccount in storageAccounts) { if (storageAccount.StorageAccountName == storageName) return storageAccount; } return null; } public Collection<StorageServicePropertiesOperationContext> GetAzureStorageAccount(string accountName) { return RunPSCmdletAndReturnAll<StorageServicePropertiesOperationContext>(new GetAzureStorageAccountCmdletInfo(accountName)); } public ManagementOperationContext SetAzureStorageAccount(string accountName, string label, string description, bool? geoReplication) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureStorageAccountCmdletInfo(accountName, label, description, geoReplication)); } public void RemoveAzureStorageAccount(string storageAccountName) { var removeAzureStorageAccountCmdletInfo = new RemoveAzureStorageAccountCmdletInfo(storageAccountName); var azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(removeAzureStorageAccountCmdletInfo); Collection<PSObject> result = azurePowershellCmdlet.Run(); } #endregion #region AzureStorageKey public StorageServiceKeyOperationContext GetAzureStorageAccountKey(string stroageAccountName) { return RunPSCmdletAndReturnFirst<StorageServiceKeyOperationContext>(new GetAzureStorageKeyCmdletInfo(stroageAccountName)); } public StorageServiceKeyOperationContext NewAzureStorageAccountKey(string stroageAccountName, string keyType) { return RunPSCmdletAndReturnFirst<StorageServiceKeyOperationContext>(new NewAzureStorageKeyCmdletInfo(stroageAccountName, keyType)); } #endregion #region AzureService public ManagementOperationContext NewAzureService(string serviceName, string location) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureServiceCmdletInfo(serviceName, location)); } internal void NewAzureService(string serviceName, string serviceLabel, string locationName) { NewAzureServiceCmdletInfo newAzureServiceCmdletInfo = new NewAzureServiceCmdletInfo(serviceName, serviceLabel, locationName); WindowsAzurePowershellCmdlet newAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(newAzureServiceCmdletInfo); Collection<PSObject> result = newAzureServiceCmdlet.Run(); } public void RemoveAzureService(string serviceName) { RemoveAzureServiceCmdletInfo removeAzureServiceCmdletInfo = new RemoveAzureServiceCmdletInfo(serviceName); WindowsAzurePowershellCmdlet removeAzureServiceCmdlet = new WindowsAzurePowershellCmdlet(removeAzureServiceCmdletInfo); var result = removeAzureServiceCmdlet.Run(); } public HostedServiceDetailedContext GetAzureService(string serviceName) { return RunPSCmdletAndReturnFirst<HostedServiceDetailedContext>(new GetAzureServiceCmdletInfo(serviceName)); } #endregion #region AzureServiceDiagnosticsExtension // New-AzureServiceDiagnosticsExtensionConfig public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig(string storage, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, config, roles)); } public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig (string storage, X509Certificate2 cert, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput> (new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, cert, config, roles)); } public ExtensionConfigurationInput NewAzureServiceDiagnosticsExtensionConfig (string storage, string thumbprint, string algorithm = null, XmlDocument config = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput> (new NewAzureServiceDiagnosticsExtensionConfigCmdletInfo(storage, thumbprint, algorithm, config, roles)); } // Set-AzureServiceDiagnosticsExtension public ManagementOperationContext SetAzureServiceDiagnosticsExtension (string service, string storage, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, config, roles, slot)); } public ManagementOperationContext SetAzureServiceDiagnosticsExtension(string service, string storage, X509Certificate2 cert, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, cert, config, roles, slot)); } public ManagementOperationContext SetAzureServiceDiagnosticsExtension(string service, string storage, string thumbprint, string algorithm = null, XmlDocument config = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceDiagnosticsExtensionCmdletInfo(service, storage, thumbprint, algorithm, config, roles, slot)); } // Get-AzureServiceDiagnosticsExtension public Collection <DiagnosticExtensionContext> GetAzureServiceDiagnosticsExtension(string serviceName, string slot = null) { return RunPSCmdletAndReturnAll<DiagnosticExtensionContext>(new GetAzureServiceDiagnosticsExtensionCmdletInfo(serviceName, slot)); } // Remove-AzureServiceDiagnosticsExtension public ManagementOperationContext RemoveAzureServiceDiagnosticsExtension(string serviceName, bool uninstall = false, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureServiceDiagnosticsExtensionCmdletInfo(serviceName, uninstall, roles, slot)); } #endregion #region AzureServiceRemoteDesktopExtension // New-AzureServiceRemoteDesktopExtensionConfig public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, exp, roles)); } public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, X509Certificate2 cert, string alg = null, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, cert, alg, exp, roles)); } public ExtensionConfigurationInput NewAzureServiceRemoteDesktopExtensionConfig(PSCredential cred, string thumbprint, string algorithm = null, DateTime? exp = null, string[] roles = null) { return RunPSCmdletAndReturnFirst<ExtensionConfigurationInput>(new NewAzureServiceRemoteDesktopExtensionConfigCmdletInfo(cred, thumbprint, algorithm, exp, roles)); } // Set-AzureServiceRemoteDesktopExtension public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential cred, DateTime? exp = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, cred, exp, roles, slot)); } public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential credential, X509Certificate2 cert, DateTime? expiration = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, credential, cert, expiration, roles, slot)); } public ManagementOperationContext SetAzureServiceRemoteDesktopExtension(string serviceName, PSCredential credential, string thumbprint, string algorithm = null, DateTime? expiration = null, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, credential, thumbprint, algorithm, expiration, roles, slot)); } // Get-AzureServiceRemoteDesktopExtension public Collection <RemoteDesktopExtensionContext> GetAzureServiceRemoteDesktopExtension(string serviceName, string slot = null) //public RemoteDesktopExtensionContext GetAzureServiceRemoteDesktopExtension(string serviceName, string slot = null) { return RunPSCmdletAndReturnAll<RemoteDesktopExtensionContext>(new GetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, slot)); //return RunPSCmdletAndReturnFirst<RemoteDesktopExtensionContext>(new GetAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, slot)); } // Remove-AzureServiceRemoteDesktopExtension public ManagementOperationContext RemoveAzureServiceRemoteDesktopExtension(string serviceName, bool uninstall = false, string[] roles = null, string slot = null) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureServiceRemoteDesktopExtensionCmdletInfo(serviceName, uninstall, roles, slot)); } #endregion #region AzureVM internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] VMs) { return NewAzureVM(serviceName, VMs, null, null, null, null, null, null, null, null); } internal Collection<ManagementOperationContext> NewAzureVM(string serviceName, PersistentVM[] vms, string vnetName, DnsServer[] dnsSettings, string affinityGroup, string serviceLabel, string serviceDescription, string deploymentLabel, string deploymentDescription, string location) { return RunPSCmdletAndReturnAll<ManagementOperationContext>( new NewAzureVMCmdletInfo(serviceName, vms, vnetName, dnsSettings, affinityGroup, serviceLabel, serviceDescription, deploymentLabel, deploymentDescription, location)); } public PersistentVMRoleContext GetAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new GetAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext RemoveAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext StartAzureVM(string vmName, string serviceName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StartAzureVMCmdletInfo(vmName, serviceName)); } public ManagementOperationContext StopAzureVM(PersistentVM vm, string serviceName, bool stay = false, bool force = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StopAzureVMCmdletInfo(vm, serviceName, stay, force)); } public ManagementOperationContext StopAzureVM(string vmName, string serviceName, bool stay = false, bool force = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new StopAzureVMCmdletInfo(vmName, serviceName, stay, force)); } public void RestartAzureVM(string vmName, string serviceName) { RestartAzureVMCmdletInfo restartAzureVMCmdlet = new RestartAzureVMCmdletInfo(vmName, serviceName); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(restartAzureVMCmdlet); azurePowershellCmdlet.Run(); } public PersistentVMRoleContext ExportAzureVM(string vmName, string serviceName, string path) { return RunPSCmdletAndReturnFirst<PersistentVMRoleContext>(new ExportAzureVMCmdletInfo(vmName, serviceName, path)); } public Collection<PersistentVM> ImportAzureVM(string path) { return RunPSCmdletAndReturnAll<PersistentVM>(new ImportAzureVMCmdletInfo(path)); } public ManagementOperationContext UpdateAzureVM(string vmName, string serviceName, PersistentVM persistentVM) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new UpdateAzureVMCmdletInfo(vmName, serviceName, persistentVM)); } #endregion #region AzureVMImage public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, string label = null) { return RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, label)); } public OSImageContext AddAzureVMImage(string imageName, string mediaLocation, OS os, InstanceSize recommendedSize) { return RunPSCmdletAndReturnFirst<OSImageContext>(new AddAzureVMImageCmdletInfo(imageName, mediaLocation, os, null, recommendedSize)); } public OSImageContext UpdateAzureVMImage(string imageName, string label) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, label)); } public OSImageContext UpdateAzureVMImage(string imageName, InstanceSize recommendedSize) { return RunPSCmdletAndReturnFirst<OSImageContext>(new UpdateAzureVMImageCmdletInfo(imageName, null, recommendedSize)); } public ManagementOperationContext RemoveAzureVMImage(string imageName, bool deleteVhd = false) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVMImageCmdletInfo(imageName, deleteVhd)); } public void SaveAzureVMImage(string serviceName, string vmName, string newVmName, string newImageName = null) { RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SaveAzureVMImageCmdletInfo(serviceName, vmName, newVmName, newImageName)); } public Collection<OSImageContext> GetAzureVMImage(string imageName = null) { return RunPSCmdletAndReturnAll<OSImageContext>(new GetAzureVMImageCmdletInfo(imageName)); } public string GetAzureVMImageName(string[] keywords, bool exactMatch = true) { Collection<OSImageContext> vmImages = GetAzureVMImage(); foreach (OSImageContext image in vmImages) { if (Utilities.MatchKeywords(image.ImageName, keywords, exactMatch) >= 0) return image.ImageName; } return null; } #endregion #region AzureVhd public string AddAzureVhdStop(FileInfo localFile, string destination, int ms) { WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, null)); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, string baseImage) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, false, baseImage)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, bool overwrite) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, null, overwrite, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int numberOfUploaderThreads) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, false, null)); } public VhdUploadContext AddAzureVhd(FileInfo localFile, string destination, int? numberOfUploaderThreads, bool overWrite) { return RunPSCmdletAndReturnFirst<VhdUploadContext>(new AddAzureVhdCmdletInfo(destination, localFile.FullName, numberOfUploaderThreads, overWrite, null)); } public VhdDownloadContext SaveAzureVhd(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite) { return RunPSCmdletAndReturnFirst<VhdDownloadContext>(new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite)); } public string SaveAzureVhdStop(Uri source, FileInfo localFilePath, int? numThreads, string storageKey, bool overwrite, int ms) { SaveAzureVhdCmdletInfo saveAzureVhdCmdletInfo = new SaveAzureVhdCmdletInfo(source, localFilePath, numThreads, storageKey, overwrite); WindowsAzurePowershellCmdlet azurePowershellCmdlet = new WindowsAzurePowershellCmdlet(saveAzureVhdCmdletInfo); return azurePowershellCmdlet.RunAndStop(ms).ToString(); } #endregion #region AzureVnetConfig public Collection<VirtualNetworkConfigContext> GetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnAll<VirtualNetworkConfigContext>(new GetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext SetAzureVNetConfig(string filePath) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetConfigCmdletInfo(filePath)); } public ManagementOperationContext RemoveAzureVNetConfig() { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetConfigCmdletInfo()); } #endregion #region AzureVNetGateway public ManagementOperationContext NewAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new NewAzureVNetGatewayCmdletInfo(vnetName)); } public Collection <VirtualNetworkGatewayContext> GetAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkGatewayContext>(new GetAzureVNetGatewayCmdletInfo(vnetName)); } public ManagementOperationContext SetAzureVNetGateway(string option, string vnetName, string localNetwork) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new SetAzureVNetGatewayCmdletInfo(option, vnetName, localNetwork)); } public ManagementOperationContext RemoveAzureVNetGateway(string vnetName) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new RemoveAzureVNetGatewayCmdletInfo(vnetName)); } public SharedKeyContext GetAzureVNetGatewayKey(string vnetName, string localnet) { return RunPSCmdletAndReturnFirst<SharedKeyContext>(new GetAzureVNetGatewayKeyCmdletInfo(vnetName, localnet)); } #endregion #region AzureVNet public Collection<GatewayConnectionContext> GetAzureVNetConnection(string vnetName) { return RunPSCmdletAndReturnAll<GatewayConnectionContext>(new GetAzureVNetConnectionCmdletInfo(vnetName)); } public Collection<VirtualNetworkSiteContext> GetAzureVNetSite(string vnetName) { return RunPSCmdletAndReturnAll<VirtualNetworkSiteContext>(new GetAzureVNetSiteCmdletInfo(vnetName)); } #endregion public ManagementOperationContext GetAzureRemoteDesktopFile(string vmName, string serviceName, string localPath, bool launch) { return RunPSCmdletAndReturnFirst<ManagementOperationContext>(new GetAzureRemoteDesktopFileCmdletInfo(vmName, serviceName, localPath, launch)); } internal PersistentVM GetPersistentVM(PersistentVMConfigInfo configInfo) { PersistentVM vm = null; if (null != configInfo) { if (configInfo.VmConfig != null) { vm = NewAzureVMConfig(configInfo.VmConfig); } if (configInfo.ProvConfig != null) { configInfo.ProvConfig.Vm = vm; vm = AddAzureProvisioningConfig(configInfo.ProvConfig); } if (configInfo.DiskConfig != null) { configInfo.DiskConfig.Vm = vm; vm = AddAzureDataDisk(configInfo.DiskConfig); } if (configInfo.EndPointConfig != null) { configInfo.EndPointConfig.Vm = vm; vm = AddAzureEndPoint(configInfo.EndPointConfig); } } return vm; } internal void AddVMDataDisks(string vmName, string serviceName, AddAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (AddAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = AddAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMDataDisks(string vmName, string serviceName, SetAzureDataDiskConfig[] diskConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); foreach (SetAzureDataDiskConfig discCfg in diskConfig) { discCfg.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureDataDisk(discCfg); } UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } internal void SetVMSize(string vmName, string serviceName, SetAzureVMSizeConfig vmSizeConfig) { PersistentVMRoleContext vmRolectx = GetAzureVM(vmName, serviceName); vmSizeConfig.Vm = vmRolectx.VM; vmRolectx.VM = SetAzureVMSize(vmSizeConfig); UpdateAzureVM(vmName, serviceName, vmRolectx.VM); } private PersistentVM SetAzureVMSize(SetAzureVMSizeConfig sizeCfg) { return RunPSCmdletAndReturnFirst<PersistentVM>(new SetAzureVMSizeCmdletInfo(sizeCfg)); } internal void AddVMDataDisksAndEndPoint(string vmName, string serviceName, AddAzureDataDiskConfig[] dataDiskConfig, AzureEndPointConfigInfo endPointConfig) { AddVMDataDisks(vmName, serviceName, dataDiskConfig); AddEndPoint(vmName, serviceName, new [] {endPointConfig}); } public void RemoveAzureSubscriptions() { // Remove all subscriptions. SAS Uri should work without a subscription. try { RunPSScript("Get-AzureSubscription | Remove-AzureSubscription -Force"); } catch { Console.WriteLine("Subscriptions cannot be removed"); } // Check if all subscriptions are removed. try { GetAzureSubscription(); Assert.Fail("Subscription was not removed!"); } catch (Exception e) { if (e is AssertFailedException) { throw; } } } public void RemoveAzureSubscription(string subscriptionName, bool force) { RemoveAzureSubscriptionCmdletInfo removeAzureSubscriptionCmdletInfo = new RemoveAzureSubscriptionCmdletInfo(subscriptionName, null, force); WindowsAzurePowershellCmdlet removeAzureSubscriptionCmdlet = new WindowsAzurePowershellCmdlet(removeAzureSubscriptionCmdletInfo); var result = removeAzureSubscriptionCmdlet.Run(); } internal NetworkAclObject NewAzureAclConfig() { return RunPSCmdletAndReturnFirst<NetworkAclObject>(new NewAzureAclConfigCmdletInfo()); } // Set-AzureAclConfig -AddRule -ACL $acl2 -Order 100 -Action Deny -RemoteSubnet "172.0.0.0/8" -Description "notes3" // vmPowershellCmdlets.SetAzureAclConfig(SetACLConfig.AddRule, aclObj, 100, ACLAction.Permit, "172.0.0.0//8", "Desc"); internal void SetAzureAclConfig(SetACLConfig aclConfig, NetworkAclObject aclObj, int order, ACLAction aclAction, string remoteSubnet, string desc) { SetAzureAclConfigCmdletInfo setAzureAclConfigCmdletInfo = new SetAzureAclConfigCmdletInfo(aclConfig.ToString(), aclObj, order, aclAction.ToString(), remoteSubnet, desc, null); WindowsAzurePowershellCmdlet setAzureAclConfigCmdlet = new WindowsAzurePowershellCmdlet(setAzureAclConfigCmdletInfo); var result = setAzureAclConfigCmdlet.Run(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Game.Audio; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osuTK; using osuTK.Graphics; namespace osu.Game.Overlays.Direct { public abstract class DirectPanel : Container { public readonly BeatmapSetInfo SetInfo; private const double hover_transition_time = 400; private const int maximum_difficulty_icons = 10; private Container content; private BeatmapSetOverlay beatmapSetOverlay; public PreviewTrack Preview => PlayButton.Preview; public Bindable<bool> PreviewPlaying => PlayButton?.Playing; protected abstract PlayButton PlayButton { get; } protected abstract Box PreviewBar { get; } protected virtual bool FadePlayButton => true; protected override Container<Drawable> Content => content; protected DirectPanel(BeatmapSetInfo setInfo) { Debug.Assert(setInfo.OnlineBeatmapSetID != null); SetInfo = setInfo; } private readonly EdgeEffectParameters edgeEffectNormal = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 1f), Radius = 2f, Colour = Color4.Black.Opacity(0.25f), }; private readonly EdgeEffectParameters edgeEffectHovered = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Offset = new Vector2(0f, 5f), Radius = 10f, Colour = Color4.Black.Opacity(0.3f), }; [BackgroundDependencyLoader(permitNulls: true)] private void load(BeatmapManager beatmaps, OsuColour colours, BeatmapSetOverlay beatmapSetOverlay) { this.beatmapSetOverlay = beatmapSetOverlay; AddInternal(content = new Container { RelativeSizeAxes = Axes.Both, Masking = true, EdgeEffect = edgeEffectNormal, Children = new[] { CreateBackground(), new DownloadProgressBar(SetInfo) { Anchor = Anchor.BottomLeft, Origin = Anchor.BottomLeft, Depth = -1, }, } }); } protected override void Update() { base.Update(); if (PreviewPlaying.Value && Preview != null && Preview.TrackLoaded) { PreviewBar.Width = (float)(Preview.CurrentTime / Preview.Length); } } protected override bool OnHover(HoverEvent e) { content.TweenEdgeEffectTo(edgeEffectHovered, hover_transition_time, Easing.OutQuint); content.MoveToY(-4, hover_transition_time, Easing.OutQuint); if (FadePlayButton) PlayButton.FadeIn(120, Easing.InOutQuint); return base.OnHover(e); } protected override void OnHoverLost(HoverLostEvent e) { content.TweenEdgeEffectTo(edgeEffectNormal, hover_transition_time, Easing.OutQuint); content.MoveToY(0, hover_transition_time, Easing.OutQuint); if (FadePlayButton && !PreviewPlaying.Value) PlayButton.FadeOut(120, Easing.InOutQuint); base.OnHoverLost(e); } protected override bool OnClick(ClickEvent e) { Debug.Assert(SetInfo.OnlineBeatmapSetID != null); beatmapSetOverlay?.FetchAndShowBeatmapSet(SetInfo.OnlineBeatmapSetID.Value); return true; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(200, Easing.Out); PreviewPlaying.ValueChanged += playing => { PlayButton.FadeTo(playing.NewValue || IsHovered || !FadePlayButton ? 1 : 0, 120, Easing.InOutQuint); PreviewBar.FadeTo(playing.NewValue ? 1 : 0, 120, Easing.InOutQuint); }; } protected List<DifficultyIcon> GetDifficultyIcons(OsuColour colours) { var icons = new List<DifficultyIcon>(); if (SetInfo.Beatmaps.Count > maximum_difficulty_icons) { foreach (var ruleset in SetInfo.Beatmaps.Select(b => b.Ruleset).Distinct()) icons.Add(new GroupedDifficultyIcon(SetInfo.Beatmaps.FindAll(b => b.Ruleset.Equals(ruleset)), ruleset, this is DirectListPanel ? Color4.White : colours.Gray5)); } else foreach (var b in SetInfo.Beatmaps.OrderBy(beatmap => beatmap.StarDifficulty)) icons.Add(new DifficultyIcon(b)); return icons; } protected Drawable CreateBackground() => new UpdateableBeatmapSetCover { RelativeSizeAxes = Axes.Both, BeatmapSet = SetInfo, }; public class Statistic : FillFlowContainer { private readonly SpriteText text; private int value; public int Value { get => value; set { this.value = value; text.Text = Value.ToString(@"N0"); } } public Statistic(IconUsage icon, int value = 0) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; AutoSizeAxes = Axes.Both; Direction = FillDirection.Horizontal; Spacing = new Vector2(5f, 0f); Children = new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.SemiBold, italics: true) }, new SpriteIcon { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, Icon = icon, Shadow = true, Size = new Vector2(14), }, }; Value = value; } } } }
/////////////////////////////////////////////////////////////////////////////////// // Open 3D Model Viewer (open3mod) (v2.0) // [MainWindow.cs] // (c) 2012-2015, Open3Mod Contributors // // Licensed under the terms and conditions of the 3-clause BSD license. See // the LICENSE file in the root folder of the repository for the details. // // HIS 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. /////////////////////////////////////////////////////////////////////////////////// #define USE_APP_IDLE using System; using System.Collections.Specialized; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Windows.Forms; using System.Threading; using OpenTK; #if LEAP using Leap; #endif namespace open3mod { public partial class MainWindow : Form { private readonly UiState _ui; private Renderer _renderer; private readonly FpsTracker _fps; private LogViewer _logViewer; private delegate void DelegateSelectTab(TabPage tab); private readonly DelegateSelectTab _delegateSelectTab; private delegate void DelegatePopulateInspector(Tab tab); private readonly DelegatePopulateInspector _delegatePopulateInspector; #if LEAP private readonly Controller _leapController; private readonly LeapListener _leapListener; #endif private readonly bool _initialized; #if !USE_APP_IDLE private System.Windows.Forms.Timer _timer; #endif public delegate void TabAddRemoveHandler (Tab tab, bool add); public event TabAddRemoveHandler TabChanged; public delegate void TabSelectionChangeHandler(Tab tab); public event TabSelectionChangeHandler SelectedTabChanged; public GLControl GlControl { get { return glControl1; } } public UiState UiState { get { return _ui; } } public FpsTracker Fps { get { return _fps; } } public Renderer Renderer { get { return _renderer; } } public const int MaxRecentItems = 12; public MainWindow() { // create delegate used for asynchronous calls _delegateSelectTab = SelectTab; _delegatePopulateInspector = PopulateInspector; InitializeComponent(); _captionStub = Text; AddEmptyTab(); // initialize UI state shelf with a default tab _ui = new UiState(new Tab(_emptyTab, null)); _fps = new FpsTracker(); // sync global UI with UIState framerateToolStripMenuItem.Checked = toolStripButtonShowFPS.Checked = _ui.ShowFps; lightingToolStripMenuItem.Checked = toolStripButtonShowShaded.Checked = _ui.RenderLit; texturedToolStripMenuItem.Checked = toolStripButtonShowTextures.Checked = _ui.RenderTextured; wireframeToolStripMenuItem.Checked = toolStripButtonWireframe.Checked = _ui.RenderWireframe; showNormalVectorsToolStripMenuItem.Checked = toolStripButtonShowNormals.Checked = _ui.ShowNormals; showBoundingBoxesToolStripMenuItem.Checked = toolStripButtonShowBB.Checked = _ui.ShowBBs; showAnimationSkeletonToolStripMenuItem.Checked = toolStripButtonShowSkeleton.Checked = _ui.ShowSkeleton; // manually register the MouseWheel handler glControl1.MouseWheel += OnMouseMove; // intercept all key events sent to children KeyPreview = true; InitRecentList(); #if LEAP //LeapMotion Support _leapListener = new LeapListener(this as MainWindow); _leapController = new Controller(_leapListener); #endif // register listener for tab changs tabControl1.SelectedIndexChanged += (object o, EventArgs e) => { if (SelectedTabChanged != null) { SelectedTabChanged(UiState.TabForId(tabControl1.SelectedTab)); } }; _initialized = true; StartUndoRedoUiStatePollLoop(); } public override sealed string Text { get { return base.Text; } set { base.Text = value; } } /// <summary> /// Add an "empty" tab if it doesn't exist yet /// </summary> private void AddEmptyTab() { // create default tab tabControl1.TabPages.Add("empty"); _emptyTab = tabControl1.TabPages[tabControl1.TabPages.Count-1]; PopulateUITab(_emptyTab); ActivateUiTab(_emptyTab); // happens when being called from ctor if (_ui != null) { _ui.AddTab(new Tab(_emptyTab, null)); } } protected override void OnCreateControl() { base.OnCreateControl(); DelayExecution(TimeSpan.FromSeconds(2), MaybeShowTipOfTheDay); DelayExecution(TimeSpan.FromSeconds(20), MaybeShowDonationDialog); } private static void MaybeShowTipOfTheDay() { if (CoreSettings.CoreSettings.Default.ShowTipsOnStartup) { var tip = new TipOfTheDayDialog(); tip.ShowDialog(); } } // http://stackoverflow.com/questions/2565166 public static void DelayExecution(TimeSpan delay, Action action) { SynchronizationContext context = SynchronizationContext.Current; System.Threading.Timer timer = null; timer = new System.Threading.Timer( (_) => { if (timer != null) { timer.Dispose(); } context.Post(__ => action(), null); }, null, delay, TimeSpan.FromMilliseconds(-1)); } /// <summary> /// Initial value for the donation countdown - every time the application is launched, /// a counter is decremented. Upon reaching 0, the user is asked to donate. /// </summary> private const int DonationCounterStart = 10; private static void MaybeShowDonationDialog() { // first time: init donation countdown if (CoreSettings.CoreSettings.Default.DonationUseCountDown == 0) { CoreSettings.CoreSettings.Default.DonationUseCountDown = DonationCounterStart; } // -1 means the countdown is disabled, otherwise the dialog is shown when 0 is reached if (CoreSettings.CoreSettings.Default.DonationUseCountDown != -1 && --CoreSettings.CoreSettings.Default.DonationUseCountDown == 0) { CoreSettings.CoreSettings.Default.DonationUseCountDown = DonationCounterStart; var don = new DonationDialog(); don.ShowDialog(); } } private void PopulateUITab(TabPage ui) { var tui = new TabUiSkeleton(); tui.Size = ui.ClientSize; tui.AutoSize = false; tui.Dock = DockStyle.Fill; ; ui.Controls.Add(tui); } private void ActivateUiTab(TabPage ui) { ((TabUiSkeleton)ui.Controls[0]).InjectGlControl(glControl1); if (_renderer != null) { _renderer.TextOverlay.Clear(); } // add postfix to main window title if (UiState != null) { var tab = UiState.TabForId(ui); if (tab != null) { if (!string.IsNullOrEmpty(tab.File)) { Text = _captionStub + " [" + tab.File + "]"; } else { Text = _captionStub; } } } } /// <summary> /// Open a new tab given a scene file to load. If the specified scene is /// already open in a tab, the existing /// tab is selected in the UI (if requested) and no tab is added. /// </summary> /// <param name="file">Source file</param> /// <param name="async">Specifies whether the data is loaded asynchr.</param> /// <param name="setActive">Specifies whether the newly added tab will /// be selected when the loading process is complete.</param> public void AddTab(string file, bool async = true, bool setActive = true) { AddRecentItem(file); // check whether the scene is already loaded for (int j = 0; j < tabControl1.TabPages.Count; ++j) { var tab = UiState.TabForId(tabControl1.TabPages[j]); Debug.Assert(tab != null); if(tab.File == file) { // if so, activate its tab and return if(setActive) { SelectTab(tabControl1.TabPages[j]); } return; } } var key = GenerateTabKey(); tabControl1.TabPages.Add(key, GenerateTabCaption(file) + LoadingTitlePostfix); var ui = tabControl1.TabPages[key]; ui.ToolTipText = file; tabControl1.ShowToolTips = true; PopulateUITab(ui); var t = new Tab(ui, file); UiState.AddTab(t); if (TabChanged != null) { TabChanged(t, true); } if (async) { var th = new Thread(() => OpenFile(t, setActive)); th.Start(); } else { OpenFile(t, setActive); } if (_emptyTab != null) { CloseTab(_emptyTab); } } /// <summary> /// Initially build the Recent-Files menu /// </summary> private void InitRecentList() { recentToolStripMenuItem.DropDownItems.Clear(); var v = CoreSettings.CoreSettings.Default.RecentFiles; if (v == null) { v = CoreSettings.CoreSettings.Default.RecentFiles = new StringCollection(); CoreSettings.CoreSettings.Default.Save(); } foreach (var s in v) { var tool = recentToolStripMenuItem.DropDownItems.Add(Path.GetFileName(s)); var path = s; tool.Click += (sender, args) => AddTab(path); } } /// <summary> /// Add a new item to the Recent-Files menu and save it persistently /// </summary> /// <param name="file"></param> private void AddRecentItem(string file) { var recent = CoreSettings.CoreSettings.Default.RecentFiles; bool removed = false; int i = 0; foreach (var s in recent) { if (s == file) { recentToolStripMenuItem.DropDownItems.RemoveAt(i); recent.Remove(s); removed = true; break; } ++i; } if (!removed && recent.Count == MaxRecentItems) { recent.RemoveAt(recent.Count - 1); } recent.Insert(0, file); CoreSettings.CoreSettings.Default.Save(); recentToolStripMenuItem.DropDownItems.Insert(0, new ToolStripMenuItem( Path.GetFileName(file), null, (sender, args) => AddTab(file))); } /// <summary> /// Generate a suitable caption to display on a scene tab given a /// file name. If multiple contains files with the same names, /// their captions are disambiguated. /// </summary> /// <param name="file">Full path to scene file</param> /// <returns></returns> private string GenerateTabCaption(string file) { var name = Path.GetFileName(file); for (int j = 0; j < tabControl1.TabPages.Count; ++j ) { if (name == tabControl1.TabPages[j].Text) { string numberedName = null; for (int i = 2; numberedName == null; ++i) { numberedName = name + " (" + i + ")"; for (int k = 0; k < tabControl1.TabPages.Count; ++k) { if (numberedName == tabControl1.TabPages[k].Text) { numberedName = null; break; } } } return numberedName; } } return name; } /// <summary> /// Close a given tab in the UI /// </summary> /// <param name="tab"></param> private void CloseTab(TabPage tab) { Debug.Assert(tab != null); // If this is the last tab, we need to add an empty tab before we remove it if (tabControl1.TabCount == 1) { if (CoreSettings.CoreSettings.Default.ExitOnTabClosing) { Application.Exit(); return; } else { AddEmptyTab(); } } if (tab == tabControl1.SelectedTab) { // need to select another tab first for (var i = 0; i < tabControl1.TabCount; ++i) { if (tabControl1.TabPages[i] == tab) { continue; } SelectTab(tabControl1.TabPages[i]); break; } } // free all internal data for this scene UiState.RemoveTab(tab); // and drop the UI tab tabControl1.TabPages.Remove(tab); if (TabChanged != null) { TabChanged((Tab)tab.Tag, false); } if(_emptyTab == tab) { _emptyTab = null; } } /// <summary> /// Select a given tab in the UI /// </summary> /// <param name="tab"></param> public void SelectTab(TabPage tab) { Debug.Assert(tab != null); tabControl1.SelectedTab = tab; var outer = UiState.TabForId(tab); Debug.Assert(outer != null); if (outer.ActiveScene != null) { toolStripStatistics.Text = outer.ActiveScene.StatsString; } else { toolStripStatistics.Text = ""; } // update internal housekeeping UiState.SelectTab(tab); // update UI check boxes var vm = _ui.ActiveTab.ActiveViewMode; fullViewToolStripMenuItem.CheckState = toolStripButtonFullView.CheckState = vm == Tab.ViewMode.Single ? CheckState.Checked : CheckState.Unchecked; twoViewsToolStripMenuItem.CheckState = toolStripButtonTwoViews.CheckState = vm == Tab.ViewMode.Two ? CheckState.Checked : CheckState.Unchecked; fourViewsToolStripMenuItem.CheckState = toolStripButtonFourViews.CheckState = vm == Tab.ViewMode.Four ? CheckState.Checked : CheckState.Unchecked; // some other UI housekeeping, this also injects the GL panel into the tab ActivateUiTab(tab); } private static int _tabCounter; private TabPage _tabContextMenuOwner; private TabPage _emptyTab; private SettingsDialog _settings; private Tab.ViewSeparator _dragSeparator = Tab.ViewSeparator._Max; private string _captionStub; private NormalVectorGeneratorDialog _normalsDialog; private const string LoadingTitlePostfix = " (loading)"; private const string FailedTitlePostfix = " (failed)"; private string GenerateTabKey() { return (++_tabCounter).ToString(CultureInfo.InvariantCulture); } /// <summary> /// Opens a particular 3D model and assigns it to a particular tab. /// May be called on a non-GUI-thread. /// </summary> private void OpenFile(Tab tab, bool setActive) { try { tab.ActiveScene = new Scene(tab.File); CoreSettings.CoreSettings.Default.CountFilesOpened++; } catch(Exception ex) { tab.SetFailed(ex.Message); } var updateTitle = new MethodInvoker(() => { var t = (TabPage)tab.Id; if (!t.Text.EndsWith(LoadingTitlePostfix)) { return; } t.Text = t.Text.Substring(0,t.Text.Length - LoadingTitlePostfix.Length); if (tab.State == Tab.TabState.Failed) { t.Text = t.Text + FailedTitlePostfix; } }); // Must use BeginInvoke() here to make sure it gets executed // on the thread hosting the GUI message pump. An exception // are potential calls coming from our own c'tor: at this // time the window handle is not ready yet and BeginInvoke() // is thus not available. if (!_initialized) { if (setActive) { SelectTab((TabPage) tab.Id); } PopulateInspector(tab); updateTitle(); } else { if (setActive) { BeginInvoke(_delegateSelectTab, new[] {tab.Id}); } BeginInvoke(_delegatePopulateInspector, new object[] { tab }); BeginInvoke(updateTitle); } } /// <summary> /// Populate the inspector view for a given tab. This can be called /// as soon as the scene to be displayed is loaded, i.e. tab.ActiveScene is non-null. /// </summary> /// <param name="tab"></param> public void PopulateInspector(Tab tab) { var ui = UiForTab(tab); Debug.Assert(ui != null); var inspector = ui.GetInspector(); inspector.SetSceneSource(tab.ActiveScene); } public TabPage TabPageForTab(Tab tab) { return (TabPage) tab.Id; } public TabUiSkeleton UiForTab(Tab tab) { return ((TabUiSkeleton) TabPageForTab(tab).Controls[0]); } private void ToolsToolStripMenuItemClick(object sender, EventArgs e) { } private void AboutToolStripMenuItemClick(object sender, EventArgs e) { var ab = new About(); ab.ShowDialog(); } private void OnGlLoad(object sender, EventArgs e) { if (_renderer != null) { _renderer.Dispose(); } _renderer = new Renderer(this); #if USE_APP_IDLE // register Idle event so we get regular callbacks for drawing Application.Idle += ApplicationIdle; #else _timer = new System.Windows.Forms.Timer(); _timer.Interval = 20; _timer.Tick += ApplicationIdle; _timer.Start(); #endif } private void OnGlResize(object sender, EventArgs e) { if (_renderer == null) // safeguard in case glControl's Load() wasn't fired yet { return; } _renderer.Resize(); } private void GlPaint(object sender, PaintEventArgs e) { if (_renderer == null) // safeguard in case glControl's Load() wasn't fired yet { return; } FrameRender(); } private void ApplicationIdle(object sender, EventArgs e) { if(IsDisposed) { return; } #if USE_APP_IDLE while (glControl1.IsIdle) #endif { FrameUpdate(); FrameRender(); } } private void FrameUpdate() { _fps.Update(); var delta = _fps.LastFrameDelta; _renderer.Update(delta); foreach(var tab in UiState.Tabs) { if (tab.ActiveScene != null) { tab.ActiveScene.Update(delta, tab != UiState.ActiveTab); } } ProcessKeys(); } private void FrameRender() { _renderer.Draw(_ui.ActiveTab); glControl1.SwapBuffers(); } private void ToggleFps(object sender, EventArgs e) { _ui.ShowFps = !_ui.ShowFps; framerateToolStripMenuItem.Checked = toolStripButtonShowFPS.Checked = _ui.ShowFps; } private void ToggleShading(object sender, EventArgs e) { _ui.RenderLit = !_ui.RenderLit; lightingToolStripMenuItem.Checked = toolStripButtonShowShaded.Checked = _ui.RenderLit; } private void ToggleTextures(object sender, EventArgs e) { _ui.RenderTextured = !_ui.RenderTextured; texturedToolStripMenuItem.Checked = toolStripButtonShowTextures.Checked = _ui.RenderTextured; } private void ToggleWireframe(object sender, EventArgs e) { _ui.RenderWireframe = !_ui.RenderWireframe; wireframeToolStripMenuItem.Checked = toolStripButtonWireframe.Checked = _ui.RenderWireframe; } private void ToggleShowBb(object sender, EventArgs e) { _ui.ShowBBs = !_ui.ShowBBs; showBoundingBoxesToolStripMenuItem.Checked = toolStripButtonShowBB.Checked = _ui.ShowBBs; } private void ToggleShowNormals(object sender, EventArgs e) { _ui.ShowNormals = !_ui.ShowNormals; showNormalVectorsToolStripMenuItem.Checked = toolStripButtonShowNormals.Checked = _ui.ShowNormals; } private void ToggleShowSkeleton(object sender, EventArgs e) { _ui.ShowSkeleton = !_ui.ShowSkeleton; showAnimationSkeletonToolStripMenuItem.Checked = toolStripButtonShowSkeleton.Checked = _ui.ShowSkeleton; } private void ToggleFullView(object sender, EventArgs e) { if (UiState.ActiveTab.ActiveViewMode == Tab.ViewMode.Single) { return; } UiState.ActiveTab.ActiveViewMode = Tab.ViewMode.Single; toolStripButtonFullView.CheckState = CheckState.Checked; toolStripButtonTwoViews.CheckState = CheckState.Unchecked; toolStripButtonFourViews.CheckState = CheckState.Unchecked; fullViewToolStripMenuItem.CheckState = CheckState.Checked; twoViewsToolStripMenuItem.CheckState = CheckState.Unchecked; fourViewsToolStripMenuItem.CheckState = CheckState.Unchecked; } private void ToggleTwoViews(object sender, EventArgs e) { if (UiState.ActiveTab.ActiveViewMode == Tab.ViewMode.Two) { return; } UiState.ActiveTab.ActiveViewMode = Tab.ViewMode.Two; toolStripButtonFullView.CheckState = CheckState.Unchecked; toolStripButtonTwoViews.CheckState = CheckState.Checked; toolStripButtonFourViews.CheckState = CheckState.Unchecked; fullViewToolStripMenuItem.CheckState = CheckState.Unchecked; twoViewsToolStripMenuItem.CheckState = CheckState.Checked; fourViewsToolStripMenuItem.CheckState = CheckState.Unchecked; } private void ToggleFourViews(object sender, EventArgs e) { if (UiState.ActiveTab.ActiveViewMode == Tab.ViewMode.Four) { return; } UiState.ActiveTab.ActiveViewMode = Tab.ViewMode.Four; toolStripButtonFullView.CheckState = CheckState.Unchecked; toolStripButtonTwoViews.CheckState = CheckState.Unchecked; toolStripButtonFourViews.CheckState = CheckState.Checked; fullViewToolStripMenuItem.CheckState = CheckState.Unchecked; twoViewsToolStripMenuItem.CheckState = CheckState.Unchecked; fourViewsToolStripMenuItem.CheckState = CheckState.Checked; } private void OnTabSelected(object sender, TabControlEventArgs e) { var tab = tabControl1.SelectedTab; SelectTab(tab); } private void OnShowTabContextMenu(object sender, MouseEventArgs e) { // http://social.msdn.microsoft.com/forums/en-US/winforms/thread/e09d081d-a7f5-479d-bd29-44b6d163ebc8 if (e.Button == MouseButtons.Right) { for (int i = 0; i < tabControl1.TabCount; i++) { // get the tab's rectangle area and check if it contains the mouse cursor Rectangle r = tabControl1.GetTabRect(i); if (r.Contains(e.Location)) { // hack: store the owning tab so the event handlers for // the context menu know on whom they operate _tabContextMenuOwner = tabControl1.TabPages[i]; tabContextMenuStrip.Show(tabControl1, e.Location); } } } } private void OnCloseTabFromContextMenu(object sender, EventArgs e) { Debug.Assert(_tabContextMenuOwner != null); CloseTab(_tabContextMenuOwner); } private void OnCloseAllTabsButThisFromContextMenu(object sender, EventArgs e) { Debug.Assert(_tabContextMenuOwner != null); while (tabControl1.TabCount > 1) { for (int i = 0; i < tabControl1.TabCount; i++) { if (_tabContextMenuOwner != tabControl1.TabPages[i]) { CloseTab(tabControl1.TabPages[i]); } } } } private void OnCloseTab(object sender, EventArgs e) { if (tabControl1.SelectedTab != null) { CloseTab(tabControl1.SelectedTab); } } private void OnFileMenuOpen(object sender, EventArgs e) { if(openFileDialog.ShowDialog() == DialogResult.OK) { var names = openFileDialog.FileNames; var first = true; foreach(var name in names) { AddTab(name,true, first); first = false; } } } private void OnFileMenuCloseAll(object sender, EventArgs e) { while(tabControl1.TabPages.Count > 1) { CloseTab(tabControl1.TabPages[0]); } CloseTab(tabControl1.TabPages[0]); } private void OnFileMenuRecent(object sender, EventArgs e) { } private void OnFileMenuQuit(object sender, EventArgs e) { Close(); } private void OnCloseForm(object sender, FormClosedEventArgs e) { UiState.Dispose(); _renderer.Dispose(); } private void OnShowSettings(object sender, EventArgs e) { if (_settings == null || _settings.IsDisposed) { _settings = new SettingsDialog {Main = this}; } if(!_settings.Visible) { _settings.Show(); } } public void CloseSettingsDialog() { Debug.Assert(_settings != null); _settings.Close(); _settings = null; } private void OnExport(object sender, EventArgs e) { var exp = new ExportDialog(this); exp.Show(this); } private void OnDrag(object sender, DragEventArgs e) { // code based on http://www.codeproject.com/Articles/3598/Drag-and-Drop try { var a = (Array)e.Data.GetData(DataFormats.FileDrop); if (a != null && a.GetLength(0) > 0) { for (int i = 0, count = a.GetLength(0); i < count; ++i) { var s = a.GetValue(i).ToString(); // check if the dragged file is a folder. In this case, // we load all applicable files in the folder. // TODO this means, files with no proper file extension // won't load this way. try { FileAttributes attr = File.GetAttributes(s); if (attr.HasFlag(FileAttributes.Directory)) { string[] formats; using (var tempImporter = new Assimp.AssimpContext()) { formats = tempImporter.GetSupportedImportFormats(); } string[] files = Directory.GetFiles(s); foreach (var file in files) { var ext = Path.GetExtension(file); if (ext == null) { continue; } var lowerExt = ext.ToLower(); if (formats.Any(format => lowerExt == format)) { AddTab(file); } } continue; } } // ReSharper disable EmptyGeneralCatchClause catch (Exception) // ReSharper restore EmptyGeneralCatchClause { // ignore this - AddTab() handles the failure } // Call OpenFile asynchronously. // Explorer instance from which file is dropped is not responding // all the time when DragDrop handler is active, so we need to return // immediately (of particular importance if OpenFile shows MessageBox). AddTab(s); } // in the case Explorer overlaps this form Activate(); } } catch (Exception ex) { Trace.WriteLine("Error in DragDrop function: " + ex.Message); } } private void OnDragEnter(object sender, DragEventArgs e) { // only accept files for drag and drop e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop) ? DragDropEffects.Copy : DragDropEffects.None; } private void OnLoad(object sender, EventArgs e) { if (CoreSettings.CoreSettings.Default.Maximized) { WindowState = FormWindowState.Maximized; Location = CoreSettings.CoreSettings.Default.Location; Size = CoreSettings.CoreSettings.Default.Size; } else { var size = CoreSettings.CoreSettings.Default.Size; if (size.Width != 0) // first-time run { Location = CoreSettings.CoreSettings.Default.Location; Size = size; } } } private void OnClosing(object sender, FormClosingEventArgs e) { if (WindowState == FormWindowState.Maximized) { CoreSettings.CoreSettings.Default.Location = RestoreBounds.Location; CoreSettings.CoreSettings.Default.Size = RestoreBounds.Size; CoreSettings.CoreSettings.Default.Maximized = true; } else { CoreSettings.CoreSettings.Default.Location = Location; CoreSettings.CoreSettings.Default.Size = Size; CoreSettings.CoreSettings.Default.Maximized = false; } CoreSettings.CoreSettings.Default.Save(); #if LEAP //Cleanup LeapMotion Controller _leapController.RemoveListener(_leapListener); _leapController.Dispose(); #endif } // note: the methods below are in MainWindow_Input.cs // Windows Forms Designer keeps re-generating them though. partial void OnKeyDown(object sender, KeyEventArgs e); partial void OnKeyUp(object sender, KeyEventArgs e); partial void OnMouseDown(object sender, MouseEventArgs e); partial void OnMouseEnter(object sender, EventArgs e); partial void OnMouseLeave(object sender, EventArgs e); partial void OnMouseMove(object sender, MouseEventArgs e); partial void OnMouseUp(object sender, MouseEventArgs e); partial void OnPreviewKeyDown(object sender, PreviewKeyDownEventArgs e); private void OnTipOfTheDay(object sender, EventArgs e) { var tip = new TipOfTheDayDialog(); tip.ShowDialog(); } private void OnDonate(object sender, LinkLabelLinkClickedEventArgs e) { linkLabelDonate.LinkVisited = false; var donate = new DonationDialog(); donate.ShowDialog(); } private void OnSetFileAssociations(object sender, EventArgs e) { using (var imp = new Assimp.AssimpContext()) { var list = imp.GetSupportedImportFormats(); // do not associate .xml - it is too generic var filteredList = list.Where(s => s != ".xml").ToArray(); var listString = string.Join(", ", filteredList); if(DialogResult.OK == MessageBox.Show(this, "The following file extensions will be associated with open3mod: " + listString, "Set file associations", MessageBoxButtons.OKCancel)) { if (!FileAssociations.SetAssociations(list)) { MessageBox.Show(this, "Failed to set file extensions","Error",MessageBoxButtons.OK,MessageBoxIcon.Error); } else { MessageBox.Show(this, "File extensions have been successfully associated", "open3mod", MessageBoxButtons.OK, MessageBoxIcon.Information); } } } } private void linkLabelWebsite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start("http://www.open3mod.com/"); } // Hardcoded sample files with paths adjusted for running from // the repository (or standalone version), or from the installed // version. private void wusonToolStripMenuItem_Click(object sender, EventArgs e) { const string repos = "../../../testdata/scenes/spider.obj"; const string installed = "testscenes/spider/spider.obj"; AddTab(File.Exists(repos) ? repos : installed); } private void jeepToolStripMenuItem_Click(object sender, EventArgs e) { const string repos = "../../../testdata/redist/jeep/jeep1.ms3d"; const string installed = "testscenes/jeep/jeep1.ms3d"; AddTab(File.Exists(repos) ? repos : installed); } private void duckToolStripMenuItem_Click(object sender, EventArgs e) { const string repos = "../../../testdata/redist/duck/duck.dae"; const string installed = "testscenes/duck/duck.dae"; AddTab(File.Exists(repos) ? repos : installed); } private void wustonAnimatedToolStripMenuItem_Click(object sender, EventArgs e) { const string repos = "../../../testdata/scenes/Testwuson.X"; const string installed = "testscenes/wuson/Testwuson.X"; AddTab(File.Exists(repos) ? repos : installed); } private void lostEmpireToolStripMenuItem_Click(object sender, EventArgs e) { const string repos = "../../../testdata/redist/lost-empire/lost_empire.obj"; const string installed = "testscenes/lost-empire/lost_empire.obj"; AddTab(File.Exists(repos) ? repos : installed); } private void StartUndoRedoUiStatePollLoop() { // Loop to regularly update the "Undo" and "Redo" buttons. // This is sub-optimal performance-wise. Ideally, we should get notified from // UndoStack if an item is pushed such that Undo or Redo becomes possible. // This however introduces a nasty dependency from a (scene-specific) UndoStack // back to MainWindow which design-wise I want to avoid. DelayExecution(new TimeSpan(0, 0, 0, 0, 100), () => { UpdateUndoRedoUiState(); StartUndoRedoUiStatePollLoop(); }); } private void UpdateUndoRedoUiState() { var scene = UiState.ActiveTab.ActiveScene; if (scene == null) { toolStripButtonUndo.Enabled = undoToolStripMenuItem.Enabled = false; toolStripButtonUndo.ToolTipText = undoToolStripMenuItem.Text = "Undo"; toolStripButtonRedo.Enabled = redoToolStripMenuItem.Enabled = false; toolStripButtonRedo.ToolTipText = redoToolStripMenuItem.Text = "Redo"; return; } var undo = scene.UndoStack; if (undo.CanUndo()) { toolStripButtonUndo.Enabled = undoToolStripMenuItem.Enabled = true; toolStripButtonUndo.ToolTipText = undoToolStripMenuItem.Text = "Undo " + undo.GetUndoDescription(); } else { toolStripButtonUndo.Enabled = undoToolStripMenuItem.Enabled = false; toolStripButtonUndo.ToolTipText = undoToolStripMenuItem.Text = "Undo"; } if (undo.CanRedo()) { toolStripButtonRedo.Enabled = redoToolStripMenuItem.Enabled = true; toolStripButtonRedo.ToolTipText = redoToolStripMenuItem.Text = "Redo " + undo.GetRedoDescription(); } else { toolStripButtonRedo.Enabled = redoToolStripMenuItem.Enabled = false; toolStripButtonRedo.ToolTipText = redoToolStripMenuItem.Text = "Redo"; } } private void OnGlobalUndo(object sender, EventArgs e) { var scene = UiState.ActiveTab.ActiveScene; if (scene == null) { return; } var undo = scene.UndoStack; if (!undo.CanUndo()) { return; } undo.Undo(); } private void OnGlobalRedo(object sender, EventArgs e) { var scene = UiState.ActiveTab.ActiveScene; if (scene == null) { return; } var undo = scene.UndoStack; if (!undo.CanRedo()) { return; } undo.Redo(); } private void OnReloadCurrentTab(object sender, EventArgs e) { var activeTab = UiState.ActiveTab; if (activeTab.ActiveScene == null) { return; } activeTab.ActiveScene = null; new Thread( () => { activeTab.ActiveScene = new Scene(activeTab.File); BeginInvoke(new Action(() => PopulateInspector(activeTab))); }).Start(); } private void OnGenerateNormals(object sender, EventArgs e) { var activeTab = UiState.ActiveTab; if (activeTab.ActiveScene == null) { return; } var scene = activeTab.ActiveScene; if (_normalsDialog != null) { _normalsDialog.Close(); _normalsDialog.Dispose(); _normalsDialog = null; } _normalsDialog = new NormalVectorGeneratorDialog(scene, scene.Raw.Meshes, TabPageForTab(activeTab).Text + " (all meshes)"); _normalsDialog.Show(this); } } } /* vi: set shiftwidth=4 tabstop=4: */
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Thrift.Protocol.Entities; using Thrift.Protocol.Utilities; using Thrift.Transport; namespace Thrift.Protocol { /// <summary> /// JSON protocol implementation for thrift. /// This is a full-featured protocol supporting Write and Read. /// Please see the C++ class header for a detailed description of the /// protocol's wire format. /// Adapted from the Java version. /// </summary> // ReSharper disable once InconsistentNaming public class TJsonProtocol : TProtocol { private const long Version = 1; // Temporary buffer used by several methods private readonly byte[] _tempBuffer = new byte[4]; // Current context that we are in protected JSONBaseContext Context; // Stack of nested contexts that we may be in protected Stack<JSONBaseContext> ContextStack = new Stack<JSONBaseContext>(); // Reader that manages a 1-byte buffer protected LookaheadReader Reader; // Default encoding protected Encoding Utf8Encoding = Encoding.UTF8; /// <summary> /// TJsonProtocol Constructor /// </summary> public TJsonProtocol(TTransport trans) : base(trans) { Context = new JSONBaseContext(this); Reader = new LookaheadReader(this); } /// <summary> /// Push a new JSON context onto the stack. /// </summary> protected void PushContext(JSONBaseContext c) { ContextStack.Push(Context); Context = c; } /// <summary> /// Pop the last JSON context off the stack /// </summary> protected void PopContext() { Context = ContextStack.Pop(); } /// <summary> /// Resets the context stack to pristine state. Allows for reusal of the protocol /// even in cases where the protocol instance was in an undefined state due to /// dangling/stale/obsolete contexts /// </summary> private void resetContext() { ContextStack.Clear(); Context = new JSONBaseContext(this); } /// <summary> /// Read a byte that must match b[0]; otherwise an exception is thrown. /// Marked protected to avoid synthetic accessor in JSONListContext.Read /// and JSONPairContext.Read /// </summary> protected async Task ReadJsonSyntaxCharAsync(byte[] bytes, CancellationToken cancellationToken) { var ch = await Reader.ReadAsync(cancellationToken); if (ch != bytes[0]) { throw new TProtocolException(TProtocolException.INVALID_DATA, $"Unexpected character: {(char) ch}"); } } /// <summary> /// Write the bytes in array buf as a JSON characters, escaping as needed /// </summary> private async Task WriteJsonStringAsync(byte[] bytes, CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); var len = bytes.Length; for (var i = 0; i < len; i++) { if ((bytes[i] & 0x00FF) >= 0x30) { if (bytes[i] == TJSONProtocolConstants.Backslash[0]) { await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); } else { await Trans.WriteAsync(bytes, i, 1, cancellationToken); } } else { _tempBuffer[0] = TJSONProtocolConstants.JsonCharTable[bytes[i]]; if (_tempBuffer[0] == 1) { await Trans.WriteAsync(bytes, i, 1, cancellationToken); } else if (_tempBuffer[0] > 1) { await Trans.WriteAsync(TJSONProtocolConstants.Backslash, cancellationToken); await Trans.WriteAsync(_tempBuffer, 0, 1, cancellationToken); } else { await Trans.WriteAsync(TJSONProtocolConstants.EscSequences, cancellationToken); _tempBuffer[0] = TJSONProtocolHelper.ToHexChar((byte) (bytes[i] >> 4)); _tempBuffer[1] = TJSONProtocolHelper.ToHexChar(bytes[i]); await Trans.WriteAsync(_tempBuffer, 0, 2, cancellationToken); } } } await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } /// <summary> /// Write out number as a JSON value. If the context dictates so, it will be /// wrapped in quotes to output as a JSON string. /// </summary> private async Task WriteJsonIntegerAsync(long num, CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); var str = num.ToString(); var escapeNum = Context.EscapeNumbers(); if (escapeNum) { await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } var bytes = Utf8Encoding.GetBytes(str); await Trans.WriteAsync(bytes, cancellationToken); if (escapeNum) { await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } } /// <summary> /// Write out a double as a JSON value. If it is NaN or infinity or if the /// context dictates escaping, Write out as JSON string. /// </summary> private async Task WriteJsonDoubleAsync(double num, CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); var str = num.ToString("G17", CultureInfo.InvariantCulture); var special = false; switch (str[0]) { case 'N': // NaN case 'I': // Infinity special = true; break; case '-': if (str[1] == 'I') { // -Infinity special = true; } break; } var escapeNum = special || Context.EscapeNumbers(); if (escapeNum) { await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } await Trans.WriteAsync(Utf8Encoding.GetBytes(str), cancellationToken); if (escapeNum) { await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } } /// <summary> /// Write out contents of byte array b as a JSON string with base-64 encoded /// data /// </summary> private async Task WriteJsonBase64Async(byte[] bytes, CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); var len = bytes.Length; var off = 0; while (len >= 3) { // Encode 3 bytes at a time TBase64Utils.Encode(bytes, off, 3, _tempBuffer, 0); await Trans.WriteAsync(_tempBuffer, 0, 4, cancellationToken); off += 3; len -= 3; } if (len > 0) { // Encode remainder TBase64Utils.Encode(bytes, off, len, _tempBuffer, 0); await Trans.WriteAsync(_tempBuffer, 0, len + 1, cancellationToken); } await Trans.WriteAsync(TJSONProtocolConstants.Quote, cancellationToken); } private async Task WriteJsonObjectStartAsync(CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); await Trans.WriteAsync(TJSONProtocolConstants.LeftBrace, cancellationToken); PushContext(new JSONPairContext(this)); } private async Task WriteJsonObjectEndAsync(CancellationToken cancellationToken) { PopContext(); await Trans.WriteAsync(TJSONProtocolConstants.RightBrace, cancellationToken); } private async Task WriteJsonArrayStartAsync(CancellationToken cancellationToken) { await Context.WriteConditionalDelimiterAsync(cancellationToken); await Trans.WriteAsync(TJSONProtocolConstants.LeftBracket, cancellationToken); PushContext(new JSONListContext(this)); } private async Task WriteJsonArrayEndAsync(CancellationToken cancellationToken) { PopContext(); await Trans.WriteAsync(TJSONProtocolConstants.RightBracket, cancellationToken); } public override async Task WriteMessageBeginAsync(TMessage message, CancellationToken cancellationToken) { resetContext(); await WriteJsonArrayStartAsync(cancellationToken); await WriteJsonIntegerAsync(Version, cancellationToken); var b = Utf8Encoding.GetBytes(message.Name); await WriteJsonStringAsync(b, cancellationToken); await WriteJsonIntegerAsync((long) message.Type, cancellationToken); await WriteJsonIntegerAsync(message.SeqID, cancellationToken); } public override async Task WriteMessageEndAsync(CancellationToken cancellationToken) { await WriteJsonArrayEndAsync(cancellationToken); } public override async Task WriteStructBeginAsync(TStruct @struct, CancellationToken cancellationToken) { await WriteJsonObjectStartAsync(cancellationToken); } public override async Task WriteStructEndAsync(CancellationToken cancellationToken) { await WriteJsonObjectEndAsync(cancellationToken); } public override async Task WriteFieldBeginAsync(TField field, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(field.ID, cancellationToken); await WriteJsonObjectStartAsync(cancellationToken); await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(field.Type), cancellationToken); } public override async Task WriteFieldEndAsync(CancellationToken cancellationToken) { await WriteJsonObjectEndAsync(cancellationToken); } public override Task WriteFieldStopAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override async Task WriteMapBeginAsync(TMap map, CancellationToken cancellationToken) { await WriteJsonArrayStartAsync(cancellationToken); await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.KeyType), cancellationToken); await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(map.ValueType), cancellationToken); await WriteJsonIntegerAsync(map.Count, cancellationToken); await WriteJsonObjectStartAsync(cancellationToken); } public override async Task WriteMapEndAsync(CancellationToken cancellationToken) { await WriteJsonObjectEndAsync(cancellationToken); await WriteJsonArrayEndAsync(cancellationToken); } public override async Task WriteListBeginAsync(TList list, CancellationToken cancellationToken) { await WriteJsonArrayStartAsync(cancellationToken); await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(list.ElementType), cancellationToken); await WriteJsonIntegerAsync(list.Count, cancellationToken); } public override async Task WriteListEndAsync(CancellationToken cancellationToken) { await WriteJsonArrayEndAsync(cancellationToken); } public override async Task WriteSetBeginAsync(TSet set, CancellationToken cancellationToken) { await WriteJsonArrayStartAsync(cancellationToken); await WriteJsonStringAsync(TJSONProtocolHelper.GetTypeNameForTypeId(set.ElementType), cancellationToken); await WriteJsonIntegerAsync(set.Count, cancellationToken); } public override async Task WriteSetEndAsync(CancellationToken cancellationToken) { await WriteJsonArrayEndAsync(cancellationToken); } public override async Task WriteBoolAsync(bool b, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(b ? 1 : 0, cancellationToken); } public override async Task WriteByteAsync(sbyte b, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(b, cancellationToken); } public override async Task WriteI16Async(short i16, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(i16, cancellationToken); } public override async Task WriteI32Async(int i32, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(i32, cancellationToken); } public override async Task WriteI64Async(long i64, CancellationToken cancellationToken) { await WriteJsonIntegerAsync(i64, cancellationToken); } public override async Task WriteDoubleAsync(double d, CancellationToken cancellationToken) { await WriteJsonDoubleAsync(d, cancellationToken); } public override async Task WriteStringAsync(string s, CancellationToken cancellationToken) { var b = Utf8Encoding.GetBytes(s); await WriteJsonStringAsync(b, cancellationToken); } public override async Task WriteBinaryAsync(byte[] bytes, CancellationToken cancellationToken) { await WriteJsonBase64Async(bytes, cancellationToken); } /// <summary> /// Read in a JSON string, unescaping as appropriate.. Skip Reading from the /// context if skipContext is true. /// </summary> private async ValueTask<byte[]> ReadJsonStringAsync(bool skipContext, CancellationToken cancellationToken) { using (var buffer = new MemoryStream()) { var codeunits = new List<char>(); if (!skipContext) { await Context.ReadConditionalDelimiterAsync(cancellationToken); } await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); while (true) { var ch = await Reader.ReadAsync(cancellationToken); if (ch == TJSONProtocolConstants.Quote[0]) { break; } // escaped? if (ch != TJSONProtocolConstants.EscSequences[0]) { await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken); continue; } // distinguish between \uXXXX and \? ch = await Reader.ReadAsync(cancellationToken); if (ch != TJSONProtocolConstants.EscSequences[1]) // control chars like \n { var off = Array.IndexOf(TJSONProtocolConstants.EscapeChars, (char) ch); if (off == -1) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected control char"); } ch = TJSONProtocolConstants.EscapeCharValues[off]; await buffer.WriteAsync(new[] {ch}, 0, 1, cancellationToken); continue; } // it's \uXXXX await Trans.ReadAllAsync(_tempBuffer, 0, 4, cancellationToken); var wch = (short) ((TJSONProtocolHelper.ToHexVal(_tempBuffer[0]) << 12) + (TJSONProtocolHelper.ToHexVal(_tempBuffer[1]) << 8) + (TJSONProtocolHelper.ToHexVal(_tempBuffer[2]) << 4) + TJSONProtocolHelper.ToHexVal(_tempBuffer[3])); if (char.IsHighSurrogate((char) wch)) { if (codeunits.Count > 0) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char"); } codeunits.Add((char) wch); } else if (char.IsLowSurrogate((char) wch)) { if (codeunits.Count == 0) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected high surrogate char"); } codeunits.Add((char) wch); var tmp = Utf8Encoding.GetBytes(codeunits.ToArray()); await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken); codeunits.Clear(); } else { var tmp = Utf8Encoding.GetBytes(new[] {(char) wch}); await buffer.WriteAsync(tmp, 0, tmp.Length, cancellationToken); } } if (codeunits.Count > 0) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Expected low surrogate char"); } return buffer.ToArray(); } } /// <summary> /// Read in a sequence of characters that are all valid in JSON numbers. Does /// not do a complete regex check to validate that this is actually a number. /// </summary> private async ValueTask<string> ReadJsonNumericCharsAsync(CancellationToken cancellationToken) { var strbld = new StringBuilder(); while (true) { //TODO: workaround for primitive types with TJsonProtocol, think - how to rewrite into more easy form without exceptions try { var ch = await Reader.PeekAsync(cancellationToken); if (!TJSONProtocolHelper.IsJsonNumeric(ch)) { break; } var c = (char)await Reader.ReadAsync(cancellationToken); strbld.Append(c); } catch (TTransportException) { break; } } return strbld.ToString(); } /// <summary> /// Read in a JSON number. If the context dictates, Read in enclosing quotes. /// </summary> private async ValueTask<long> ReadJsonIntegerAsync(CancellationToken cancellationToken) { await Context.ReadConditionalDelimiterAsync(cancellationToken); if (Context.EscapeNumbers()) { await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); } var str = await ReadJsonNumericCharsAsync(cancellationToken); if (Context.EscapeNumbers()) { await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); } try { return long.Parse(str); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } /// <summary> /// Read in a JSON double value. Throw if the value is not wrapped in quotes /// when expected or if wrapped in quotes when not expected. /// </summary> private async ValueTask<double> ReadJsonDoubleAsync(CancellationToken cancellationToken) { await Context.ReadConditionalDelimiterAsync(cancellationToken); if (await Reader.PeekAsync(cancellationToken) == TJSONProtocolConstants.Quote[0]) { var arr = await ReadJsonStringAsync(true, cancellationToken); var dub = double.Parse(Utf8Encoding.GetString(arr, 0, arr.Length), CultureInfo.InvariantCulture); if (!Context.EscapeNumbers() && !double.IsNaN(dub) && !double.IsInfinity(dub)) { // Throw exception -- we should not be in a string in this case throw new TProtocolException(TProtocolException.INVALID_DATA, "Numeric data unexpectedly quoted"); } return dub; } if (Context.EscapeNumbers()) { // This will throw - we should have had a quote if escapeNum == true await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Quote, cancellationToken); } try { return double.Parse(await ReadJsonNumericCharsAsync(cancellationToken), CultureInfo.InvariantCulture); } catch (FormatException) { throw new TProtocolException(TProtocolException.INVALID_DATA, "Bad data encounted in numeric data"); } } /// <summary> /// Read in a JSON string containing base-64 encoded data and decode it. /// </summary> private async ValueTask<byte[]> ReadJsonBase64Async(CancellationToken cancellationToken) { var b = await ReadJsonStringAsync(false, cancellationToken); var len = b.Length; var off = 0; var size = 0; // reduce len to ignore fill bytes while ((len > 0) && (b[len - 1] == '=')) { --len; } // read & decode full byte triplets = 4 source bytes while (len > 4) { // Decode 4 bytes at a time TBase64Utils.Decode(b, off, 4, b, size); // NB: decoded in place off += 4; len -= 4; size += 3; } // Don't decode if we hit the end or got a single leftover byte (invalid // base64 but legal for skip of regular string exType) if (len > 1) { // Decode remainder TBase64Utils.Decode(b, off, len, b, size); // NB: decoded in place size += len - 1; } // Sadly we must copy the byte[] (any way around this?) var result = new byte[size]; Array.Copy(b, 0, result, 0, size); return result; } private async Task ReadJsonObjectStartAsync(CancellationToken cancellationToken) { await Context.ReadConditionalDelimiterAsync(cancellationToken); await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBrace, cancellationToken); PushContext(new JSONPairContext(this)); } private async Task ReadJsonObjectEndAsync(CancellationToken cancellationToken) { await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBrace, cancellationToken); PopContext(); } private async Task ReadJsonArrayStartAsync(CancellationToken cancellationToken) { await Context.ReadConditionalDelimiterAsync(cancellationToken); await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.LeftBracket, cancellationToken); PushContext(new JSONListContext(this)); } private async Task ReadJsonArrayEndAsync(CancellationToken cancellationToken) { await ReadJsonSyntaxCharAsync(TJSONProtocolConstants.RightBracket, cancellationToken); PopContext(); } public override async ValueTask<TMessage> ReadMessageBeginAsync(CancellationToken cancellationToken) { var message = new TMessage(); resetContext(); await ReadJsonArrayStartAsync(cancellationToken); if (await ReadJsonIntegerAsync(cancellationToken) != Version) { throw new TProtocolException(TProtocolException.BAD_VERSION, "Message contained bad version."); } var buf = await ReadJsonStringAsync(false, cancellationToken); message.Name = Utf8Encoding.GetString(buf, 0, buf.Length); message.Type = (TMessageType) await ReadJsonIntegerAsync(cancellationToken); message.SeqID = (int) await ReadJsonIntegerAsync(cancellationToken); return message; } public override async Task ReadMessageEndAsync(CancellationToken cancellationToken) { await ReadJsonArrayEndAsync(cancellationToken); } public override async ValueTask<TStruct> ReadStructBeginAsync(CancellationToken cancellationToken) { await ReadJsonObjectStartAsync(cancellationToken); return AnonymousStruct; } public override async Task ReadStructEndAsync(CancellationToken cancellationToken) { await ReadJsonObjectEndAsync(cancellationToken); } public override async ValueTask<TField> ReadFieldBeginAsync(CancellationToken cancellationToken) { var ch = await Reader.PeekAsync(cancellationToken); if (ch == TJSONProtocolConstants.RightBrace[0]) { return StopField; } var field = new TField() { ID = (short)await ReadJsonIntegerAsync(cancellationToken) }; await ReadJsonObjectStartAsync(cancellationToken); field.Type = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); return field; } public override async Task ReadFieldEndAsync(CancellationToken cancellationToken) { await ReadJsonObjectEndAsync(cancellationToken); } public override async ValueTask<TMap> ReadMapBeginAsync(CancellationToken cancellationToken) { var map = new TMap(); await ReadJsonArrayStartAsync(cancellationToken); map.KeyType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); map.ValueType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); map.Count = (int) await ReadJsonIntegerAsync(cancellationToken); CheckReadBytesAvailable(map); await ReadJsonObjectStartAsync(cancellationToken); return map; } public override async Task ReadMapEndAsync(CancellationToken cancellationToken) { await ReadJsonObjectEndAsync(cancellationToken); await ReadJsonArrayEndAsync(cancellationToken); } public override async ValueTask<TList> ReadListBeginAsync(CancellationToken cancellationToken) { var list = new TList(); await ReadJsonArrayStartAsync(cancellationToken); list.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); list.Count = (int) await ReadJsonIntegerAsync(cancellationToken); CheckReadBytesAvailable(list); return list; } public override async Task ReadListEndAsync(CancellationToken cancellationToken) { await ReadJsonArrayEndAsync(cancellationToken); } public override async ValueTask<TSet> ReadSetBeginAsync(CancellationToken cancellationToken) { var set = new TSet(); await ReadJsonArrayStartAsync(cancellationToken); set.ElementType = TJSONProtocolHelper.GetTypeIdForTypeName(await ReadJsonStringAsync(false, cancellationToken)); set.Count = (int) await ReadJsonIntegerAsync(cancellationToken); CheckReadBytesAvailable(set); return set; } public override async Task ReadSetEndAsync(CancellationToken cancellationToken) { await ReadJsonArrayEndAsync(cancellationToken); } public override async ValueTask<bool> ReadBoolAsync(CancellationToken cancellationToken) { return await ReadJsonIntegerAsync(cancellationToken) != 0; } public override async ValueTask<sbyte> ReadByteAsync(CancellationToken cancellationToken) { return (sbyte) await ReadJsonIntegerAsync(cancellationToken); } public override async ValueTask<short> ReadI16Async(CancellationToken cancellationToken) { return (short) await ReadJsonIntegerAsync(cancellationToken); } public override async ValueTask<int> ReadI32Async(CancellationToken cancellationToken) { return (int) await ReadJsonIntegerAsync(cancellationToken); } public override async ValueTask<long> ReadI64Async(CancellationToken cancellationToken) { return await ReadJsonIntegerAsync(cancellationToken); } public override async ValueTask<double> ReadDoubleAsync(CancellationToken cancellationToken) { return await ReadJsonDoubleAsync(cancellationToken); } public override async ValueTask<string> ReadStringAsync(CancellationToken cancellationToken) { var buf = await ReadJsonStringAsync(false, cancellationToken); return Utf8Encoding.GetString(buf, 0, buf.Length); } public override async ValueTask<byte[]> ReadBinaryAsync(CancellationToken cancellationToken) { return await ReadJsonBase64Async(cancellationToken); } // Return the minimum number of bytes a type will consume on the wire public override int GetMinSerializedSize(TType type) { switch (type) { case TType.Stop: return 0; case TType.Void: return 0; case TType.Bool: return 1; // written as int case TType.Byte: return 1; case TType.Double: return 1; case TType.I16: return 1; case TType.I32: return 1; case TType.I64: return 1; case TType.String: return 2; // empty string case TType.Struct: return 2; // empty struct case TType.Map: return 2; // empty map case TType.Set: return 2; // empty set case TType.List: return 2; // empty list default: throw new TTransportException(TTransportException.ExceptionType.Unknown, "unrecognized type code"); } } /// <summary> /// Factory for JSON protocol objects /// </summary> public class Factory : TProtocolFactory { public override TProtocol GetProtocol(TTransport trans) { return new TJsonProtocol(trans); } } /// <summary> /// Base class for tracking JSON contexts that may require /// inserting/Reading additional JSON syntax characters /// This base context does nothing. /// </summary> protected class JSONBaseContext { protected TJsonProtocol Proto; public JSONBaseContext(TJsonProtocol proto) { Proto = proto; } public virtual Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public virtual Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public virtual bool EscapeNumbers() { return false; } } /// <summary> /// Context for JSON lists. Will insert/Read commas before each item except /// for the first one /// </summary> protected class JSONListContext : JSONBaseContext { private bool _first = true; public JSONListContext(TJsonProtocol protocol) : base(protocol) { } public override async Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken) { if (_first) { _first = false; } else { await Proto.Trans.WriteAsync(TJSONProtocolConstants.Comma, cancellationToken); } } public override async Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken) { if (_first) { _first = false; } else { await Proto.ReadJsonSyntaxCharAsync(TJSONProtocolConstants.Comma, cancellationToken); } } } /// <summary> /// Context for JSON records. Will insert/Read colons before the value portion /// of each record pair, and commas before each key except the first. In /// addition, will indicate that numbers in the key position need to be /// escaped in quotes (since JSON keys must be strings). /// </summary> // ReSharper disable once InconsistentNaming protected class JSONPairContext : JSONBaseContext { private bool _colon = true; private bool _first = true; public JSONPairContext(TJsonProtocol proto) : base(proto) { } public override async Task WriteConditionalDelimiterAsync(CancellationToken cancellationToken) { if (_first) { _first = false; _colon = true; } else { await Proto.Trans.WriteAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken); _colon = !_colon; } } public override async Task ReadConditionalDelimiterAsync(CancellationToken cancellationToken) { if (_first) { _first = false; _colon = true; } else { await Proto.ReadJsonSyntaxCharAsync(_colon ? TJSONProtocolConstants.Colon : TJSONProtocolConstants.Comma, cancellationToken); _colon = !_colon; } } public override bool EscapeNumbers() { return _colon; } } /// <summary> /// Holds up to one byte from the transport /// </summary> protected class LookaheadReader { private readonly byte[] _data = new byte[1]; private bool _hasData; protected TJsonProtocol Proto; public LookaheadReader(TJsonProtocol proto) { Proto = proto; } /// <summary> /// Return and consume the next byte to be Read, either taking it from the /// data buffer if present or getting it from the transport otherwise. /// </summary> public async ValueTask<byte> ReadAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (_hasData) { _hasData = false; } else { // find more easy way to avoid exception on reading primitive types await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken); } return _data[0]; } /// <summary> /// Return the next byte to be Read without consuming, filling the data /// buffer if it has not been filled alReady. /// </summary> public async ValueTask<byte> PeekAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (!_hasData) { // find more easy way to avoid exception on reading primitive types await Proto.Trans.ReadAllAsync(_data, 0, 1, cancellationToken); _hasData = true; } return _data[0]; } } } }
using System.Linq; using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.CSharp; using System; namespace RefactoringEssentials.CSharp.CodeRefactorings { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = "Invert if")] public class InvertIfCodeRefactoringProvider : CodeRefactoringProvider { static readonly string invertIfFixMessage = GettextCatalog.GetString("Invert 'if'"); public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) return; var span = context.Span; if (!span.IsEmpty) return; var cancellationToken = context.CancellationToken; if (cancellationToken.IsCancellationRequested) return; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); if (model.IsFromGeneratedCode(cancellationToken)) return; var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); var complexIfElseStatement = GetIfElseStatement(root, span); if (complexIfElseStatement != null) { context.RegisterRefactoring( CodeActionFactory.Create( span, DiagnosticSeverity.Info, invertIfFixMessage, t2 => { var statements = GenerateReplacementStatements(complexIfElseStatement); var newRoot = statements.Count == 1 ? root.ReplaceNode(complexIfElseStatement, statements[0]) : root.ReplaceNode(complexIfElseStatement, statements); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) ); return; } var simpleIfElseStatement = GetIfElseStatementSimple(root, span); if (simpleIfElseStatement != null) { context.RegisterRefactoring( CodeActionFactory.Create( span, DiagnosticSeverity.Info, invertIfFixMessage, t2 => { var newRoot = root.ReplaceNode((SyntaxNode) simpleIfElseStatement, simpleIfElseStatement .WithCondition(CSharpUtil.InvertCondition(simpleIfElseStatement.Condition)) .WithStatement(simpleIfElseStatement.Else.Statement) .WithElse(simpleIfElseStatement.Else.WithStatement(simpleIfElseStatement.Statement)) .WithAdditionalAnnotations(Formatter.Annotation) ); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) ); return; } var ifStatement = GetIfStatement(root, span); if (ifStatement != null) { context.RegisterRefactoring( CodeActionFactory.Create( ifStatement.Span, DiagnosticSeverity.Info, invertIfFixMessage, t2 => { var mergedIfStatement = SyntaxFactory.IfStatement(CSharpUtil.InvertCondition(ifStatement.Condition), SyntaxFactory.ReturnStatement()) .WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode((SyntaxNode)ifStatement, new SyntaxNode[] { mergedIfStatement }.Concat(GetStatements(ifStatement.Statement))); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) ); } var ifStatementInLoop = GetIfElseStatementInLoop(root, span); if (ifStatementInLoop != null) { context.RegisterRefactoring( CodeActionFactory.Create( ifStatementInLoop.Span, DiagnosticSeverity.Info, invertIfFixMessage, t2 => { var mergedIfStatement = SyntaxFactory.IfStatement(CSharpUtil.InvertCondition(ifStatementInLoop.Condition), SyntaxFactory.ContinueStatement()) .WithAdditionalAnnotations(Formatter.Annotation); var newRoot = root.ReplaceNode((SyntaxNode)ifStatementInLoop, new SyntaxNode[] { mergedIfStatement }.Concat(GetStatements(ifStatementInLoop.Statement))); return Task.FromResult(document.WithSyntaxRoot(newRoot)); } ) ); return; } } static StatementSyntax GenerateNewTrueStatement(StatementSyntax falseStatement) { var blockStatement = falseStatement as BlockSyntax; if (blockStatement != null) { if (blockStatement.Statements.Count == 1) { var stmt = blockStatement.Statements.First(); if (stmt.GetLeadingTrivia().All(triva => triva.IsKind(SyntaxKind.WhitespaceTrivia))) return stmt; } } return falseStatement; } static IReadOnlyList<SyntaxNode> GenerateReplacementStatements(IfStatementSyntax ifStatement) { if (!(ifStatement.Parent is BlockSyntax)) { return new [] { SyntaxFactory.IfStatement( CSharpUtil.InvertCondition(ifStatement.Condition), ifStatement.Else.Statement ).WithElse(ifStatement.Else.WithStatement(ifStatement.Statement)).WithAdditionalAnnotations(Formatter.Annotation) }; } var result = new List<StatementSyntax>(); result.Add(SyntaxFactory.IfStatement( CSharpUtil.InvertCondition(ifStatement.Condition), GenerateNewTrueStatement(ifStatement.Else.Statement) ).WithAdditionalAnnotations(Formatter.Annotation)); var body = ifStatement.Statement as BlockSyntax; if (body != null) { foreach (var stmt in body.Statements) { result.Add(stmt.WithAdditionalAnnotations(Formatter.Annotation)); } } else { result.Add(ifStatement.Statement.WithAdditionalAnnotations(Formatter.Annotation)); } return result; } static IfStatementSyntax GetIfElseStatement(SyntaxNode root, TextSpan span) { var result = root.FindNode(span) as IfStatementSyntax; if (result == null || !result.IfKeyword.Span.Contains(span) || result.Else == null) return null; var falseStatement = result.Else.Statement; var isQuitingStatement = falseStatement; var blockStatement = falseStatement as BlockSyntax; if (blockStatement != null) { isQuitingStatement = blockStatement.Statements.FirstOrDefault() ?? blockStatement; } if (isQuitingStatement.IsKind(SyntaxKind.ReturnStatement) || isQuitingStatement.IsKind(SyntaxKind.ContinueStatement) || isQuitingStatement.IsKind(SyntaxKind.BreakStatement)) return result; return null; } static IfStatementSyntax GetIfElseStatementSimple(SyntaxNode root, TextSpan span) { var result = root.FindNode(span) as IfStatementSyntax; if (result == null || !result.IfKeyword.Span.Contains(span) || result.Else == null) return null; return result; } static IfStatementSyntax GetIfStatement(SyntaxNode root, TextSpan span) { var result = root.FindNode(span) as IfStatementSyntax; if (result == null) return null; if (!result.IfKeyword.Span.Contains(span) || result.Statement == null || result.Else != null) return null; var parentBlock = result.Parent as BlockSyntax; if (parentBlock == null) return null; var method = parentBlock.Parent as MethodDeclarationSyntax; if (method == null || method.ReturnType.ToString() != "void") return null; int i = parentBlock.Statements.IndexOf(result); if (i + 1 >= parentBlock.Statements.Count) return result; return null; } internal static IEnumerable<SyntaxNode> GetStatements(StatementSyntax statement) { var blockSyntax = statement as BlockSyntax; if (blockSyntax != null) { foreach (var stmt in blockSyntax.Statements) yield return stmt.WithAdditionalAnnotations(Formatter.Annotation); } else { yield return statement.WithAdditionalAnnotations(Formatter.Annotation); } } static IfStatementSyntax GetIfElseStatementInLoop(SyntaxNode root, TextSpan span) { var result = root.FindNode(span) as IfStatementSyntax; if (result == null) return null; if (!result.IfKeyword.Span.Contains(span) || result.Statement == null || result.Else != null) return null; var parentBlock = result.Parent as BlockSyntax; if (parentBlock == null) return null; if (!(parentBlock.Parent is WhileStatementSyntax || parentBlock.Parent is ForEachStatementSyntax || parentBlock.Parent is ForStatementSyntax)) return null; int i = parentBlock.Statements.IndexOf(result); if (i + 1 >= parentBlock.Statements.Count) return result; return null; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Threading; using log4net; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenMetaverse; using OpenMetaverse.Packets; using TokenBucket = OpenSim.Region.ClientStack.LindenUDP.TokenBucket; namespace OpenSim.Region.ClientStack.LindenUDP { #region Delegates /// <summary> /// Fired when updated networking stats are produced for this client /// </summary> /// <param name="inPackets">Number of incoming packets received since this /// event was last fired</param> /// <param name="outPackets">Number of outgoing packets sent since this /// event was last fired</param> /// <param name="unAckedBytes">Current total number of bytes in packets we /// are waiting on ACKs for</param> public delegate void PacketStats(int inPackets, int outPackets, int unAckedBytes); /// <summary> /// Fired when the queue for one or more packet categories is empty. This /// event can be hooked to put more data on the empty queues /// </summary> /// <param name="category">Categories of the packet queues that are empty</param> public delegate void QueueEmpty(ThrottleOutPacketTypeFlags categories); #endregion Delegates /// <summary> /// Tracks state for a client UDP connection and provides client-specific methods /// </summary> public sealed class LLUDPClient { // TODO: Make this a config setting /// <summary>Percentage of the task throttle category that is allocated to avatar and prim /// state updates</summary> const float STATE_TASK_PERCENTAGE = 0.8f; private static readonly ILog m_log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary>The number of packet categories to throttle on. If a throttle category is added /// or removed, this number must also change</summary> const int THROTTLE_CATEGORY_COUNT = 8; /// <summary> /// Controls whether information is logged about each outbound packet immediately before it is sent. For debug purposes. /// </summary> /// <remarks>Any level above 0 will turn on logging.</remarks> public int DebugDataOutLevel { get; set; } /// <summary> /// Controls whether information is logged about each outbound packet immediately before it is sent. For debug purposes. /// </summary> /// <remarks>Any level above 0 will turn on logging.</remarks> public int ThrottleDebugLevel { get { return m_throttleDebugLevel; } set { m_throttleDebugLevel = value; /* m_throttleClient.DebugLevel = m_throttleDebugLevel; foreach (TokenBucket tb in m_throttleCategories) tb.DebugLevel = m_throttleDebugLevel; */ } } private int m_throttleDebugLevel; /// <summary>Fired when updated networking stats are produced for this client</summary> public event PacketStats OnPacketStats; /// <summary>Fired when the queue for a packet category is empty. This event can be /// hooked to put more data on the empty queue</summary> public event QueueEmpty OnQueueEmpty; public event Func<ThrottleOutPacketTypeFlags, bool> HasUpdates; /// <summary>AgentID for this client</summary> public readonly UUID AgentID; /// <summary>The remote address of the connected client</summary> public readonly IPEndPoint RemoteEndPoint; /// <summary>Circuit code that this client is connected on</summary> public readonly uint CircuitCode; /// <summary>Sequence numbers of packets we've received (for duplicate checking)</summary> public IncomingPacketHistoryCollection PacketArchive = new IncomingPacketHistoryCollection(200); /// <summary>Packets we have sent that need to be ACKed by the client</summary> public UnackedPacketCollection NeedAcks = new UnackedPacketCollection(); /// <summary>ACKs that are queued up, waiting to be sent to the client</summary> public DoubleLocklessQueue<uint> PendingAcks = new DoubleLocklessQueue<uint>(); /// <summary>Current packet sequence number</summary> public int CurrentSequence; /// <summary>Current ping sequence number</summary> public byte CurrentPingSequence; /// <summary>True when this connection is alive, otherwise false</summary> public bool IsConnected = true; /// <summary>True when this connection is paused, otherwise false</summary> public bool IsPaused; /// <summary>Environment.TickCount when the last packet was received for this client</summary> public int TickLastPacketReceived; /// <summary>Smoothed round-trip time. A smoothed average of the round-trip time for sending a /// reliable packet to the client and receiving an ACK</summary> public float SRTT; /// <summary>Round-trip time variance. Measures the consistency of round-trip times</summary> public float RTTVAR; /// <summary>Retransmission timeout. Packets that have not been acknowledged in this number of /// milliseconds or longer will be resent</summary> /// <remarks>Calculated from <seealso cref="SRTT"/> and <seealso cref="RTTVAR"/> using the /// guidelines in RFC 2988</remarks> public int RTO; /// <summary>Number of bytes received since the last acknowledgement was sent out. This is used /// to loosely follow the TCP delayed ACK algorithm in RFC 1122 (4.2.3.2)</summary> public int BytesSinceLastACK; /// <summary>Number of packets received from this client</summary> public int PacketsReceived; /// <summary>Number of packets sent to this client</summary> public int PacketsSent; /// <summary>Number of packets resent to this client</summary> public int PacketsResent; /// <summary>Total byte count of unacked packets sent to this client</summary> public int UnackedBytes; private int m_packetsUnAckReported; /// <summary>Total number of received packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsReceivedReported; /// <summary>Total number of sent packets that we have reported to the OnPacketStats event(s)</summary> private int m_packetsSentReported; /// <summary>Holds the Environment.TickCount value of when the next OnQueueEmpty can be fired</summary> private double m_nextOnQueueEmpty = 0; /// <summary>Throttle bucket for this agent's connection</summary> private AdaptiveTokenBucket m_throttleClient; public AdaptiveTokenBucket FlowThrottle { get { return m_throttleClient; } } /// <summary>Throttle buckets for each packet category</summary> private readonly TokenBucket[] m_throttleCategories; /// <summary>Outgoing queues for throttled packets</summary> private DoubleLocklessQueue<OutgoingPacket>[] m_packetOutboxes = new DoubleLocklessQueue<OutgoingPacket>[THROTTLE_CATEGORY_COUNT]; /// <summary>A container that can hold one packet for each outbox, used to store /// dequeued packets that are being held for throttling</summary> private OutgoingPacket[] m_nextPackets = new OutgoingPacket[THROTTLE_CATEGORY_COUNT]; /// <summary>A reference to the LLUDPServer that is managing this client</summary> private readonly LLUDPServer m_udpServer; /// <summary>Caches packed throttle information</summary> private byte[] m_packedThrottles; private int m_defaultRTO = 1000; // 1sec is the recommendation in the RFC private int m_maxRTO = 60000; public bool m_deliverPackets = true; private float m_burstTime; public int m_lastStartpingTimeMS; public int m_pingMS; public int PingTimeMS { get { if (m_pingMS < 10) return 10; if(m_pingMS > 2000) return 2000; return m_pingMS; } } /// <summary> /// This is the percentage of the udp texture queue to add to the task queue since /// textures are now generally handled through http. /// </summary> private double m_cannibalrate = 0.0; private ClientInfo m_info = new ClientInfo(); /// <summary> /// Default constructor /// </summary> /// <param name="server">Reference to the UDP server this client is connected to</param> /// <param name="rates">Default throttling rates and maximum throttle limits</param> /// <param name="parentThrottle">Parent HTB (hierarchical token bucket) /// that the child throttles will be governed by</param> /// <param name="circuitCode">Circuit code for this connection</param> /// <param name="agentID">AgentID for the connected agent</param> /// <param name="remoteEndPoint">Remote endpoint for this connection</param> /// <param name="defaultRTO"> /// Default retransmission timeout for unacked packets. The RTO will never drop /// beyond this number. /// </param> /// <param name="maxRTO"> /// The maximum retransmission timeout for unacked packets. The RTO will never exceed this number. /// </param> public LLUDPClient( LLUDPServer server, ThrottleRates rates, TokenBucket parentThrottle, uint circuitCode, UUID agentID, IPEndPoint remoteEndPoint, int defaultRTO, int maxRTO) { AgentID = agentID; RemoteEndPoint = remoteEndPoint; CircuitCode = circuitCode; m_udpServer = server; if (defaultRTO != 0) m_defaultRTO = defaultRTO; if (maxRTO != 0) m_maxRTO = maxRTO; m_burstTime = rates.BrustTime; float m_burst = rates.ClientMaxRate * m_burstTime; // Create a token bucket throttle for this client that has the scene token bucket as a parent m_throttleClient = new AdaptiveTokenBucket(parentThrottle, rates.ClientMaxRate, m_burst, rates.AdaptiveThrottlesEnabled); // Create an array of token buckets for this clients different throttle categories m_throttleCategories = new TokenBucket[THROTTLE_CATEGORY_COUNT]; m_cannibalrate = rates.CannibalizeTextureRate; m_burst = rates.Total * rates.BrustTime; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { ThrottleOutPacketType type = (ThrottleOutPacketType)i; // Initialize the packet outboxes, where packets sit while they are waiting for tokens m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>(); // Initialize the token buckets that control the throttling for each category m_throttleCategories[i] = new TokenBucket(m_throttleClient, rates.GetRate(type), m_burst); } // Default the retransmission timeout to one second RTO = m_defaultRTO; // Initialize this to a sane value to prevent early disconnects TickLastPacketReceived = Environment.TickCount & Int32.MaxValue; m_pingMS = (int)(3.0 * server.TickCountResolution); // so filter doesnt start at 0; } /// <summary> /// Shuts down this client connection /// </summary> public void Shutdown() { IsConnected = false; for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { m_packetOutboxes[i].Clear(); m_nextPackets[i] = null; } // pull the throttle out of the scene throttle m_throttleClient.Parent.UnregisterRequest(m_throttleClient); PendingAcks.Clear(); NeedAcks.Clear(); } /// <summary> /// Gets information about this client connection /// </summary> /// <returns>Information about the client connection</returns> public ClientInfo GetClientInfo() { // TODO: This data structure is wrong in so many ways. Locking and copying the entire lists // of pending and needed ACKs for every client every time some method wants information about // this connection is a recipe for poor performance m_info.resendThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Resend].DripRate; m_info.landThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Land].DripRate; m_info.windThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Wind].DripRate; m_info.cloudThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].DripRate; m_info.taskThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Task].DripRate; m_info.assetThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Asset].DripRate; m_info.textureThrottle = (int)m_throttleCategories[(int)ThrottleOutPacketType.Texture].DripRate; m_info.totalThrottle = (int)m_throttleClient.DripRate; return m_info; } /// <summary> /// Modifies the UDP throttles /// </summary> /// <param name="info">New throttling values</param> public void SetClientInfo(ClientInfo info) { // TODO: Allowing throttles to be manually set from this function seems like a reasonable // idea. On the other hand, letting external code manipulate our ACK accounting is not // going to happen throw new NotImplementedException(); } /// <summary> /// Get the total number of pakcets queued for this client. /// </summary> /// <returns></returns> public int GetTotalPacketsQueuedCount() { int total = 0; for (int i = 0; i <= (int)ThrottleOutPacketType.Asset; i++) total += m_packetOutboxes[i].Count; return total; } /// <summary> /// Get the number of packets queued for the given throttle type. /// </summary> /// <returns></returns> /// <param name="throttleType"></param> public int GetPacketsQueuedCount(ThrottleOutPacketType throttleType) { int icat = (int)throttleType; if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT) return m_packetOutboxes[icat].Count; else return 0; } /// <summary> /// Return statistics information about client packet queues. /// </summary> /// <remarks> /// FIXME: This should really be done in a more sensible manner rather than sending back a formatted string. /// </remarks> /// <returns></returns> public string GetStats() { return string.Format( "{0,7} {1,7} {2,7} {3,9} {4,7} {5,7} {6,7} {7,7} {8,7} {9,8} {10,7} {11,7}", Util.EnvironmentTickCountSubtract(TickLastPacketReceived), PacketsReceived, PacketsSent, PacketsResent, UnackedBytes, m_packetOutboxes[(int)ThrottleOutPacketType.Resend].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Land].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Wind].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Cloud].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Task].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Texture].Count, m_packetOutboxes[(int)ThrottleOutPacketType.Asset].Count); } public void SendPacketStats() { PacketStats callback = OnPacketStats; if (callback != null) { int newPacketsReceived = PacketsReceived - m_packetsReceivedReported; int newPacketsSent = PacketsSent - m_packetsSentReported; int newPacketUnAck = UnackedBytes - m_packetsUnAckReported; callback(newPacketsReceived, newPacketsSent, UnackedBytes); m_packetsReceivedReported += newPacketsReceived; m_packetsSentReported += newPacketsSent; m_packetsUnAckReported += newPacketUnAck; } } public void SetThrottles(byte[] throttleData) { SetThrottles(throttleData, 1.0f); } public void SetThrottles(byte[] throttleData, float factor) { byte[] adjData; int pos = 0; if (!BitConverter.IsLittleEndian) { byte[] newData = new byte[7 * 4]; Buffer.BlockCopy(throttleData, 0, newData, 0, 7 * 4); for (int i = 0; i < 7; i++) Array.Reverse(newData, i * 4, 4); adjData = newData; } else { adjData = throttleData; } // 0.125f converts from bits to bytes float scale = 0.125f * factor; int resend = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int land = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int wind = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int cloud = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int task = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int texture = (int)(BitConverter.ToSingle(adjData, pos) * scale); pos += 4; int asset = (int)(BitConverter.ToSingle(adjData, pos) * scale); // Make sure none of the throttles are set below our packet MTU, // otherwise a throttle could become permanently clogged /* now using floats resend = Math.Max(resend, LLUDPServer.MTU); land = Math.Max(land, LLUDPServer.MTU); wind = Math.Max(wind, LLUDPServer.MTU); cloud = Math.Max(cloud, LLUDPServer.MTU); task = Math.Max(task, LLUDPServer.MTU); texture = Math.Max(texture, LLUDPServer.MTU); asset = Math.Max(asset, LLUDPServer.MTU); */ // Since most textures are now delivered through http, make it possible // to cannibalize some of the bw from the texture throttle to use for // the task queue (e.g. object updates) task = task + (int)(m_cannibalrate * texture); texture = (int)((1 - m_cannibalrate) * texture); int total = resend + land + wind + cloud + task + texture + asset; float m_burst = total * m_burstTime; if (ThrottleDebugLevel > 0) { m_log.DebugFormat( "[LLUDPCLIENT]: {0} is setting throttles in {1} to Resend={2}, Land={3}, Wind={4}, Cloud={5}, Task={6}, Texture={7}, Asset={8}, TOTAL = {9}", AgentID, m_udpServer.Scene.Name, resend, land, wind, cloud, task, texture, asset, total); } TokenBucket bucket; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Resend]; bucket.RequestedDripRate = resend; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Land]; bucket.RequestedDripRate = land; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Wind]; bucket.RequestedDripRate = wind; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Cloud]; bucket.RequestedDripRate = cloud; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Asset]; bucket.RequestedDripRate = asset; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Task]; bucket.RequestedDripRate = task; bucket.RequestedBurst = m_burst; bucket = m_throttleCategories[(int)ThrottleOutPacketType.Texture]; bucket.RequestedDripRate = texture; bucket.RequestedBurst = m_burst; // Reset the packed throttles cached data m_packedThrottles = null; } public byte[] GetThrottlesPacked(float multiplier) { byte[] data = m_packedThrottles; if (data == null) { float rate; data = new byte[7 * 4]; int i = 0; // multiply by 8 to convert bytes back to bits multiplier *= 8; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Resend].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Land].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Wind].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Cloud].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Task].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Texture].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; rate = (float)m_throttleCategories[(int)ThrottleOutPacketType.Asset].RequestedDripRate * multiplier; Buffer.BlockCopy(Utils.FloatToBytes(rate), 0, data, i, 4); i += 4; m_packedThrottles = data; } return data; } public int GetCatBytesCanSend(ThrottleOutPacketType cat, int timeMS) { int icat = (int)cat; if (icat > 0 && icat < THROTTLE_CATEGORY_COUNT) { TokenBucket bucket = m_throttleCategories[icat]; return bucket.GetCatBytesCanSend(timeMS); } else return 0; } /// <summary> /// Queue an outgoing packet if appropriate. /// </summary> /// <param name="packet"></param> /// <param name="forceQueue">Always queue the packet if at all possible.</param> /// <returns> /// true if the packet has been queued, /// false if the packet has not been queued and should be sent immediately. /// </returns> public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue) { return EnqueueOutgoing(packet, forceQueue, false); } public bool EnqueueOutgoing(OutgoingPacket packet, bool forceQueue, bool highPriority) { int category = (int)packet.Category; if (category >= 0 && category < m_packetOutboxes.Length) { DoubleLocklessQueue<OutgoingPacket> queue = m_packetOutboxes[category]; if (m_deliverPackets == false) { queue.Enqueue(packet, highPriority); return true; } TokenBucket bucket = m_throttleCategories[category]; // Don't send this packet if queue is not empty if (queue.Count > 0 || m_nextPackets[category] != null) { queue.Enqueue(packet, highPriority); return true; } if (!forceQueue && bucket.CheckTokens(packet.Buffer.DataLength)) { // enough tokens so it can be sent imediatly by caller bucket.RemoveTokens(packet.Buffer.DataLength); return false; } else { // Force queue specified or not enough tokens in the bucket, queue this packet queue.Enqueue(packet, highPriority); return true; } } else { // We don't have a token bucket for this category, so it will not be queued return false; } } /// <summary> /// Loops through all of the packet queues for this client and tries to send /// an outgoing packet from each, obeying the throttling bucket limits /// </summary> /// /// <remarks> /// Packet queues are inspected in ascending numerical order starting from 0. Therefore, queues with a lower /// ThrottleOutPacketType number will see their packet get sent first (e.g. if both Land and Wind queues have /// packets, then the packet at the front of the Land queue will be sent before the packet at the front of the /// wind queue). /// /// This function is only called from a synchronous loop in the /// UDPServer so we don't need to bother making this thread safe /// </remarks> /// /// <returns>True if any packets were sent, otherwise false</returns> public bool DequeueOutgoing() { // if (m_deliverPackets == false) return false; OutgoingPacket packet = null; DoubleLocklessQueue<OutgoingPacket> queue; TokenBucket bucket; bool packetSent = false; ThrottleOutPacketTypeFlags emptyCategories = 0; //string queueDebugOutput = String.Empty; // Serious debug business for (int i = 0; i < THROTTLE_CATEGORY_COUNT; i++) { bucket = m_throttleCategories[i]; //queueDebugOutput += m_packetOutboxes[i].Count + " "; // Serious debug business if (m_nextPackets[i] != null) { // This bucket was empty the last time we tried to send a packet, // leaving a dequeued packet still waiting to be sent out. Try to // send it again OutgoingPacket nextPacket = m_nextPackets[i]; if (bucket.RemoveTokens(nextPacket.Buffer.DataLength)) { // Send the packet m_udpServer.SendPacketFinal(nextPacket); m_nextPackets[i] = null; packetSent = true; if (m_packetOutboxes[i].Count < 5) emptyCategories |= CategoryToFlag(i); } } else { // No dequeued packet waiting to be sent, try to pull one off // this queue queue = m_packetOutboxes[i]; if (queue != null) { bool success = false; try { success = queue.Dequeue(out packet); } catch { m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>(); } if (success) { // A packet was pulled off the queue. See if we have // enough tokens in the bucket to send it out if (bucket.RemoveTokens(packet.Buffer.DataLength)) { // Send the packet m_udpServer.SendPacketFinal(packet); packetSent = true; if (queue.Count < 5) emptyCategories |= CategoryToFlag(i); } else { // Save the dequeued packet for the next iteration m_nextPackets[i] = packet; } } else { // No packets in this queue. Fire the queue empty callback // if it has not been called recently emptyCategories |= CategoryToFlag(i); } } else { m_packetOutboxes[i] = new DoubleLocklessQueue<OutgoingPacket>(); emptyCategories |= CategoryToFlag(i); } } } if (emptyCategories != 0) BeginFireQueueEmpty(emptyCategories); //m_log.Info("[LLUDPCLIENT]: Queues: " + queueDebugOutput); // Serious debug business return packetSent; } /// <summary> /// Called when an ACK packet is received and a round-trip time for a /// packet is calculated. This is used to calculate the smoothed /// round-trip time, round trip time variance, and finally the /// retransmission timeout /// </summary> /// <param name="r">Round-trip time of a single packet and its /// acknowledgement</param> public void UpdateRoundTrip(float r) { const float ALPHA = 0.125f; const float BETA = 0.25f; const float K = 4.0f; if (RTTVAR == 0.0f) { // First RTT measurement SRTT = r; RTTVAR = r * 0.5f; } else { // Subsequence RTT measurement RTTVAR = (1.0f - BETA) * RTTVAR + BETA * Math.Abs(SRTT - r); SRTT = (1.0f - ALPHA) * SRTT + ALPHA * r; } int rto = (int)(SRTT + Math.Max(m_udpServer.TickCountResolution, K * RTTVAR)); // Clamp the retransmission timeout to manageable values rto = Utils.Clamp(rto, m_defaultRTO, m_maxRTO); RTO = rto; //if (RTO != rto) // m_log.Debug("[LLUDPCLIENT]: Setting RTO to " + RTO + "ms from " + rto + "ms with an RTTVAR of " + //RTTVAR + " based on new RTT of " + r + "ms"); } /// <summary> /// Exponential backoff of the retransmission timeout, per section 5.5 /// of RFC 2988 /// </summary> public void BackoffRTO() { // Reset SRTT and RTTVAR, we assume they are bogus since things // didn't work out and we're backing off the timeout SRTT = 0.0f; RTTVAR = 0.0f; // Double the retransmission timeout RTO = Math.Min(RTO * 2, m_maxRTO); } const double MIN_CALLBACK_MS = 20.0; private bool m_isQueueEmptyRunning; /// <summary> /// Does an early check to see if this queue empty callback is already /// running, then asynchronously firing the event /// </summary> /// <param name="categories">Throttle categories to fire the callback for</param> private void BeginFireQueueEmpty(ThrottleOutPacketTypeFlags categories) { if (!m_isQueueEmptyRunning) { if (!HasUpdates(categories)) return; double start = Util.GetTimeStampMS(); if (start < m_nextOnQueueEmpty) return; m_isQueueEmptyRunning = true; m_nextOnQueueEmpty = start + MIN_CALLBACK_MS; // Asynchronously run the callback if (m_udpServer.OqrEngine.IsRunning) m_udpServer.OqrEngine.QueueJob(AgentID.ToString(), () => FireQueueEmpty(categories)); else Util.FireAndForget(FireQueueEmpty, categories, "LLUDPClient.BeginFireQueueEmpty"); } } /// <summary> /// Fires the OnQueueEmpty callback and sets the minimum time that it /// can be called again /// </summary> /// <param name="o">Throttle categories to fire the callback for, /// stored as an object to match the WaitCallback delegate /// signature</param> public void FireQueueEmpty(object o) { ThrottleOutPacketTypeFlags categories = (ThrottleOutPacketTypeFlags)o; QueueEmpty callback = OnQueueEmpty; if (callback != null) { // if (m_udpServer.IsRunningOutbound) // { try { callback(categories); } catch (Exception e) { m_log.Error("[LLUDPCLIENT]: OnQueueEmpty(" + categories + ") threw an exception: " + e.Message, e); } // } } m_isQueueEmptyRunning = false; } internal void ForceThrottleSetting(int throttle, int setting) { if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT) m_throttleCategories[throttle].RequestedDripRate = Math.Max(setting, LLUDPServer.MTU); } internal int GetThrottleSetting(int throttle) { if (throttle > 0 && throttle < THROTTLE_CATEGORY_COUNT) return (int)m_throttleCategories[throttle].RequestedDripRate; else return 0; } /// <summary> /// Converts a <seealso cref="ThrottleOutPacketType"/> integer to a /// flag value /// </summary> /// <param name="i">Throttle category to convert</param> /// <returns>Flag representation of the throttle category</returns> private static ThrottleOutPacketTypeFlags CategoryToFlag(int i) { ThrottleOutPacketType category = (ThrottleOutPacketType)i; /* * Land = 1, /// <summary>Wind data</summary> Wind = 2, /// <summary>Cloud data</summary> Cloud = 3, /// <summary>Any packets that do not fit into the other throttles</summary> Task = 4, /// <summary>Texture assets</summary> Texture = 5, /// <summary>Non-texture assets</summary> Asset = 6, */ switch (category) { case ThrottleOutPacketType.Land: return ThrottleOutPacketTypeFlags.Land; case ThrottleOutPacketType.Wind: return ThrottleOutPacketTypeFlags.Wind; case ThrottleOutPacketType.Cloud: return ThrottleOutPacketTypeFlags.Cloud; case ThrottleOutPacketType.Task: return ThrottleOutPacketTypeFlags.Task; case ThrottleOutPacketType.Texture: return ThrottleOutPacketTypeFlags.Texture; case ThrottleOutPacketType.Asset: return ThrottleOutPacketTypeFlags.Asset; default: return 0; } } } public class DoubleLocklessQueue<T> : OpenSim.Framework.LocklessQueue<T> { OpenSim.Framework.LocklessQueue<T> highQueue = new OpenSim.Framework.LocklessQueue<T>(); public override int Count { get { return base.Count + highQueue.Count; } } public override bool Dequeue(out T item) { if (highQueue.Dequeue(out item)) return true; return base.Dequeue(out item); } public void Enqueue(T item, bool highPriority) { if (highPriority) highQueue.Enqueue(item); else Enqueue(item); } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Newtonsoft.Json.Linq; using Mandrill.Model; using Xunit; using Xunit.Abstractions; namespace Tests { [Trait("Category", "messages")] [Collection("messages")] public class Messages : IntegrationTest { public string FromEmail => "mandrill.net@" + (Environment.GetEnvironmentVariable("MANDRILL_SENDING_DOMAIN") ?? "test.mandrillapp.com"); public Messages(ITestOutputHelper output) : base(output) { } void AssertResults(IEnumerable<MandrillSendMessageResponse> result) { foreach (var response in result) { if (response.Status == MandrillSendMessageResponseStatus.Invalid) { Assert.True(false, "invalid email: " + response.RejectReason); } if (response.Status == MandrillSendMessageResponseStatus.Rejected && response.RejectReason == "unsigned") { Output.WriteLine("unsigned sending domain"); break; } if (response.Status == MandrillSendMessageResponseStatus.Rejected) { Assert.True(false, "rejected email: " + response.RejectReason); } if (response.Status == MandrillSendMessageResponseStatus.Queued || response.Status == MandrillSendMessageResponseStatus.Sent) { break; } Assert.True(false, "Unexptected status:" + response.Status); } } [Trait("Category", "messages/cancel_scheduled.json")] public class CancelScheduled : Messages { public CancelScheduled(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_cancel_scheduled() { var list = await Api.Messages.ListScheduledAsync(); var schedule = list.LastOrDefault(); if (schedule != null) { var result = await Api.Messages.CancelScheduledAsync(schedule.Id); result.Id.Should().Be(schedule.Id); } else { Output.WriteLine("no scheduled results"); } } } [Trait("Category", "messages/content.json")] public class Content : Messages { public Content(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_retrieve_content() { var results = await Api.Messages.SearchAsync(null, DateTime.Today.AddDays(-1)); //the api doesn't return results immediately, it may return no results. //Also, the content may not be around > 24 hrs var found = results.Where(x => x.Ts > DateTime.UtcNow.AddHours(-24)) .OrderBy(x => x.Ts) .FirstOrDefault(x => x.State == MandrillMessageState.Sent); if (found != null) { var result = await Api.Messages.ContentAsync(found.Id); result.Should().NotBeNull(); var content = result.Html ?? result.Text; content.Should().NotBeNullOrWhiteSpace(); } else { Output.WriteLine("no results were found yet, try again in a few minutes"); } } [Fact] public async Task Throws_when_not_found() { var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.ContentAsync(Guid.NewGuid().ToString("N"))); mandrillException.Name.Should().Be("Unknown_Message"); } [Fact] public async Task Throws_when_not_found_sync() { var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.ContentAsync(Guid.NewGuid().ToString("N"))); mandrillException.Name.Should().Be("Unknown_Message"); Output.WriteLine(mandrillException.ToString()); } } [Trait("Category", "messages/info.json")] public class Info : Messages { public Info(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_retrieve_info() { var results = await Api.Messages.SearchAsync("email:mandrilldotnet.org"); //the api doesn't return results immediately, it may return no results var found = results.OrderBy(x => x.Ts).FirstOrDefault(); if (found != null) { var result = await Api.Messages.InfoAsync(found.Id); result.Should().NotBeNull(); result.Id.Should().Be(found.Id); } else { Output.WriteLine("no results were found yet, try again in a few minutes"); } } [Fact] public async Task Throws_when_not_found() { var mandrillException = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.InfoAsync(Guid.NewGuid().ToString("N"))); mandrillException.Name.Should().Be("Unknown_Message"); } } [Trait("Category", "messages/list_scheduled.json")] public class ListScheduled : Messages { public ListScheduled(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_list_scheduled() { var result = await Api.Messages.ListScheduledAsync(); result.Should().NotBeNull(); result.Count.Should().BeGreaterOrEqualTo(0); } } [Trait("Category", "messages/parse.json")] public class Parse : Messages { public Parse(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_parse_raw_message() { var rawMessage = $"From: {FromEmail}\nTo: [email protected]\nSubject: Some Subject\n\nSome content."; var result = await Api.Messages.ParseAsync(rawMessage); result.Should().NotBeNull(); result.FromEmail.Should().Be(FromEmail); result.To[0].Email.Should().Be("[email protected]"); result.Subject.Should().Be("Some Subject"); result.Text.Should().Be("Some content."); } [Fact] public async Task Can_parse_full_raw_message_headers() { var rawMessage = @"Delivered-To: [email protected] Received: by 10.36.81.3 with SMTP id e3cs239nzb; Tue, 29 Mar 2005 15:11:47 -0800 (PST) Return-Path: Received: from mail.emailprovider.com (mail.emailprovider.com [111.111.11.111]) by mx.gmail.com with SMTP id h19si826631rnb.2005.03.29.15.11.46; Tue, 29 Mar 2005 15:11:47 -0800 (PST) Message-ID: <[email protected]> Reply-To: [email protected] Received: from [11.11.111.111] by mail.emailprovider.com via HTTP; Tue, 29 Mar 2005 15:11:45 PST Date: Tue, 29 Mar 2005 15:11:45 -0800 (PST) From: Mr Jones Subject: Hello To: Mr Smith "; var result = await Api.Messages.ParseAsync(rawMessage); result.Should().NotBeNull(); result.Headers["Received"].Should().BeOfType<JArray>(); ((JArray)result.Headers["Received"]).Count.Should().Be(3); result.Headers["Delivered-To"].Should().BeOfType<string>(); result.Headers["Delivered-To"].Should().Be("[email protected]"); result.ReplyTo.Should().Be("[email protected]"); } } [Trait("Category", "messages/reschedule.json")] public class Reschedule : Messages { public Reschedule(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_reschedule() { var list = await Api.Messages.ListScheduledAsync(); var schedule = list.LastOrDefault(); if (schedule != null) { var sendAtUtc = DateTime.UtcNow.AddHours(1); sendAtUtc = new DateTime(sendAtUtc.Year, sendAtUtc.Month, sendAtUtc.Day, sendAtUtc.Hour, sendAtUtc.Minute, sendAtUtc.Second, 0, DateTimeKind.Utc); var result = await Api.Messages.RescheduleAsync(schedule.Id, sendAtUtc); result.SendAt.Should().Be(sendAtUtc); } else { Output.WriteLine("no scheduled messages found."); } } [Fact] public async Task Throws_on_missing_args() { await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.RescheduleAsync(null, DateTime.UtcNow)); } [Fact] public async Task Throws_on_invalid_date() { await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.RescheduleAsync("foo", DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local))); } } [Trait("Category", "messages/search.json")] public class Search : Messages { public Search(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_search_all_params() { var results = await Api.Messages.SearchAsync("email:mandrilldotnet.org", DateTime.Today.AddDays(-1), DateTime.Today.AddDays(1), new string[0], new[] { FromEmail }, new[] { ApiKey }, 10); //the api doesn't return results immediately, it may return no results results.Count.Should().BeLessOrEqualTo(10); foreach (var result in results) { result.Id.Should().NotBeEmpty(); } if (results.Count == 0) { Output.WriteLine("no results were found yet, try again in a few minutes"); } } [Fact] public async Task Can_search_query() { var results = await Api.Messages.SearchAsync("email:mandrilldotnet.org", limit: 1); //the api doesn't return results immediately, it may return no results results.Count.Should().BeLessOrEqualTo(1); foreach (var result in results) { result.Id.Should().NotBeEmpty(); } if (results.Count == 0) { Output.WriteLine("no results were found yet, try again in a few minutes"); } } } [Trait("Category", "messages/search_time_series.json")] public class SearchTimeSeries : Messages { public SearchTimeSeries(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_search_all_params() { var results = await Api.Messages.SearchTimeSeriesAsync("email:mandrilldotnet.org", DateTime.Today.AddDays(-1), DateTime.Today.AddDays(1), new string[0], new[] { FromEmail }); foreach (var result in results) { result.Clicks.Should().BeGreaterOrEqualTo(0); } if (results.Count == 0) { Output.WriteLine("no results were found yet, try again in a few minutes"); } } [Fact] public async Task Can_search_open_query() { var results = await Api.Messages.SearchTimeSeriesAsync(null); foreach (var result in results) { result.Clicks.Should().BeGreaterOrEqualTo(0); } if (results.Count == 0) { Output.WriteLine("no results were found yet, try again in a few minutes"); } } } [Trait("Category", "messages/send.json")] public class Send : Messages { public Send(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_send_message() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send", "mandrill-net" }, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]"), new MandrillMailAddress("[email protected]", "A test") }, Text = "This is a test", Html = @"<html> <head> <title>a test</title> </head> <body> <p>this is a test</p> <img src=""cid:mandrill_logo""> </body> </html>" }; message.Images.Add(new MandrillImage("image/png", "mandrill_logo", TestData.PngImage)); message.Attachments.Add(new MandrillAttachment("text/plain", "message.txt", Encoding.UTF8.GetBytes("This is an attachment.\n"))); var result = await Api.Messages.SendAsync(message); result.Should().HaveCount(2); AssertResults(result); } [Fact] public async Task Can_throw_errors_when_error_response() { var invalidSubaccount = Guid.NewGuid().ToString("N"); var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send-invalid" }, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]") }, Text = "This is a test", Subaccount = invalidSubaccount }; var result = await Assert.ThrowsAsync<MandrillException>(() => Api.Messages.SendAsync(message)); result.Should().NotBeNull(); result.Name.Should().Be("Unknown_Subaccount"); result.Message.Should().Contain(invalidSubaccount); } [Fact] public async Task Can_send_async() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string> { "test-send", "mandrill-net" }, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]") }, Text = "This is a test", }; var result = await Api.Messages.SendAsync(message, true); result.Should().HaveCount(1); AssertResults(result); } [Fact] public async Task Throws_on_missing_args() { await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendAsync(null, true)); } [Fact] public async Task Can_send_scheduled() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send", "mandrill-net" }, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]") }, Text = "This is a test", }; var sendAtUtc = DateTime.UtcNow.AddHours(1); var result = await Api.Messages.SendAsync(message, sendAtUtc: sendAtUtc); result.Should().HaveCount(1); result[0].Email.Should().Be("[email protected]"); result[0].Status.Should().Be(MandrillSendMessageResponseStatus.Scheduled); } [Fact] public async Task Throws_if_scheduled_is_not_utc() { var message = new MandrillMessage(); var sendAtLocal = DateTime.SpecifyKind(DateTime.Now.AddHours(1), DateTimeKind.Local); var result = await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.SendAsync(message, sendAtUtc: sendAtLocal)); result.ParamName.Should().Be("sendAtUtc"); } } [Trait("Category", "messages/send_raw.json")] public class SendRaw : Messages { public SendRaw(ITestOutputHelper output) : base(output) { } [Fact] public async Task Can_send_raw_message() { var rawMessage = $"From: {FromEmail}\nTo: [email protected]\nSubject: Some Subject\n\nSome content."; var fromEmail = FromEmail; var fromName = "From Name"; var to = new[] { "[email protected]" }; bool async = false; string ipPool = "Main Pool"; DateTime? sendAt = null; string returnPathDomain = null; var result = await Api.Messages.SendRawAsync(rawMessage, fromEmail, fromName, to, async, ipPool, sendAt, returnPathDomain); result.Should().HaveCount(1); AssertResults(result); } } [Trait("Category", "messages/send_template.json")] public class SendTemplate : Messages { protected string TestTemplateName; public SendTemplate(ITestOutputHelper output) : base(output) { TestTemplateName = Guid.NewGuid().ToString(); var result = Api.Templates.AddAsync(TestTemplateName, TemplateContent.Code, TemplateContent.Text, true).GetAwaiter().GetResult(); result.Should().NotBeNull(); } public override void Dispose() { var result = Api.Templates.DeleteAsync(TestTemplateName).GetAwaiter().GetResult(); result.Should().NotBeNull(); } [Fact] public async Task Can_send_template() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send-template", "mandrill-net" }, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]", "Test1 User"), new MandrillMailAddress("[email protected]", "Test2 User") }, }; message.AddGlobalMergeVars("ORDERDATE", string.Format("{0:d}", DateTime.UtcNow)); message.AddRcptMergeVars("[email protected]", "INVOICEDETAILS", "invoice for [email protected]"); message.AddRcptMergeVars("[email protected]", "INVOICEDETAILS", "invoice for [email protected]"); var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName); result.Should().HaveCount(2); AssertResults(result); } [Fact] public async Task Throws_on_missing_args0() { var result = await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendTemplateAsync(null, TestTemplateName)); } [Fact] public async Task Throws_on_missing_args1() { var result = await Assert.ThrowsAsync<ArgumentNullException>(() => Api.Messages.SendTemplateAsync(new MandrillMessage(), null)); } [Fact] public async Task Throws_on_invalid_date_type() { var result = await Assert.ThrowsAsync<ArgumentException>(() => Api.Messages.SendTemplateAsync(new MandrillMessage(), TestTemplateName, sendAtUtc: DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Local))); } } [Trait("Category", "messages/send_template.json"), Trait("Category", "handlebars")] public class SendTemplate_Handlebars : Messages { protected string TestTemplateName; public SendTemplate_Handlebars(ITestOutputHelper output) : base(output) { TestTemplateName = Guid.NewGuid().ToString(); var result = Api.Templates.AddAsync(TestTemplateName, TemplateContent.HandleBarCode, null, true).GetAwaiter().GetResult(); result.Should().NotBeNull(); } public override void Dispose() { var result = Api.Templates.DeleteAsync(TestTemplateName).GetAwaiter().GetResult(); result.Should().NotBeNull(); base.Dispose(); } [Fact] public async Task Can_send_template_string_dictionary() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" }, MergeLanguage = MandrillMessageMergeLanguage.Handlebars, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]", "Test1 User"), new MandrillMailAddress("[email protected]", "Test2 User") }, }; var data1 = new[] { new Dictionary<string, object> { {"sku", "APL43"}, {"name", "apples"}, {"description", "Granny Smith Apples"}, {"price", "0.20"}, {"qty", "8"}, {"ordPrice", "1.60"}, }, new Dictionary<string, object> { {"sku", "ORA44"}, {"name", "Oranges"}, {"description", "Blood Oranges"}, {"price", "0.30"}, {"qty", "3"}, {"ordPrice", "0.93"}, } }; var data2 = new[] { new Dictionary<string, object> { {"sku", "APL54"}, {"name", "apples"}, {"description", "Red Delicious Apples"}, {"price", "0.22"}, {"qty", "9"}, {"ordPrice", "1.98"}, }, new Dictionary<string, object> { {"sku", "ORA53"}, {"name", "Oranges"}, {"description", "Sunkist Oranges"}, {"price", "0.20"}, {"qty", "1"}, {"ordPrice", "0.20"}, } }; message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d")); message.AddRcptMergeVars("[email protected]", "PRODUCTS", data1); message.AddRcptMergeVars("[email protected]", "PRODUCTS", data2); var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName); result.Should().HaveCount(2); AssertResults(result); } [Fact] public async Task Can_send_template_object_list() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" }, MergeLanguage = MandrillMessageMergeLanguage.Handlebars, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]", "Test1 User"), new MandrillMailAddress("[email protected]", "Test2 User") }, }; var data1 = new[] { new Dictionary<string, object> { {"sku", "APL43"}, {"name", "apples"}, {"description", "Granny Smith Apples"}, {"price", 0.20}, {"qty", 8}, {"ordPrice", 1.60}, }, new Dictionary<string, object> { {"sku", "ORA44"}, {"name", "Oranges"}, {"description", "Blood Oranges"}, {"price", 0.30}, {"qty", 3}, {"ordPrice", 0.93}, } }; var data2 = new[] { new Dictionary<string, object> { {"sku", "APL54"}, {"name", "apples"}, {"description", "Red Delicious Apples"}, {"price", 0.22}, {"qty", 9}, {"ordPrice", 1.98}, }, new Dictionary<string, object> { {"sku", "ORA53"}, {"name", "Oranges"}, {"description", "Sunkist Oranges"}, {"price", 0.20}, {"qty", 1}, {"ordPrice", 0.20}, } }; message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d")); message.AddRcptMergeVars("[email protected]", "PRODUCTS", data1); message.AddRcptMergeVars("[email protected]", "PRODUCTS", data2); var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName); result.Should().HaveCount(2); AssertResults(result); } [Fact] public async Task Can_send_template_dynamic() { var message = new MandrillMessage { FromEmail = FromEmail, Subject = "test", Tags = new List<string>() { "test-send-template", "mandrill-net", "handlebars" }, MergeLanguage = MandrillMessageMergeLanguage.Handlebars, To = new List<MandrillMailAddress>() { new MandrillMailAddress("[email protected]", "Test1 User"), new MandrillMailAddress("[email protected]", "Test2 User") }, }; dynamic item1 = new ExpandoObject(); item1.sku = "APL54"; item1.name = "apples"; item1.description = "Red Dynamic Apples"; item1.price = 0.22; item1.qty = 9; item1.ordPrice = 1.98; item1.tags = new { id = "tag1", enabled = true }; dynamic item2 = new ExpandoObject(); item2.sku = "ORA54"; item2.name = "oranges"; item2.description = "Dynamic Oranges"; item2.price = 0.33; item2.qty = 8; item2.ordPrice = 2.00; item2.tags = new { id = "tag2", enabled = false }; message.AddGlobalMergeVars("ORDERDATE", DateTime.UtcNow.ToString("d")); message.AddGlobalMergeVars("PRODUCTS", new[] { item1, item2 }); var result = await Api.Messages.SendTemplateAsync(message, TestTemplateName); result.Should().HaveCount(2); AssertResults(result); } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections; using System.Threading; using System.Linq; namespace Newtonsoft.Json.Utilities { internal interface IWrappedDictionary : IDictionary { object UnderlyingDictionary { get; } } internal class DictionaryWrapper<TKey, TValue> : IDictionary<TKey, TValue>, IWrappedDictionary { private readonly IDictionary _dictionary; private readonly IDictionary<TKey, TValue> _genericDictionary; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) private readonly IReadOnlyDictionary<TKey, TValue> _readOnlyDictionary; //#endif private object _syncRoot; public DictionaryWrapper(IDictionary dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _dictionary = dictionary; } public DictionaryWrapper(IDictionary<TKey, TValue> dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _genericDictionary = dictionary; } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) public DictionaryWrapper(IReadOnlyDictionary<TKey, TValue> dictionary) { ValidationUtils.ArgumentNotNull(dictionary, "dictionary"); _readOnlyDictionary = dictionary; } //#endif public void Add(TKey key, TValue value) { if (_dictionary != null) _dictionary.Add(key, value); else if (_genericDictionary != null) _genericDictionary.Add(key, value); else throw new NotSupportedException(); } public bool ContainsKey(TKey key) { if (_dictionary != null) return _dictionary.Contains(key); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.ContainsKey(key); //#endif else return _genericDictionary.ContainsKey(key); } public ICollection<TKey> Keys { get { if (_dictionary != null) return _dictionary.Keys.Cast<TKey>().ToList(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Keys.ToList(); //#endif else return _genericDictionary.Keys; } } public bool Remove(TKey key) { if (_dictionary != null) { if (_dictionary.Contains(key)) { _dictionary.Remove(key); return true; } else { return false; } } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) { throw new NotSupportedException(); } //#endif else { return _genericDictionary.Remove(key); } } public bool TryGetValue(TKey key, out TValue value) { if (_dictionary != null) { if (!_dictionary.Contains(key)) { value = default(TValue); return false; } else { value = (TValue)_dictionary[key]; return true; } } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) { throw new NotSupportedException(); } //#endif else { return _genericDictionary.TryGetValue(key, out value); } } public ICollection<TValue> Values { get { if (_dictionary != null) return _dictionary.Values.Cast<TValue>().ToList(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Values.ToList(); //#endif else return _genericDictionary.Values; } } public TValue this[TKey key] { get { if (_dictionary != null) return (TValue)_dictionary[key]; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary[key]; //#endif else return _genericDictionary[key]; } set { if (_dictionary != null) _dictionary[key] = value; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary[key] = value; } } public void Add(KeyValuePair<TKey, TValue> item) { if (_dictionary != null) ((IList)_dictionary).Add(item); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else if (_genericDictionary != null) _genericDictionary.Add(item); } public void Clear() { if (_dictionary != null) _dictionary.Clear(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary.Clear(); } public bool Contains(KeyValuePair<TKey, TValue> item) { if (_dictionary != null) return ((IList)_dictionary).Contains(item); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Contains(item); //#endif else return _genericDictionary.Contains(item); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (_dictionary != null) { foreach (DictionaryEntry item in _dictionary) { array[arrayIndex++] = new KeyValuePair<TKey, TValue>((TKey)item.Key, (TValue)item.Value); } } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) { throw new NotSupportedException(); } //#endif else { _genericDictionary.CopyTo(array, arrayIndex); } } public int Count { get { if (_dictionary != null) return _dictionary.Count; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Count; //#endif else return _genericDictionary.Count; } } public bool IsReadOnly { get { if (_dictionary != null) return _dictionary.IsReadOnly; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return true; //#endif else return _genericDictionary.IsReadOnly; } } public bool Remove(KeyValuePair<TKey, TValue> item) { if (_dictionary != null) { if (_dictionary.Contains(item.Key)) { object value = _dictionary[item.Key]; if (object.Equals(value, item.Value)) { _dictionary.Remove(item.Key); return true; } else { return false; } } else { return true; } } //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) { throw new NotSupportedException(); } //#endif else { return _genericDictionary.Remove(item); } } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (_dictionary != null) return _dictionary.Cast<DictionaryEntry>().Select(de => new KeyValuePair<TKey, TValue>((TKey)de.Key, (TValue)de.Value)).GetEnumerator(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.GetEnumerator(); //#endif else return _genericDictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IDictionary.Add(object key, object value) { if (_dictionary != null) _dictionary.Add(key, value); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary.Add((TKey)key, (TValue)value); } object IDictionary.this[object key] { get { if (_dictionary != null) return _dictionary[key]; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary[(TKey)key]; //#endif else return _genericDictionary[(TKey)key]; } set { if (_dictionary != null) _dictionary[key] = value; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary[(TKey)key] = (TValue)value; } } private struct DictionaryEnumerator<TEnumeratorKey, TEnumeratorValue> : IDictionaryEnumerator { private readonly IEnumerator<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> _e; public DictionaryEnumerator(IEnumerator<KeyValuePair<TEnumeratorKey, TEnumeratorValue>> e) { ValidationUtils.ArgumentNotNull(e, "e"); _e = e; } public DictionaryEntry Entry { get { return (DictionaryEntry)Current; } } public object Key { get { return Entry.Key; } } public object Value { get { return Entry.Value; } } public object Current { get { return new DictionaryEntry(_e.Current.Key, _e.Current.Value); } } public bool MoveNext() { return _e.MoveNext(); } public void Reset() { _e.Reset(); } } IDictionaryEnumerator IDictionary.GetEnumerator() { if (_dictionary != null) return _dictionary.GetEnumerator(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return new DictionaryEnumerator<TKey, TValue>(_readOnlyDictionary.GetEnumerator()); //#endif else return new DictionaryEnumerator<TKey, TValue>(_genericDictionary.GetEnumerator()); } bool IDictionary.Contains(object key) { if (_genericDictionary != null) return _genericDictionary.ContainsKey((TKey)key); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.ContainsKey((TKey)key); //#endif else return _dictionary.Contains(key); } bool IDictionary.IsFixedSize { get { if (_genericDictionary != null) return false; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return true; //#endif else return _dictionary.IsFixedSize; } } ICollection IDictionary.Keys { get { if (_genericDictionary != null) return _genericDictionary.Keys.ToList(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Keys.ToList(); //#endif else return _dictionary.Keys; } } public void Remove(object key) { if (_dictionary != null) _dictionary.Remove(key); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary.Remove((TKey)key); } ICollection IDictionary.Values { get { if (_genericDictionary != null) return _genericDictionary.Values.ToList(); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary.Values.ToList(); //#endif else return _dictionary.Values; } } void ICollection.CopyTo(Array array, int index) { if (_dictionary != null) _dictionary.CopyTo(array, index); //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) throw new NotSupportedException(); //#endif else _genericDictionary.CopyTo((KeyValuePair<TKey, TValue>[])array, index); } bool ICollection.IsSynchronized { get { if (_dictionary != null) return _dictionary.IsSynchronized; else return false; } } object ICollection.SyncRoot { get { if (_syncRoot == null) Interlocked.CompareExchange(ref _syncRoot, new object(), null); return _syncRoot; } } public object UnderlyingDictionary { get { if (_dictionary != null) return _dictionary; //#if !(NET40 || NET35 || NET20 || SILVERLIGHT || WINDOWS_PHONE || PORTABLE40) else if (_readOnlyDictionary != null) return _readOnlyDictionary; //#endif else return _genericDictionary; } } } } #endif
// ******************************************************************************************************** // Product Name: DotSpatial.Data.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created Before 2010. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // | Name | Date | Comments // |----------------------|-------------|----------------------------------------------------------------- // | Ted Dunsford | 6/30/2010 | Moved to DotSpatial // ******************************************************************************************************** using System; namespace DotSpatial.Data { /// <summary> /// This handles the methodology of progress messaging in one place to make it easier to update. /// </summary> public class ProgressMeter { private string _baseMessage; private double _endValue = 100; private int _oldProg = -1; // the previous progress level private int _prog; // the current progress level private IProgressHandler _progressHandler; private bool _silent; private double _startValue; private int _stepPercent = 1; private double _value; #region Constructors /// <summary> /// Initializes a new progress meter, but doesn't support the IProgressHandler unless one is specified. /// </summary> public ProgressMeter() : this(null, "Calculating values.", 100) { } /// <summary> /// A progress meter can't actually do anything without a progressHandler, which actually displays the status. /// </summary> /// <param name="progressHandler">An IProgressHandler that will actually handle the status messages sent by this meter.</param> public ProgressMeter(IProgressHandler progressHandler) : this(progressHandler, "Calculating values.", 100) { } /// <summary> /// A progress meter that simply keeps track of progress and is capable of sending progress messages. /// This assumes a MaxValue of 100 unless it is changed later. /// </summary> /// <param name="progressHandler">Any valid IProgressHandler that will display progress messages</param> /// <param name="baseMessage">A base message to use as the basic status for this progress handler.</param> public ProgressMeter(IProgressHandler progressHandler, string baseMessage) : this(progressHandler, baseMessage, 100) { } /// <summary> /// A progress meter that simply keeps track of progress and is capable of sending progress messages. /// </summary> /// <param name="progressHandler">Any valid implementation if IProgressHandler that will handle the progress function</param> /// <param name="baseMessage">The message without any progress information.</param> /// <param name="endValue">Percent should show a range between the MinValue and MaxValue. MinValue is assumed to be 0.</param> public ProgressMeter(IProgressHandler progressHandler, string baseMessage, object endValue) { _endValue = Convert.ToDouble(endValue); _progressHandler = progressHandler; Reset(); _baseMessage = baseMessage; } #endregion #region Methods /// <summary> /// Resets the progress meter to the 0 value. This sets the status message to "Ready.". /// </summary> public void Reset() { _prog = 0; _oldProg = 0; _baseMessage = "Ready."; if (_silent) return; if (_progressHandler == null) return; _progressHandler.Progress(_baseMessage, _prog, _baseMessage); } #endregion #region Properties /// <summary> /// Gets or sets the string message (without the progress element). /// </summary> public string BaseMessage { get { return _baseMessage; } set { _baseMessage = value; } } /// <summary> /// Gets or sets the string that does not include any mention of progress percentage, but specifies what is occurring. /// </summary> public string Key { get { return _baseMessage; } set { _baseMessage = value; } } /// <summary> /// Gets or sets the current integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int CurrentPercent { get { return _prog; } set { int val = value; if (val < 0) val = 0; if (val > 100) { val = 100; } _prog = val; if (_prog >= _oldProg + _stepPercent) { SendProgress(); _oldProg = _prog; } } } /// <summary> /// Gets or sets the current value relative to the specified MaxValue in order to update the progress. /// Setting this will also update OldProgress if there is an integer change in the percentage, and send /// a progress message to the IProgressHandler interface. /// </summary> public object CurrentValue { get { return _value; } set { _value = Convert.ToDouble(value); if (_startValue < _endValue) { CurrentPercent = Convert.ToInt32(Math.Round(100 * (_value - _startValue) / (_endValue - _startValue))); } else { if (_startValue == _endValue) { CurrentPercent = 100; } else { CurrentPercent = Convert.ToInt32(Math.Round(100 * (_startValue - _value) / (_startValue - _endValue))); } } } } /// <summary> /// The value that defines when the meter should show as 100% complete. /// EndValue can be less than StartValue, but values closer to EndValue /// will show as being closer to 100%. /// </summary> public object EndValue { get { return _endValue; } set { _endValue = Convert.ToDouble(value); } } /// <summary> /// Gets or sets whether the progress meter should send messages to the IProgressHandler. /// By default Silent is false, but setting this to true will disable the messaging portion. /// </summary> public bool Silent { get { return _silent; } set { _silent = value; } } /// <summary> /// The minimum value defines when the meter should show as 0% complete. /// </summary> public object StartValue { get { return _startValue; } set { _startValue = Convert.ToDouble(value); } } /// <summary> /// An integer value that is 1 by default. Ordinarily this will send a progress message only when the integer progress /// has changed by 1 percentage point. For example, if StepPercent were set to 5, then a progress update would only /// be sent out at 5%, 10% and so on. This helps reduce overhead in cases where showing status messages is actually /// the majority of the processing time for the function. /// </summary> public int StepPercent { get { return _stepPercent; } set { _stepPercent = value; if (_stepPercent < 1) _stepPercent = 1; if (_stepPercent > 100) _stepPercent = 100; } } /// <summary> /// Gets or sets the previous integer progress level from 0 to 100. If a new update is less than or equal to the previous /// value, then no progress will be displayed by the ProgressMeter. Values less than 0 are set to 0. Values greater than /// 100 are set to 100. /// </summary> public int PreviousPercent { get { return _oldProg; } set { int val = value; if (val < 0) val = 0; if (val > 100) val = 100; _oldProg = val; } } /// <summary> /// Gets or sets the progress handler for this meter /// </summary> public IProgressHandler ProgressHandler { get { return _progressHandler; } set { _progressHandler = value; } } /// <summary> /// This always increments the CurrentValue by one. /// </summary> public void Next() { CurrentValue = _value + 1; } /// <summary> /// Sends a progress message to the IProgressHandler interface with the current message and progress /// </summary> public void SendProgress() { if (_silent) return; if (_progressHandler == null) return; _progressHandler.Progress(_baseMessage, _prog, _baseMessage + ", " + _prog + "% Complete."); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Web; using log4net; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework { /// <summary> /// Implementation of a generic REST client /// </summary> /// <remarks> /// This class is a generic implementation of a REST (Representational State Transfer) web service. This /// class is designed to execute both synchronously and asynchronously. /// /// Internally the implementation works as a two stage asynchronous web-client. /// When the request is initiated, RestClient will query asynchronously for for a web-response, /// sleeping until the initial response is returned by the server. Once the initial response is retrieved /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response /// object into a memorystream as a sequence of asynchronous reads. /// /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be /// invoked by the caller in either synchronous mode or asynchronous modes. /// </remarks> public class RestClient : IDisposable { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private string realuri; #region member variables /// <summary> /// The base Uri of the web-service e.g. http://www.google.com /// </summary> private string _url; /// <summary> /// Path elements of the query /// </summary> private List<string> _pathElements = new List<string>(); /// <summary> /// Parameter elements of the query, e.g. min=34 /// </summary> private Dictionary<string, string> _parameterElements = new Dictionary<string, string>(); /// <summary> /// Request method. E.g. GET, POST, PUT or DELETE /// </summary> private string _method; /// <summary> /// Temporary buffer used to store bytes temporarily as they come in from the server /// </summary> private byte[] _readbuf; /// <summary> /// MemoryStream representing the resulting resource /// </summary> private Stream _resource; /// <summary> /// WebRequest object, held as a member variable /// </summary> private HttpWebRequest _request; /// <summary> /// WebResponse object, held as a member variable, so we can close it /// </summary> private HttpWebResponse _response; /// <summary> /// This flag will help block the main synchroneous method, in case we run in synchroneous mode /// </summary> //public static ManualResetEvent _allDone = new ManualResetEvent(false); /// <summary> /// Default time out period /// </summary> //private const int DefaultTimeout = 10*1000; // 10 seconds timeout /// <summary> /// Default Buffer size of a block requested from the web-server /// </summary> private const int BufferSize = 4096; // Read blocks of 4 KB. /// <summary> /// if an exception occours during async processing, we need to save it, so it can be /// rethrown on the primary thread; /// </summary> private Exception _asyncException; #endregion member variables #region constructors /// <summary> /// Instantiate a new RestClient /// </summary> /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param> public RestClient(string url) { _url = url; _readbuf = new byte[BufferSize]; _resource = new MemoryStream(); _request = null; _response = null; _lock = new object(); } private object _lock; #endregion constructors #region Dispose private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { _resource.Dispose(); } disposed = true; } #endregion Dispose /// <summary> /// Add a path element to the query, e.g. assets /// </summary> /// <param name="element">path entry</param> public void AddResourcePath(string element) { if (isSlashed(element)) _pathElements.Add(element.Substring(0, element.Length - 1)); else _pathElements.Add(element); } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> /// <param name="value">Value of the parameter, e.g. 42</param> public void AddQueryParameter(string name, string value) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value)); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> public void AddQueryParameter(string name) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), null); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Web-Request method, e.g. GET, PUT, POST, DELETE /// </summary> public string RequestMethod { get { return _method; } set { _method = value; } } /// <summary> /// True if string contains a trailing slash '/' /// </summary> /// <param name="s">string to be examined</param> /// <returns>true if slash is present</returns> private static bool isSlashed(string s) { return s.Substring(s.Length - 1, 1) == "/"; } /// <summary> /// Build a Uri based on the initial Url, path elements and parameters /// </summary> /// <returns>fully constructed Uri</returns> private Uri buildUri() { StringBuilder sb = new StringBuilder(); sb.Append(_url); foreach (string e in _pathElements) { sb.Append("/"); sb.Append(e); } bool firstElement = true; foreach (KeyValuePair<string, string> kv in _parameterElements) { if (firstElement) { sb.Append("?"); firstElement = false; } else sb.Append("&"); sb.Append(kv.Key); if (!string.IsNullOrEmpty(kv.Value)) { sb.Append("="); sb.Append(kv.Value); } } // realuri = sb.ToString(); //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri); return new Uri(sb.ToString()); } #region Async communications with server /// <summary> /// Async method, invoked when a block of data has been received from the service /// </summary> /// <param name="ar"></param> private void StreamIsReadyDelegate(IAsyncResult ar) { try { Stream s = (Stream) ar.AsyncState; int read = s.EndRead(ar); if (read > 0) { _resource.Write(_readbuf, 0, read); // IAsyncResult asynchronousResult = // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); // TODO! Implement timeout, without killing the server //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); } else { s.Close(); //_allDone.Set(); } } catch (Exception e) { //_allDone.Set(); _asyncException = e; } } #endregion Async communications with server /// <summary> /// Perform a synchronous request /// </summary> public Stream Request() { return Request(null); } /// <summary> /// Perform a synchronous request /// </summary> public Stream Request(IServiceAuth auth) { lock (_lock) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 200000; _request.Method = RequestMethod; _asyncException = null; if (auth != null) auth.AddAuthorization(_request.Headers); int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); try { using (_response = (HttpWebResponse) _request.GetResponse()) { using (Stream src = _response.GetResponseStream()) { int length = src.Read(_readbuf, 0, BufferSize); while (length > 0) { _resource.Write(_readbuf, 0, length); length = src.Read(_readbuf, 0, BufferSize); } // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); // _allDone.WaitOne(); } } } catch (WebException e) { using (HttpWebResponse errorResponse = e.Response as HttpWebResponse) { if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode) { // This is often benign. E.g., requesting a missing asset will return 404. m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString()); } else { m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e); } } return null; } if (_asyncException != null) throw _asyncException; if (_resource != null) { _resource.Flush(); _resource.Seek(0, SeekOrigin.Begin); } if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, _resource); return _resource; } } public Stream Request(Stream src, IServiceAuth auth) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 90000; _request.Method = RequestMethod; _asyncException = null; _request.ContentLength = src.Length; if (auth != null) auth.AddAuthorization(_request.Headers); src.Seek(0, SeekOrigin.Begin); int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src); using (Stream dst = _request.GetRequestStream()) { m_log.Info("[REST]: GetRequestStream is ok"); byte[] buf = new byte[1024]; int length = src.Read(buf, 0, 1024); m_log.Info("[REST]: First Read is ok"); while (length > 0) { dst.Write(buf, 0, length); length = src.Read(buf, 0, 1024); } } try { _response = (HttpWebResponse)_request.GetResponse(); } catch (WebException e) { m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}", RequestMethod, _request.RequestUri, e.Status, e.Message); return null; } catch (Exception e) { m_log.WarnFormat( "[REST]: Request {0} {1} failed with exception {2} {3}", RequestMethod, _request.RequestUri, e.Message, e.StackTrace); return null; } if (WebUtil.DebugLevel >= 5) { using (Stream responseStream = _response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); WebUtil.LogResponseDetail(reqnum, responseStr); } } } if (_response != null) _response.Close(); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); return null; } #region Async Invocation public IAsyncResult BeginRequest(AsyncCallback callback, object state) { /// <summary> /// In case, we are invoked asynchroneously this object will keep track of the state /// </summary> AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state); Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest"); return ar; } public Stream EndRequest(IAsyncResult asyncResult) { AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; // Wait for operation to complete, then return result or // throw exception return ar.EndInvoke(); } private void RequestHelper(Object asyncResult) { // We know that it's really an AsyncResult<DateTime> object AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; try { // Perform the operation; if sucessful set the result Stream s = Request(null); ar.SetAsCompleted(s, false); } catch (Exception e) { // If operation fails, set the exception ar.HandleException(e, false); } } #endregion Async Invocation } internal class SimpleAsyncResult : IAsyncResult { private readonly AsyncCallback m_callback; /// <summary> /// Is process completed? /// </summary> /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks> private byte m_completed; /// <summary> /// Did process complete synchronously? /// </summary> /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about /// booleans and VolatileRead as m_completed /// </remarks> private byte m_completedSynchronously; private readonly object m_asyncState; private ManualResetEvent m_waitHandle; private Exception m_exception; internal SimpleAsyncResult(AsyncCallback cb, object state) { m_callback = cb; m_asyncState = state; m_completed = 0; m_completedSynchronously = 1; } #region IAsyncResult Members public object AsyncState { get { return m_asyncState; } } public WaitHandle AsyncWaitHandle { get { if (m_waitHandle == null) { bool done = IsCompleted; ManualResetEvent mre = new ManualResetEvent(done); if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null) { mre.Close(); } else { if (!done && IsCompleted) { m_waitHandle.Set(); } } } return m_waitHandle; } } public bool CompletedSynchronously { get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; } } public bool IsCompleted { get { return Thread.VolatileRead(ref m_completed) == 1; } } #endregion #region class Methods internal void SetAsCompleted(bool completedSynchronously) { m_completed = 1; if (completedSynchronously) m_completedSynchronously = 1; else m_completedSynchronously = 0; SignalCompletion(); } internal void HandleException(Exception e, bool completedSynchronously) { m_completed = 1; if (completedSynchronously) m_completedSynchronously = 1; else m_completedSynchronously = 0; m_exception = e; SignalCompletion(); } private void SignalCompletion() { if (m_waitHandle != null) m_waitHandle.Set(); if (m_callback != null) m_callback(this); } public void EndInvoke() { // This method assumes that only 1 thread calls EndInvoke if (!IsCompleted) { // If the operation isn't done, wait for it AsyncWaitHandle.WaitOne(); AsyncWaitHandle.Close(); m_waitHandle.Close(); m_waitHandle = null; // Allow early GC } // Operation is done: if an exception occured, throw it if (m_exception != null) throw m_exception; } #endregion } internal class AsyncResult<T> : SimpleAsyncResult { private T m_result = default(T); public AsyncResult(AsyncCallback asyncCallback, Object state) : base(asyncCallback, state) { } public void SetAsCompleted(T result, bool completedSynchronously) { // Save the asynchronous operation's result m_result = result; // Tell the base class that the operation completed // sucessfully (no exception) base.SetAsCompleted(completedSynchronously); } public new T EndInvoke() { base.EndInvoke(); return m_result; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace SimpleTimerJob { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// // Main.cs // // Author: // Ruben Vermeersch <[email protected]> // Paul Lange <[email protected]> // Evan Briones <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2006-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2010 Paul Lange // Copyright (C) 2010 Evan Briones // Copyright (C) 2006-2009 Stephane Delcroix // // 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.IO; using System.Reflection; using System.Threading; using Mono.Addins; using Mono.Addins.Setup; using Mono.Unix; using FSpot.Settings; using FSpot.Utils; using Hyena; using Hyena.CommandLine; using Hyena.Gui; namespace FSpot { public static class Driver { static void ShowVersion () { Console.WriteLine ("F-Spot {0}", Defines.VERSION); Console.WriteLine ("http://f-spot.org"); Console.WriteLine ("\t(c)2003-2009, Novell Inc"); Console.WriteLine ("\t(c)2009 Stephane Delcroix"); Console.WriteLine ("Personal photo management for the GNOME Desktop"); } static void ShowAssemblyVersions () { ShowVersion (); Console.WriteLine (); Console.WriteLine ("Mono/.NET Version: " + Environment.Version); Console.WriteLine (string.Format ("{0}Assembly Version Information:", Environment.NewLine)); foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies ()) { AssemblyName name = asm.GetName (); Console.WriteLine ("\t" + name.Name + " (" + name.Version + ")"); } } static void ShowHelp () { Console.WriteLine ("Usage: f-spot [options...] [files|URIs...]"); Console.WriteLine (); var commands = new Hyena.CommandLine.Layout ( new LayoutGroup ("help", "Help Options", new LayoutOption ("help", "Show this help"), new LayoutOption ("help-options", "Show command line options"), new LayoutOption ("help-all", "Show all options"), new LayoutOption ("version", "Show version information"), new LayoutOption ("versions", "Show detailed version information")), new LayoutGroup ("options", "General options", new LayoutOption ("basedir=DIR", "Path to the photo database folder"), new LayoutOption ("import=URI", "Import from the given uri"), new LayoutOption ("photodir=DIR", "Default import folder"), new LayoutOption ("view ITEM", "View file(s) or directories"), new LayoutOption ("shutdown", "Shut down a running instance of F-Spot"), new LayoutOption ("slideshow", "Display a slideshow"), new LayoutOption ("debug", "Run in debug mode"))); if (ApplicationContext.CommandLine.Contains ("help-all")) { Console.WriteLine (commands); return; } List<string> errors = null; foreach (KeyValuePair<string, string> argument in ApplicationContext.CommandLine.Arguments) { switch (argument.Key) { case "help": Console.WriteLine (commands.ToString ("help")); break; case "help-options": Console.WriteLine (commands.ToString ("options")); break; default: if (argument.Key.StartsWith ("help")) { (errors ?? (errors = new List<string> ())).Add (argument.Key); } break; } } if (errors != null) { Console.WriteLine (commands.LayoutLine (string.Format ( "The following help arguments are invalid: {0}", Hyena.Collections.CollectionExtensions.Join (errors, "--", null, ", ")))); } } static string [] FixArgs (string [] args) { // Makes sure command line arguments are parsed backwards compatible. var outargs = new List<string> (); for (int i = 0; i < args.Length; i++) { switch (args [i]) { case "-h": case "-help": case "-usage": outargs.Add ("--help"); break; case "-V": case "-version": outargs.Add ("--version"); break; case "-versions": outargs.Add ("--versions"); break; case "-shutdown": outargs.Add ("--shutdown"); break; case "-b": case "-basedir": case "--basedir": outargs.Add ("--basedir=" + (i + 1 == args.Length ? string.Empty : args [++i])); break; case "-p": case "-photodir": case "--photodir": outargs.Add ("--photodir=" + (i + 1 == args.Length ? string.Empty : args [++i])); break; case "-i": case "-import": case "--import": outargs.Add ("--import=" + (i + 1 == args.Length ? string.Empty : args [++i])); break; case "-v": case "-view": outargs.Add ("--view"); break; case "-slideshow": outargs.Add ("--slideshow"); break; default: outargs.Add (args [i]); break; } } return outargs.ToArray (); } static int Main (string [] args) { args = FixArgs (args); ApplicationContext.ApplicationName = "F-Spot"; ApplicationContext.TrySetProcessName (Defines.PACKAGE); Paths.ApplicationName = "f-spot"; SynchronizationContext.SetSynchronizationContext (new GtkSynchronizationContext ()); ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = RunIdle; // Options and Option parsing bool shutdown = false; bool view = false; bool slideshow = false; bool import = false; GLib.GType.Init (); Catalog.Init ("f-spot", Defines.LOCALE_DIR); Global.PhotoUri = new SafeUri (Preferences.Get<string> (Preferences.STORAGE_PATH)); ApplicationContext.CommandLine = new CommandLineParser (args, 0); if (ApplicationContext.CommandLine.ContainsStart ("help")) { ShowHelp (); return 0; } if (ApplicationContext.CommandLine.Contains ("version")) { ShowVersion (); return 0; } if (ApplicationContext.CommandLine.Contains ("versions")) { ShowAssemblyVersions (); return 0; } if (ApplicationContext.CommandLine.Contains ("shutdown")) { Log.Information ("Shutting down existing F-Spot server..."); shutdown = true; } if (ApplicationContext.CommandLine.Contains ("slideshow")) { Log.Information ("Running F-Spot in slideshow mode."); slideshow = true; } if (ApplicationContext.CommandLine.Contains ("basedir")) { string dir = ApplicationContext.CommandLine ["basedir"]; if (!string.IsNullOrEmpty (dir)) { Global.BaseDirectory = dir; Log.InformationFormat ("BaseDirectory is now {0}", dir); } else { Log.Error ("f-spot: -basedir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("photodir")) { string dir = ApplicationContext.CommandLine ["photodir"]; if (!string.IsNullOrEmpty (dir)) { Global.PhotoUri = new SafeUri (dir); Log.InformationFormat ("PhotoDirectory is now {0}", dir); } else { Log.Error ("f-spot: -photodir option takes one argument"); return 1; } } if (ApplicationContext.CommandLine.Contains ("import")) import = true; if (ApplicationContext.CommandLine.Contains ("view")) view = true; if (ApplicationContext.CommandLine.Contains ("debug")) { Log.Debugging = true; // Debug GdkPixbuf critical warnings var logFunc = new GLib.LogFunc (GLib.Log.PrintTraceLogFunction); GLib.Log.SetLogHandler ("GdkPixbuf", GLib.LogLevelFlags.Critical, logFunc); // Debug Gtk critical warnings GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, logFunc); // Debug GLib critical warnings GLib.Log.SetLogHandler ("GLib", GLib.LogLevelFlags.Critical, logFunc); //Debug GLib-GObject critical warnings GLib.Log.SetLogHandler ("GLib-GObject", GLib.LogLevelFlags.Critical, logFunc); GLib.Log.SetLogHandler ("GLib-GIO", GLib.LogLevelFlags.Critical, logFunc); } // Validate command line options if ((import && (view || shutdown || slideshow)) || (view && (shutdown || slideshow)) || (shutdown && slideshow)) { Log.Error ("Can't mix -import, -view, -shutdown or -slideshow"); return 1; } InitializeAddins (); // Gtk initialization Gtk.Application.Init (Defines.PACKAGE, ref args); // Maybe we'll add this at a future date //Xwt.Application.InitializeAsGuest (Xwt.ToolkitType.Gtk); // init web proxy globally Platform.WebProxy.Init (); if (File.Exists (Preferences.Get<string> (Preferences.GTK_RC))) { if (File.Exists (Path.Combine (Global.BaseDirectory, "gtkrc"))) Gtk.Rc.AddDefaultFile (Path.Combine (Global.BaseDirectory, "gtkrc")); Global.DefaultRcFiles = Gtk.Rc.DefaultFiles; Gtk.Rc.AddDefaultFile (Preferences.Get<string> (Preferences.GTK_RC)); Gtk.Rc.ReparseAllForSettings (Gtk.Settings.Default, true); } try { Gtk.Window.DefaultIconList = new Gdk.Pixbuf [] { GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 16, 0), GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 22, 0), GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 32, 0), GtkUtil.TryLoadIcon (Global.IconTheme, "f-spot", 48, 0) }; } catch (Exception ex) { Log.Exception ("Loading default f-spot icons", ex); } GLib.ExceptionManager.UnhandledException += exceptionArgs => { Console.WriteLine ("Unhandeled exception handler:"); var exception = exceptionArgs.ExceptionObject as Exception; if (exception != null) { Console.WriteLine ("Message: " + exception.Message); Console.WriteLine ("Stack trace: " + exception.StackTrace); } else { Console.WriteLine ("Unknown exception type: " + exceptionArgs.ExceptionObject.GetType ().ToString ()); } }; CleanRoomStartup.Startup (Startup); // Running threads are preventing the application from quitting // we force it for now until this is fixed Environment.Exit (0); return 0; } static void InitializeAddins () { uint timer = Log.InformationTimerStart ("Initializing Mono.Addins"); try { UpdatePlugins (); } catch (Exception) { Log.Debug ("Failed to initialize plugins, will remove addin-db and try again."); ResetPluginDb (); } var setupService = new SetupService (AddinManager.Registry); foreach (AddinRepository repo in setupService.Repositories.GetRepositories ()) { if (repo.Url.StartsWith ("http://addins.f-spot.org/")) { Log.InformationFormat ("Unregistering {0}", repo.Url); setupService.Repositories.RemoveRepository (repo.Url); } } Log.DebugTimerPrint (timer, "Mono.Addins Initialization took {0}"); } static void UpdatePlugins () { AddinManager.Initialize (Global.BaseDirectory); AddinManager.Registry.Update (null); } static void ResetPluginDb () { // Nuke addin-db var directory = GLib.FileFactory.NewForUri (new SafeUri (Global.BaseDirectory)); using (var list = directory.EnumerateChildren ("standard::name", GLib.FileQueryInfoFlags.None, null)) { foreach (GLib.FileInfo info in list) { if (info.Name.StartsWith ("addin-db-")) { var file = GLib.FileFactory.NewForPath (Path.Combine (directory.Path, info.Name)); file.DeleteRecursive (); } } } // Try again UpdatePlugins (); } static void Startup () { if (ApplicationContext.CommandLine.Contains ("slideshow")) App.Instance.Slideshow (null); else if (ApplicationContext.CommandLine.Contains ("shutdown")) App.Instance.Shutdown (); else if (ApplicationContext.CommandLine.Contains ("view")) { if (ApplicationContext.CommandLine.Files.Count == 0) { Log.Error ("f-spot: -view option takes at least one argument"); Environment.Exit (1); } var list = new UriList (); foreach (var f in ApplicationContext.CommandLine.Files) list.AddUnknown (f); if (list.Count == 0) { ShowHelp (); Environment.Exit (1); } App.Instance.View (list); } else if (ApplicationContext.CommandLine.Contains ("import")) { string dir = ApplicationContext.CommandLine ["import"]; if (string.IsNullOrEmpty (dir)) { Log.Error ("f-spot: -import option takes one argument"); Environment.Exit (1); } App.Instance.Import (dir); } else App.Instance.Organize (); if (!App.Instance.IsRunning) Gtk.Application.Run (); } public static void RunIdle (InvokeHandler handler) { GLib.Idle.Add (delegate { handler (); return false; }); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace CC.MT.Public.Sheriff.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; /// <summary> /// ModelDescriptionGenerator /// </summary> /// <param name="config">HttpConfiguration</param> public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// GeneratedModels /// </summary> public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } /// <summary> /// GetOrCreateModelDescription /// </summary> /// <param name="modelType">Type</param> /// <returns>ModelDescription</returns> public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Catalog; using ESRI.ArcGIS.CatalogUI; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using System.IO; namespace CustomGxObject_CS { [Guid("65590ce5-9a58-4384-a85b-9efccbc0b727")] [ClassInterface(ClassInterfaceType.None)] [ProgId("CustomGxObject_CS.GxPyObject")] public class GxPyObject : ESRI.ArcGIS.Catalog.IGxObject, ESRI.ArcGIS.Catalog.IGxObjectUI, ESRI.ArcGIS.Catalog.IGxObjectEdit, ESRI.ArcGIS.Catalog.IGxObjectProperties { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GxRootObjects.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GxRootObjects.Unregister(regKey); } #endregion #endregion [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr hObject); #region Member Variables private IGxObject m_gxParent = null; private IGxCatalog m_gxCatalog = null; private string[] m_names = new string[3]; //0:FullName; 1:Name; 2:BaseName private string m_sCategory = "PY File"; private System.Drawing.Bitmap[] m_bitmaps = new System.Drawing.Bitmap[2]; private IntPtr[] m_hBitmap = new IntPtr[2]; #endregion #region Constructor/Destructor code public GxPyObject() { this.SetBitmaps(); } public GxPyObject(string name) { this.SetBitmaps(); this.SetNames(name); } private void SetBitmaps() { try { // In the constructor, initialize the icons to use. m_bitmaps[0] = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream("CustomGxObject_CS.LargeIcon.bmp")); m_bitmaps[1] = new System.Drawing.Bitmap(GetType().Assembly.GetManifestResourceStream("CustomGxObject_CS.SmallIcon.bmp")); if (m_bitmaps[0] != null) { m_bitmaps[0].MakeTransparent(m_bitmaps[0].GetPixel(1,1)); m_hBitmap[0] = m_bitmaps[0].GetHbitmap(); } if (m_bitmaps[1] != null) { m_bitmaps[1].MakeTransparent(m_bitmaps[1].GetPixel(1,1)); m_hBitmap[1] = m_bitmaps[1].GetHbitmap(); } } catch (System.ArgumentException ex) { if (ex.TargetSite.ToString() == "Void .ctor(System.IO.Stream)") { System.Diagnostics.Debug.WriteLine(ex.Message); // Error accessing the bitmap embedded resource. m_bitmaps[0] = null; m_bitmaps[1] = null; } } } private void SetNames(string newName) { if (newName != null) { // Set the Name, FullName and BaseName, based on the specified string. m_names[0] = newName; int indx = newName.LastIndexOf(@"\"); if (indx > -1) m_names[1] = newName.Substring(indx + 1); else m_names[1] = newName; indx = m_names[1].LastIndexOf("."); if (indx > -1) m_names[2] = m_names[1].Remove(indx, m_names[1].Length - indx); else m_names[1] = newName; } } ~GxPyObject() { if (m_hBitmap[0].ToInt32() != 0) DeleteObject(m_hBitmap[0]); if (m_hBitmap[1].ToInt32() != 0) DeleteObject(m_hBitmap[1]); } #endregion #region Implementation of IGxObject public void Attach(IGxObject Parent, IGxCatalog pCatalog) { m_gxParent = Parent; m_gxCatalog = pCatalog; } public void Detach() { m_gxParent = null; m_gxCatalog = null; } public void Refresh() { // No impl. } public IName InternalObjectName { get { IFileName fileName = new FileNameClass(); fileName.Path = m_names[0]; return (IName)fileName; } } public bool IsValid { get { return File.Exists(m_names[0]); } } public string FullName { get { return m_names[0]; } } public string BaseName { get { return m_names[2]; } } public string Name { get { return m_names[1]; } } public UID ClassID { get { UID clsid = new UIDClass(); clsid.Value = "{0E63CDC4-7E13-422f-8B2D-F5DF853F9CA1}"; return clsid; } } public IGxObject Parent { get { return m_gxParent; } } public string Category { get { return m_sCategory; } } #endregion #region Implementation of IGxObjectUI public UID NewMenu { get { //If you have created a class for new menu of this object, you can implement it here return null; } } public int SmallImage { get { if (m_bitmaps[1] != null) return m_bitmaps[1].GetHbitmap().ToInt32(); else return 0; } } public int LargeSelectedImage { get { if (m_bitmaps[0] != null) return m_bitmaps[0].GetHbitmap().ToInt32(); else return 0; } } public int SmallSelectedImage { get { if (m_bitmaps[1] != null) return m_bitmaps[1].GetHbitmap().ToInt32(); else return 0; } } public UID ContextMenu { get { //If you have created a class for context menu of this object, you can implement it here return null; } } public int LargeImage { get { if (m_bitmaps[0] != null) return m_bitmaps[0].GetHbitmap().ToInt32(); else return 0; } } #endregion #region Implementation of IGxObjectEdit public bool CanCopy() { return true; } public bool CanDelete() { return File.Exists(m_names[0]) && File.GetAttributes(m_names[0]) != FileAttributes.ReadOnly; } public bool CanRename() { return true; } public void Delete() { File.Delete(m_names[0]); //Tell parent the object is gone IGxObjectContainer pGxObjectContainer = (IGxObjectContainer)m_gxParent; pGxObjectContainer.DeleteChild(this); } public void EditProperties(int hParent) { //Add implementation if you have defined property page } public void Rename(string newShortName) { //Trim AML extension if (newShortName.ToUpper().EndsWith(".AML")) newShortName = newShortName.Substring(0, newShortName.Length - 4); //Construct new name int pos = m_names[0].LastIndexOf("\\"); String newName = m_names[0].Substring(0, pos) + newShortName + ".aml"; //Rename File.Move(m_names[0], newName); //Tell parent that name is changed m_gxParent.Refresh(); } #endregion #region Implementation of IGxObjectProperties public object GetProperty(string Name) { if (Name != null) { switch (Name) { case "ESRI_GxObject_Name": return this.Name; case "ESRI_GxObject_Type": return this.Category; default: return null; } } return null; } public void GetPropByIndex(int Index, ref string pName, ref object pValue) { switch (Index) { case 0: pName = "ESRI_GxObject_Name"; pValue = (System.Object) this.Name; return; case 1: pName = "ESRI_GxObject_Type"; pValue = (System.Object) this.Category; return; default: pName = null; pValue = null; return; } } public void SetProperty(string Name, object Value) { //No implementation return; } public int PropertyCount { get { return 2; } } #endregion } }
// // Authors: // Ben Motmans <[email protected]> // // Copyright (c) 2007 Ben Motmans // // 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.Text; using System.Data; using System.Collections.Generic; namespace MonoDevelop.Database.Sql { public abstract class AbstractSqlDialect : ISqlDialect { public abstract string QuoteIdentifier (string identifier); public abstract string MarkAsParameter (string identifier); public virtual string GetSql (IStatement statement) { if (statement == null) throw new ArgumentNullException ("statement"); Type type = statement.GetType (); if (type == typeof (SelectStatement)) return GetStatementSql (statement as SelectStatement); else if (type == typeof (InsertStatement)) return GetStatementSql (statement as InsertStatement); else if (type == typeof (UpdateStatement)) return GetStatementSql (statement as UpdateStatement); else if (type == typeof (DeleteStatement)) return GetStatementSql (statement as DeleteStatement); else if (type == typeof (DropStatement)) return GetStatementSql (statement as DropStatement); else if (type == typeof (TruncateStatement)) return GetStatementSql (statement as TruncateStatement); else throw new NotImplementedException (type.FullName); } public virtual string GetSql (IClause clause) { if (clause == null) throw new ArgumentNullException ("clause"); Type type = clause.GetType (); if (type == typeof (FromSelectClause)) return GetClauseSql (clause as FromSelectClause); else if (type == typeof (FromTableClause)) return GetClauseSql (clause as FromTableClause); else if (type == typeof (WhereClause)) return GetClauseSql (clause as WhereClause); else if (type == typeof (HavingClause)) return GetClauseSql (clause as HavingClause); else if (type == typeof (JoinClause)) return GetClauseSql (clause as JoinClause); else if (type == typeof (OrderByClause)) return GetClauseSql (clause as OrderByClause); else if (type == typeof (GroupByClause)) return GetClauseSql (clause as GroupByClause); else if (type == typeof (UnionClause)) return GetClauseSql (clause as UnionClause); else throw new NotImplementedException (type.FullName); } public virtual string GetSql (IExpression expr) { if (expr == null) throw new ArgumentNullException ("expr"); Type type = expr.GetType (); if (type == typeof (AliasedIdentifierExpression)) return GetExpressionSql (expr as AliasedIdentifierExpression); else if (type == typeof (IdentifierExpression)) return GetExpressionSql (expr as IdentifierExpression); else if (type == typeof (BooleanExpression)) return GetExpressionSql (expr as BooleanExpression); else if (type == typeof (OperatorExpression)) return GetExpressionSql (expr as OperatorExpression); else if (type == typeof (ParameterExpression)) return GetExpressionSql (expr as ParameterExpression); else throw new NotImplementedException (type.FullName); } public virtual string GetSql (ILiteral literal) { if (literal == null) throw new ArgumentNullException ("literal"); Type type = literal.GetType (); if (type == typeof (StringLiteral)) return GetLiteralSql (literal as StringLiteral); else if (type == typeof (NumericLiteral)) return GetLiteralSql (literal as NumericLiteral); else if (type == typeof (BooleanLiteral)) return GetLiteralSql (literal as BooleanLiteral); else if (type == typeof (NullLiteral)) return GetLiteralSql (literal as NullLiteral); else if (type == typeof (TrueLiteral)) return GetLiteralSql (literal as TrueLiteral); else if (type == typeof (FalseLiteral)) return GetLiteralSql (literal as FalseLiteral); else if (type == typeof (HexLiteral)) return GetLiteralSql (literal as HexLiteral); else if (type == typeof (BitLiteral)) return GetLiteralSql (literal as BitLiteral); else throw new NotImplementedException (type.FullName); } protected virtual string GetStatementSql (SelectStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("SELECT "); bool first = true; foreach (IdentifierExpression expr in statement.Columns) { if (first) first = false; else sb.Append (','); sb.Append (GetSql (expr)); } sb.Append (' '); sb.Append (Environment.NewLine); sb.Append (GetSql (statement.From)); if (statement.Where != null) { sb.Append (GetSql (statement.Where)); sb.Append (' '); sb.Append (Environment.NewLine); } if (statement.OrderBy != null) { sb.Append (GetSql (statement.OrderBy)); sb.Append (' '); sb.Append (Environment.NewLine); } if (statement.GroupBy != null) { sb.Append (GetSql (statement.GroupBy)); sb.Append (' '); sb.Append (Environment.NewLine); } if (statement.Having != null) { sb.Append (GetSql (statement.Having)); sb.Append (' '); sb.Append (Environment.NewLine); } if (statement.Union != null) { sb.Append (GetSql (statement.Union)); sb.Append (' '); sb.Append (Environment.NewLine); } if (statement.Join != null) { sb.Append (GetSql (statement.Join)); sb.Append (' '); sb.Append (Environment.NewLine); } sb.Append (';'); return sb.ToString (); } protected virtual string GetStatementSql (InsertStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("INSERT INTO "); sb.Append (GetSql (statement.Identifier)); if (statement.Columns.Count > 0) { sb.Append (Environment.NewLine); sb.Append (" ("); int columnCount = statement.Columns.Count; for (int i=0; i<columnCount; i++) { sb.Append (GetSql (statement.Columns[i])); sb.Append (i == (columnCount - 1) ? ", " : ""); } sb.Append (")"); } sb.Append (Environment.NewLine); sb.Append (" VALUES "); int rowCount = statement.Values.Count; for (int j=0; j<rowCount; j++) { sb.Append ("("); List<IExpression> expr = statement.Values[j]; int columnCount = expr.Count; for (int i=0; i<columnCount; i++) { sb.Append (GetSql (expr[i])); sb.Append (i == (columnCount - 1) ? ", " : ""); } sb.Append (")"); sb.Append (j == (rowCount - 1) ? "," + Environment.NewLine : ""); } sb.Append (';'); return sb.ToString (); } protected virtual string GetStatementSql (UpdateStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("UPDATE "); sb.Append (GetSql (statement.Identifier)); sb.Append (' '); sb.Append (Environment.NewLine); sb.Append ("SET "); int columnCount = statement.Columns.Count; for (int i=0; i<columnCount; i++) { OperatorExpression expr = new OperatorExpression (statement.Columns[i], Operator.Equals, statement.Values[i]); sb.Append (GetExpressionSql (expr)); sb.Append (i != (columnCount - 1) ? ", " : ""); } if (statement.Where != null) { sb.Append (GetSql (statement.Where)); sb.Append (' '); sb.Append (Environment.NewLine); } sb.Append (';'); return sb.ToString (); } protected virtual string GetStatementSql (DeleteStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("DELETE "); sb.Append (GetSql (statement.From)); if (statement.Where != null) { sb.Append (GetSql (statement.Where)); sb.Append (' '); sb.Append (Environment.NewLine); } sb.Append (';'); return sb.ToString (); } protected virtual string GetStatementSql (DropStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("DROP "); switch (statement.DropType) { case DropStatementType.Database: sb.Append ("DATABASE "); break; case DropStatementType.Table: sb.Append ("TABLE "); break; case DropStatementType.Index: sb.Append ("INDEX "); break; case DropStatementType.Procedure: sb.Append ("PROCEDURE "); break; case DropStatementType.View: sb.Append ("VIEW "); break; } sb.Append (GetSql (statement.Identifier)); sb.Append (';'); return sb.ToString (); } protected virtual string GetStatementSql (TruncateStatement statement) { StringBuilder sb = new StringBuilder (); sb.Append ("TRUNCATE "); sb.Append (GetSql (statement.Identifier)); sb.Append (';'); return sb.ToString (); } protected virtual string GetClauseSql (FromSelectClause clause) { return String.Concat ("FROM ", GetStatementSql (clause.Source)); } protected virtual string GetClauseSql (FromTableClause clause) { return String.Concat ("FROM ", GetExpressionSql (clause.Source)); } protected virtual string GetClauseSql (WhereClause clause) { return String.Concat ("WHERE ", GetSql (clause.Condition)); } protected virtual string GetClauseSql (OrderByClause clause) { throw new NotImplementedException (); } protected virtual string GetClauseSql (GroupByClause clause) { throw new NotImplementedException (); } protected virtual string GetClauseSql (UnionClause clause) { throw new NotImplementedException (); } protected virtual string GetClauseSql (JoinClause clause) { throw new NotImplementedException (); } protected virtual string GetClauseSql (HavingClause clause) { throw new NotImplementedException (); } protected virtual string GetLiteralSql (StringLiteral literal) { return String.Concat ("'", literal.Value, "'"); } protected virtual string GetLiteralSql (NumericLiteral literal) { return literal.Value; } protected virtual string GetLiteralSql (NullLiteral literal) { return "NULL"; } protected virtual string GetLiteralSql (TrueLiteral literal) { return "TRUE"; } protected virtual string GetLiteralSql (FalseLiteral literal) { return "FALSE"; } protected virtual string GetLiteralSql (HexLiteral literal) { // X'ABCD' return String.Concat ("X'", literal.Value, "'"); } protected virtual string GetLiteralSql (BitLiteral literal) { // B'01011010' return String.Concat ("B'", literal.Value, "'"); } protected virtual string GetLiteralSql (BooleanLiteral literal) { if (literal.Value) return "TRUE"; return "FALSE"; } protected virtual string GetExpressionSql (AliasedIdentifierExpression expr) { return String.Concat (GetIdentifierName (expr.Name), " AS ", GetIdentifierName (expr.Alias)); } protected virtual string GetExpressionSql (IdentifierExpression expr) { return GetIdentifierName (expr.Name); } protected virtual string GetIdentifierName (string identifier) { return QuoteIdentifier (identifier); } protected virtual string GetExpressionSql (BooleanExpression expr) { return String.Concat ("(", GetSql (expr.Left), " ", GetOperatorSql (expr.Operator), " ", GetSql (expr.Right), ")"); } protected virtual string GetExpressionSql (OperatorExpression expr) { return String.Concat ("(", GetSql (expr.Left), " ", GetOperatorSql (expr.Operator), " ", GetSql (expr.Right), ")"); } protected virtual string GetExpressionSql (ParameterExpression expr) { return MarkAsParameter (expr.Name); } protected virtual string GetOperatorSql (Operator op) { switch (op) { case Operator.Equals: return "="; case Operator.NotEqual: return "!="; case Operator.GreaterThanOrEqual: return ">="; case Operator.GreaterThan: return ">"; case Operator.LessThanOrEqual: return "<="; case Operator.LessThan: return "<"; case Operator.Plus: return "+"; case Operator.Minus: return "-"; case Operator.Divide: return "/"; case Operator.Multiply: return "*"; case Operator.Modus: return "%"; case Operator.Is: return "IS"; case Operator.IsNot: return "IS NOT"; case Operator.In: return "IN"; case Operator.Like: return "LIKE"; default: throw new NotImplementedException (); } } protected virtual string GetOperatorSql (BooleanOperator op) { bool not = ((op & BooleanOperator.Not) == BooleanOperator.Not); bool and = ((op & BooleanOperator.And) == BooleanOperator.And); bool or = ((op & BooleanOperator.Or) == BooleanOperator.Or); if (and) if (not) return "AND NOT"; else return "AND"; else if (or) if (not) return "OR NOT"; else return "OR"; else return "NOT"; } } }
using System; using UIKit; using CoreGraphics; using Foundation; namespace PaintCode { /// <summary> /// Blue button example /// http://paintcodeapp.com/examples.html /// </summary> /// <remarks> /// This implementation only deals with Normal and Pressed states. /// There is no handling for the Disabled state. /// </remarks> public class GlossyButton : UIButton { bool isPressed; public UIColor NormalColor; /// <summary> /// Invoked when the user touches /// </summary> public event Action<GlossyButton> Tapped; /// <summary> /// Creates a new instance of the GlassButton using the specified dimensions /// </summary> public GlossyButton (CGRect frame) : base (frame) { NormalColor = UIColor.FromRGBA (0.82f, 0.11f, 0.14f, 1.00f); } /// <summary> /// Whether the button is rendered enabled or not. /// </summary> public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; SetNeedsDisplay (); } } public override bool BeginTracking (UITouch uitouch, UIEvent uievent) { SetNeedsDisplay (); isPressed = true; return base.BeginTracking (uitouch, uievent); } public override void EndTracking (UITouch uitouch, UIEvent uievent) { if (isPressed && Enabled) { if (Tapped != null) Tapped (this); } isPressed = false; SetNeedsDisplay (); base.EndTracking (uitouch, uievent); } public override bool ContinueTracking (UITouch uitouch, UIEvent uievent) { var touch = uievent.AllTouches.AnyObject as UITouch; if (Bounds.Contains (touch.LocationInView (this))) isPressed = true; else isPressed = false; return base.ContinueTracking (uitouch, uievent); } public override void Draw (CGRect rect) { using (var context = UIGraphics.GetCurrentContext ()) { var bounds = Bounds; //UIColor background = Enabled ? isPressed ? HighlightedColor : NormalColor : DisabledColor; UIColor buttonColor = NormalColor; //UIColor.FromRGBA (0.00f, 0.37f, 0.89f, 1.00f); var buttonColorRGBA = new nfloat[4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], out buttonColorRGBA [2], out buttonColorRGBA [3] ); if (isPressed) { // Get the Hue Saturation Brightness Alpha copy of the color var buttonColorHSBA = new nfloat[4]; buttonColor.GetHSBA ( out buttonColorHSBA [0], out buttonColorHSBA [1], out buttonColorHSBA [2], out buttonColorHSBA [3] ); // Change the brightness to a fixed value (0.5f) buttonColor = UIColor.FromHSBA (buttonColorHSBA [0], buttonColorHSBA [1], 0.5f, buttonColorHSBA [3]); // Re-set the base buttonColorRGBA because everything else is relative to it buttonColorRGBA = new nfloat[4]; buttonColor.GetRGBA ( out buttonColorRGBA [0], out buttonColorRGBA [1], out buttonColorRGBA [2], out buttonColorRGBA [3] ); } using (var colorSpace = CGColorSpace.CreateDeviceRGB ()) { // Abstracted Graphic Attributes // var textContent = this.Title (UIControlState.Normal); //"STOP"; // var font = UIFont.SystemFontOfSize (18); // ------------- START PAINTCODE ------------- // Color Declarations UIColor frameColorTop = UIColor.FromRGBA (0.20f, 0.20f, 0.20f, 1.00f); UIColor frameShadowColor = UIColor.FromRGBA (1.00f, 1.00f, 1.00f, 0.40f); UIColor glossyColorBottom = UIColor.FromRGBA ( (buttonColorRGBA [0] * 0.6f + 0.4f), (buttonColorRGBA [1] * 0.6f + 0.4f), (buttonColorRGBA [2] * 0.6f + 0.4f), (buttonColorRGBA [3] * 0.6f + 0.4f) ); UIColor glossyColorUp = UIColor.FromRGBA ( (buttonColorRGBA [0] * 0.2f + 0.8f), (buttonColorRGBA [1] * 0.2f + 0.8f), (buttonColorRGBA [2] * 0.2f + 0.8f), (buttonColorRGBA [3] * 0.2f + 0.8f) ); // Gradient Declarations var glossyGradientColors = new CGColor [] { glossyColorUp.CGColor, glossyColorBottom.CGColor }; var glossyGradientLocations = new nfloat [] { 0, 1 }; var glossyGradient = new CGGradient (colorSpace, glossyGradientColors, glossyGradientLocations); // Shadow Declarations var frameInnerShadow = frameShadowColor.CGColor; var frameInnerShadowOffset = new CGSize (0, -0); const int frameInnerShadowBlurRadius = 3; var buttonInnerShadow = UIColor.Black.CGColor; var buttonInnerShadowOffset = new CGSize (0, -0); const int buttonInnerShadowBlurRadius = 12; var textShadow = UIColor.Black.CGColor; var textShadowOffset = new CGSize (0, -0); const int textShadowBlurRadius = 1; var buttonShadow = UIColor.Black.CGColor; var buttonShadowOffset = new CGSize (0, isPressed ? 0 : 2); // ADDED this code after PaintCode var buttonShadowBlurRadius = isPressed ? 2 : 3; // ADDED this code after PaintCode // outerFrame Drawing var outerFramePath = UIBezierPath.FromRoundedRect (new CGRect (2.5f, 1.5f, 120, 32), 8); context.SaveState (); context.SetShadow (buttonShadowOffset, buttonShadowBlurRadius, buttonShadow); frameColorTop.SetFill (); outerFramePath.Fill (); context.RestoreState (); UIColor.Black.SetStroke (); outerFramePath.LineWidth = 1; outerFramePath.Stroke (); // innerFrame Drawing var innerFramePath = UIBezierPath.FromRoundedRect (new CGRect (5.5f, 4.5f, 114, 26), 5); context.SaveState (); context.SetShadow (frameInnerShadowOffset, frameInnerShadowBlurRadius, frameInnerShadow); buttonColor.SetFill (); innerFramePath.Fill (); // innerFrame Inner Shadow var innerFrameBorderRect = innerFramePath.Bounds; innerFrameBorderRect.Inflate (buttonInnerShadowBlurRadius, buttonInnerShadowBlurRadius); innerFrameBorderRect.Offset (-buttonInnerShadowOffset.Width, -buttonInnerShadowOffset.Height); innerFrameBorderRect = CGRect.Union (innerFrameBorderRect, innerFramePath.Bounds); innerFrameBorderRect.Inflate (1, 1); var innerFrameNegativePath = UIBezierPath.FromRect (innerFrameBorderRect); innerFrameNegativePath.AppendPath (innerFramePath); innerFrameNegativePath.UsesEvenOddFillRule = true; context.SaveState (); { var xOffset = buttonInnerShadowOffset.Width + (float)Math.Round (innerFrameBorderRect.Width); var yOffset = buttonInnerShadowOffset.Height; context.SetShadow ( new CGSize (xOffset + (xOffset >= 0 ? 0.1f : -0.1f), yOffset + (yOffset >= 0 ? 0.1f : -0.1f)), buttonInnerShadowBlurRadius, buttonInnerShadow); innerFramePath.AddClip (); var transform = CGAffineTransform.MakeTranslation (-(float)Math.Round (innerFrameBorderRect.Width), 0); innerFrameNegativePath.ApplyTransform (transform); UIColor.Gray.SetFill (); innerFrameNegativePath.Fill (); } context.RestoreState (); context.RestoreState (); UIColor.Black.SetStroke (); innerFramePath.LineWidth = 1; innerFramePath.Stroke (); // Rounded Rectangle Drawing var roundedRectanglePath = UIBezierPath.FromRoundedRect (new CGRect (8, 6, 109, 9), 4); context.SaveState (); roundedRectanglePath.AddClip (); context.DrawLinearGradient (glossyGradient, new CGPoint (62.5f, 6), new CGPoint (62.5f, 15), 0); context.RestoreState (); // Text Drawing // var textRect = new CGRect (18, 6, 90, 28); context.SaveState (); context.SetShadow(textShadowOffset, textShadowBlurRadius, textShadow); glossyColorUp.SetFill (); // Use default button-drawn text // new NSString(textContent).DrawString(textRect, font, UILineBreakMode.WordWrap, UITextAlignment.Center); context.RestoreState (); // ------------- END PAINTCODE ------------- } } } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core { /// <summary> /// Encapsulates initialization and shutdown of gRPC library. /// </summary> public class GrpcEnvironment { const int MinDefaultThreadPoolSize = 4; const int DefaultBatchContextPoolSharedCapacity = 10000; const int DefaultBatchContextPoolThreadLocalCapacity = 64; static object staticLock = new object(); static GrpcEnvironment instance; static int refCount; static int? customThreadPoolSize; static int? customCompletionQueueCount; static bool inlineHandlers; static int batchContextPoolSharedCapacity = DefaultBatchContextPoolSharedCapacity; static int batchContextPoolThreadLocalCapacity = DefaultBatchContextPoolThreadLocalCapacity; static readonly HashSet<Channel> registeredChannels = new HashSet<Channel>(); static readonly HashSet<Server> registeredServers = new HashSet<Server>(); static ILogger logger = new LogLevelFilterLogger(new ConsoleLogger(), LogLevel.Off, true); readonly IObjectPool<BatchContextSafeHandle> batchContextPool; readonly GrpcThreadPool threadPool; readonly DebugStats debugStats = new DebugStats(); readonly AtomicCounter cqPickerCounter = new AtomicCounter(); bool isShutdown; /// <summary> /// Returns a reference-counted instance of initialized gRPC environment. /// Subsequent invocations return the same instance unless reference count has dropped to zero previously. /// </summary> internal static GrpcEnvironment AddRef() { ShutdownHooks.Register(); lock (staticLock) { refCount++; if (instance == null) { instance = new GrpcEnvironment(); } return instance; } } /// <summary> /// Decrements the reference count for currently active environment and asynchronously shuts down the gRPC environment if reference count drops to zero. /// </summary> internal static async Task ReleaseAsync() { GrpcEnvironment instanceToShutdown = null; lock (staticLock) { GrpcPreconditions.CheckState(refCount > 0); refCount--; if (refCount == 0) { instanceToShutdown = instance; instance = null; } } if (instanceToShutdown != null) { await instanceToShutdown.ShutdownAsync().ConfigureAwait(false); } } internal static int GetRefCount() { lock (staticLock) { return refCount; } } internal static void RegisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); registeredChannels.Add(channel); } } internal static void UnregisterChannel(Channel channel) { lock (staticLock) { GrpcPreconditions.CheckNotNull(channel); GrpcPreconditions.CheckArgument(registeredChannels.Remove(channel), "Channel not found in the registered channels set."); } } internal static void RegisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); registeredServers.Add(server); } } internal static void UnregisterServer(Server server) { lock (staticLock) { GrpcPreconditions.CheckNotNull(server); GrpcPreconditions.CheckArgument(registeredServers.Remove(server), "Server not found in the registered servers set."); } } /// <summary> /// Requests shutdown of all channels created by the current process. /// </summary> public static Task ShutdownChannelsAsync() { HashSet<Channel> snapshot = null; lock (staticLock) { snapshot = new HashSet<Channel>(registeredChannels); } return Task.WhenAll(snapshot.Select((channel) => channel.ShutdownAsync())); } /// <summary> /// Requests immediate shutdown of all servers created by the current process. /// </summary> public static Task KillServersAsync() { HashSet<Server> snapshot = null; lock (staticLock) { snapshot = new HashSet<Server>(registeredServers); } return Task.WhenAll(snapshot.Select((server) => server.KillAsync())); } /// <summary> /// Gets application-wide logger used by gRPC. /// </summary> /// <value>The logger.</value> public static ILogger Logger { get { return logger; } } /// <summary> /// Sets the application-wide logger that should be used by gRPC. /// </summary> public static void SetLogger(ILogger customLogger) { GrpcPreconditions.CheckNotNull(customLogger, "customLogger"); logger = customLogger; } /// <summary> /// Sets the number of threads in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting thread pool size is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetThreadPoolSize(int threadCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(threadCount > 0, "threadCount needs to be a positive number"); customThreadPoolSize = threadCount; } } /// <summary> /// Sets the number of completion queues in the gRPC thread pool that polls for internal RPC events. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// Setting the number of completions queues is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetCompletionQueueCount(int completionQueueCount) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(completionQueueCount > 0, "threadCount needs to be a positive number"); customCompletionQueueCount = completionQueueCount; } } /// <summary> /// By default, gRPC's internal event handlers get offloaded to .NET default thread pool thread (<c>inlineHandlers=false</c>). /// Setting <c>inlineHandlers</c> to <c>true</c> will allow scheduling the event handlers directly to /// <c>GrpcThreadPool</c> internal threads. That can lead to significant performance gains in some situations, /// but requires user to never block in async code (incorrectly written code can easily lead to deadlocks). /// Inlining handlers is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// Note: <c>inlineHandlers=true</c> was the default in gRPC C# v1.4.x and earlier. /// </summary> public static void SetHandlerInlining(bool inlineHandlers) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcEnvironment.inlineHandlers = inlineHandlers; } } /// <summary> /// Sets the parameters for a pool that caches batch context instances. Reusing batch context instances /// instead of creating a new one for every C core operation helps reducing the GC pressure. /// Can be only invoked before the <c>GrpcEnviroment</c> is started and cannot be changed afterwards. /// This is an advanced setting and you should only use it if you know what you are doing. /// Most users should rely on the default value provided by gRPC library. /// Note: this method is part of an experimental API that can change or be removed without any prior notice. /// </summary> public static void SetBatchContextPoolParams(int sharedCapacity, int threadLocalCapacity) { lock (staticLock) { GrpcPreconditions.CheckState(instance == null, "Can only be set before GrpcEnvironment is initialized"); GrpcPreconditions.CheckArgument(sharedCapacity >= 0, "Shared capacity needs to be a non-negative number"); GrpcPreconditions.CheckArgument(threadLocalCapacity >= 0, "Thread local capacity needs to be a non-negative number"); batchContextPoolSharedCapacity = sharedCapacity; batchContextPoolThreadLocalCapacity = threadLocalCapacity; } } /// <summary> /// Occurs when <c>GrpcEnvironment</c> is about the start the shutdown logic. /// If <c>GrpcEnvironment</c> is later initialized and shutdown, the event will be fired again (unless unregistered first). /// </summary> public static event EventHandler ShuttingDown; /// <summary> /// Creates gRPC environment. /// </summary> private GrpcEnvironment() { GrpcNativeInit(); batchContextPool = new DefaultObjectPool<BatchContextSafeHandle>(() => BatchContextSafeHandle.Create(this.batchContextPool), batchContextPoolSharedCapacity, batchContextPoolThreadLocalCapacity); threadPool = new GrpcThreadPool(this, GetThreadPoolSizeOrDefault(), GetCompletionQueueCountOrDefault(), inlineHandlers); threadPool.Start(); } /// <summary> /// Gets the completion queues used by this gRPC environment. /// </summary> internal IReadOnlyCollection<CompletionQueueSafeHandle> CompletionQueues { get { return this.threadPool.CompletionQueues; } } internal IObjectPool<BatchContextSafeHandle> BatchContextPool => batchContextPool; internal bool IsAlive { get { return this.threadPool.IsAlive; } } /// <summary> /// Picks a completion queue in a round-robin fashion. /// Shouldn't be invoked on a per-call basis (used at per-channel basis). /// </summary> internal CompletionQueueSafeHandle PickCompletionQueue() { var cqIndex = (int) ((cqPickerCounter.Increment() - 1) % this.threadPool.CompletionQueues.Count); return this.threadPool.CompletionQueues.ElementAt(cqIndex); } /// <summary> /// Gets the completion queue used by this gRPC environment. /// </summary> internal DebugStats DebugStats { get { return this.debugStats; } } /// <summary> /// Gets version of gRPC C core. /// </summary> internal static string GetCoreVersionString() { var ptr = NativeMethods.Get().grpcsharp_version_string(); // the pointer is not owned return Marshal.PtrToStringAnsi(ptr); } internal static void GrpcNativeInit() { NativeMethods.Get().grpcsharp_init(); } internal static void GrpcNativeShutdown() { NativeMethods.Get().grpcsharp_shutdown(); } /// <summary> /// Shuts down this environment. /// </summary> private async Task ShutdownAsync() { if (isShutdown) { throw new InvalidOperationException("ShutdownAsync has already been called"); } await Task.Run(() => ShuttingDown?.Invoke(this, null)).ConfigureAwait(false); await threadPool.StopAsync().ConfigureAwait(false); batchContextPool.Dispose(); GrpcNativeShutdown(); isShutdown = true; debugStats.CheckOK(); } private int GetThreadPoolSizeOrDefault() { if (customThreadPoolSize.HasValue) { return customThreadPoolSize.Value; } // In systems with many cores, use half of the cores for GrpcThreadPool // and the other half for .NET thread pool. This heuristic definitely needs // more work, but seems to work reasonably well for a start. return Math.Max(MinDefaultThreadPoolSize, Environment.ProcessorCount / 2); } private int GetCompletionQueueCountOrDefault() { if (customCompletionQueueCount.HasValue) { return customCompletionQueueCount.Value; } // by default, create a completion queue for each thread return GetThreadPoolSizeOrDefault(); } private static class ShutdownHooks { static object staticLock = new object(); static bool hooksRegistered; public static void Register() { lock (staticLock) { if (!hooksRegistered) { #if NETSTANDARD1_5 System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (assemblyLoadContext) => { HandleShutdown(); }; #else AppDomain.CurrentDomain.ProcessExit += (sender, eventArgs) => { HandleShutdown(); }; AppDomain.CurrentDomain.DomainUnload += (sender, eventArgs) => { HandleShutdown(); }; #endif } hooksRegistered = true; } } /// <summary> /// Handler for AppDomain.DomainUnload, AppDomain.ProcessExit and AssemblyLoadContext.Unloading hooks. /// </summary> private static void HandleShutdown() { Task.WaitAll(GrpcEnvironment.ShutdownChannelsAsync(), GrpcEnvironment.KillServersAsync()); } } } }
#region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Structure; using Autodesk.Revit.UI; #endregion namespace SetoutPoints { [Transaction( TransactionMode.Manual )] public class CmdGeomVertices : IExternalCommand { /// <summary> /// Classify the possible setup point /// host geometry types that we support. /// </summary> enum HostType { Floors, Ramps, StructuralColumns, StructuralFraming, StructuralFoundations, Walls } /// <summary> /// Return the HostType for a given element. /// </summary> HostType GetHostType( Element e ) { if( e is WallFoundation ) { return HostType.StructuralFoundations; } if( e is Floor ) { return HostType.Floors; } if( e is Wall ) { return HostType.Walls; } if( null != e.Category ) { switch( e.Category.Id.IntegerValue ) { case (int) BuiltInCategory.OST_StructuralColumns: return HostType.StructuralColumns; case (int) BuiltInCategory.OST_StructuralFraming: return HostType.StructuralFraming; case (int) BuiltInCategory.OST_StructuralFoundation: return HostType.StructuralFoundations; case (int) BuiltInCategory.OST_Floors: return HostType.Floors; case (int) BuiltInCategory.OST_Ramps: return HostType.Ramps; } } Debug.Assert( false, "what host type is this element?" ); return HostType.Floors; } /// <summary> /// Return a string describing the given element: /// .NET type name, category name, family and /// symbol name for a family instance, element id /// and element name. /// </summary> public static string ElementDescription( Element e ) { if( null == e ) { return "<null>"; } // For a wall, the element name equals the // wall type name, which is equivalent to the // family name ... FamilyInstance fi = e as FamilyInstance; string typeName = e.GetType().Name; string categoryName = ( null == e.Category ) ? string.Empty : e.Category.Name + " "; string familyName = ( null == fi ) ? string.Empty : fi.Symbol.Family.Name + " "; string symbolName = ( null == fi || e.Name.Equals( fi.Symbol.Name ) ) ? string.Empty : fi.Symbol.Name + " "; return string.Format( "{0} {1}{2}{3}<{4} {5}>", typeName, categoryName, familyName, symbolName, e.Id.IntegerValue, e.Name ); } /// <summary> /// Retrieve all structural elements that we are /// interested in using to define setout points. /// We are looking at concrete for the moment. /// This includes: columns, framing, floors, /// foundations, ramps, walls. /// </summary> FilteredElementCollector GetStructuralElements( Document doc ) { // What categories of family instances // are we interested in? BuiltInCategory[] bics = new BuiltInCategory[] { BuiltInCategory.OST_StructuralColumns, BuiltInCategory.OST_StructuralFraming, BuiltInCategory.OST_StructuralFoundation, BuiltInCategory.OST_Floors, BuiltInCategory.OST_Ramps }; IList<ElementFilter> a = new List<ElementFilter>( bics.Length ); foreach( BuiltInCategory bic in bics ) { a.Add( new ElementCategoryFilter( bic ) ); } LogicalOrFilter categoryFilter = new LogicalOrFilter( a ); // Filter only for structural family // instances using concrete or precast // concrete structural material: List<ElementFilter> b = new List<ElementFilter>( 2 ); b.Add( new StructuralMaterialTypeFilter( StructuralMaterialType.Concrete ) ); b.Add( new StructuralMaterialTypeFilter( StructuralMaterialType.PrecastConcrete ) ); LogicalOrFilter structuralMaterialFilter = new LogicalOrFilter( b ); List<ElementFilter> c = new List<ElementFilter>( 3 ); c.Add( new ElementClassFilter( typeof( FamilyInstance ) ) ); c.Add( structuralMaterialFilter ); c.Add( categoryFilter ); LogicalAndFilter familyInstanceFilter = new LogicalAndFilter( c ); IList<ElementFilter> d = new List<ElementFilter>( 6 ); d.Add( new ElementClassFilter( typeof( Wall ) ) ); d.Add( new ElementClassFilter( typeof( Floor ) ) ); //d.Add( new ElementClassFilter( // typeof( ContFooting ) ) ); #if NEED_LOADS d.Add( new ElementClassFilter( typeof( PointLoad ) ) ); d.Add( new ElementClassFilter( typeof( LineLoad ) ) ); d.Add( new ElementClassFilter( typeof( AreaLoad ) ) ); #endif d.Add( familyInstanceFilter ); LogicalOrFilter classFilter = new LogicalOrFilter( d ); FilteredElementCollector col = new FilteredElementCollector( doc ) .WhereElementIsNotElementType() .WherePasses( classFilter ); return col; } #region Setout point family identification constants public const string FamilyName = "SetoutPoint"; public const string SymbolName = "SetoutPoint"; const string _extension = ".rfa"; const string _directory = // "C:/a/doc/revit/blog/src/SetoutPoints/test/"; // 2013 //"Z:/a/doc/revit/blog/src/SetoutPoints/test/"; // 2015 "C:/a/vs/SetoutPoints/test/"; // 2017 const string _family_path = _directory + FamilyName + _extension; // Shared parameter GUIDs retrieved // from the shared parameter file. static Guid _parameter_host_type = new Guid( "27188736-2491-4ac8-b634-8f4c9399afef" ); static Guid _parameter_host_id = new Guid( "64221c53-558b-4f29-a469-039a2001a037" ); public static Guid _parameter_key = new Guid( "f48cd131-b9b6-432a-8b5c-a7534183a880" ); public static Guid _parameter_point_nr = new Guid( "febfe8b9-6938-4099-8cf6-d62f58a9c933" ); static Guid _parameter_x = new Guid( "7a5d1056-a1df-4389-b026-9f32fc3ac5fb" ); static Guid _parameter_y = new Guid( "84f9a2be-85d5-44da-94b9-fc5b7808026b" ); static Guid _parameter_z = new Guid( "04c33d6a-f7f1-450c-8b15-9ac9aba24606" ); #endregion // Setout point family identification constants /// <summary> /// Retrieve project base point. /// </summary> bool GetBasePoint( Document doc, out XYZ basePoint, out double north ) { BuiltInParameter[] bip = new[] { BuiltInParameter.BASEPOINT_EASTWEST_PARAM, BuiltInParameter.BASEPOINT_NORTHSOUTH_PARAM, BuiltInParameter.BASEPOINT_ELEVATION_PARAM, BuiltInParameter.BASEPOINT_ANGLETON_PARAM }; FilteredElementCollector col = new FilteredElementCollector( doc ) .OfClass( typeof( BasePoint ) ); Parameter p = null; basePoint = null; north = 0; foreach( BasePoint bp in col ) { basePoint = new XYZ( bp.get_Parameter( bip[0] ).AsDouble(), bp.get_Parameter( bip[1] ).AsDouble(), bp.get_Parameter( bip[2] ).AsDouble() ); Debug.Print( "base point {0}", GeomVertices.PointString( basePoint ) ); p = bp.get_Parameter( bip[3] ); if( null != p ) { north = p.AsDouble(); Debug.Print( "north {0}", north ); break; } } return null != p; } /// <summary> /// Return the project location transform. /// </summary> Transform GetProjectLocationTransform( Document doc ) { // Retrieve the active project location position. ProjectPosition projectPosition = doc.ActiveProjectLocation.get_ProjectPosition( XYZ.Zero ); // Create a translation vector for the offsets XYZ translationVector = new XYZ( projectPosition.EastWest, projectPosition.NorthSouth, projectPosition.Elevation ); Transform translationTransform = Transform.CreateTranslation( translationVector ); // Create a rotation for the angle about true north //Transform rotationTransform // = Transform.get_Rotation( XYZ.Zero, // XYZ.BasisZ, projectPosition.Angle ); Transform rotationTransform = Transform.CreateRotation( XYZ.BasisZ, projectPosition.Angle ); // Combine the transforms Transform finalTransform = translationTransform.Multiply( rotationTransform ); return finalTransform; } /// <summary> /// Retrieve or load the setout point family symbols. /// </summary> public static FamilySymbol[] GetFamilySymbols( Document doc, bool loadIt ) { FamilySymbol[] symbols = null; Family family = new FilteredElementCollector( doc ) .OfClass( typeof( Family ) ) .FirstOrDefault<Element>( e => e.Name.Equals( FamilyName ) ) as Family; // If the family is not already loaded, do so: if( null == family && loadIt ) { // Load the setout point family using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Load Setout Point Family" ); //if( !doc.LoadFamilySymbol( // _family_path, SymbolName, out symbol ) ) if( doc.LoadFamily( _family_path, out family ) ) { foreach( ElementId id in family .GetFamilySymbolIds() ) { ( doc.GetElement( id ) as FamilySymbol ).Activate(); } tx.Commit(); } else { tx.RollBack(); } } } if( null != family ) { symbols = new FamilySymbol[2]; int i = 0; //foreach( FamilySymbol s in family.Symbols ) // 2014 foreach( ElementId id in family .GetFamilySymbolIds() ) // 2015 { symbols[i++] = doc.GetElement( id ) as FamilySymbol; } Debug.Assert( symbols[0].Name.EndsWith( "Major" ), "expected major (key) setout point first" ); Debug.Assert( symbols[1].Name.EndsWith( "Minor" ), "expected minor setout point second" ); } return symbols; } //const double _feetToMm = 25.4 * 12.0; /// <summary> /// Setout point number, continues growing from /// one command launch to the next. /// </summary> static int _point_number = 0; public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; // Useless initial attempt to retrieve project // location to calculate project location: //XYZ basePoint; //double north; //GetBasePoint( doc, out basePoint, out north ); // Successful retrieval of active project // location position as a transform: Transform projectLocationTransform = GetProjectLocationTransform( doc ); // Load or retrieve setout point family symbols: FamilySymbol[] symbols = GetFamilySymbols( doc, true ); if( null == symbols ) { message = string.Format( "Unable to load setout point family from '{1}'.", _family_path ); return Result.Failed; } // Retrieve structural concrete elements. FilteredElementCollector col = GetStructuralElements( doc ); // Retrieve element geometry and place a // setout point on each geometry corner. // Setout points are numbered starting at // one each time the command is run with // no decoration or prefix whatsoever. using( Transaction tx = new Transaction( doc ) ) { tx.Start( "Place Setout Points" ); Options opt = app.Create.NewGeometryOptions(); // On the very first attempt only, run an error // check to see whether the required shared // parameters have actually been bound: bool first = true; foreach( Element e in col ) { Transform t; List<Solid> solids = GeomVertices.GetSolids( e, opt, out t ); string desc = ElementDescription( e ); if( null == solids || 0 == solids.Count ) { Debug.Print( "Unable to access element solid for element {0}.", desc ); continue; } Dictionary<XYZ, int> corners = GeomVertices.GetCorners( solids ); int n = corners.Count; Debug.Print( "{0}: {1} corners found:", desc, n ); foreach( XYZ p in corners.Keys ) { ++_point_number; Debug.Print( " {0}: {1}", _point_number, GeomVertices.PointString( p ) ); XYZ p1 = t.OfPoint( p ); // Handle error saying, "The symbol is not // active.\r\nParameter name: symbol". FamilyInstance fi = doc.Create.NewFamilyInstance( p1, symbols[1], StructuralType.NonStructural ); #region Test shared parameter availability #if TEST_SHARED_PARAMETERS // Test code to ensure that the shared // parameters really are available Parameter p1 = fi.get_Parameter( "X" ); Parameter p2 = fi.get_Parameter( "Y" ); Parameter p3 = fi.get_Parameter( "Z" ); Parameter p4 = fi.get_Parameter( "Host_Geometry" ); Parameter p5 = fi.get_Parameter( "Point_Number" ); //doc.Regenerate(); // no need for this, thankfully //Parameter p11 = fi.get_Parameter( // "{7a5d1056-a1df-4389-b026-9f32fc3ac5fb}" ); //Parameter p12 = fi.get_Parameter( // "7a5d1056-a1df-4389-b026-9f32fc3ac5fb" ); #endif // TEST_SHARED_PARAMETERS #endregion // Test shared parameter availability // Add shared parameter data immediately // after creating the new family instance. // The shared parameters are indeed added // immediately by Revit, so we can access and // populate them. // No need to commit the transaction that // added the family instance to give Revit // a chance to add the shared parameters to // it, nor to regenerate the document, we // can write the shared parameter values // right away. if( first ) { Parameter q = fi.get_Parameter( _parameter_x ); if( null == q ) { message = "The required shared parameters " + "X, Y, Z, Host_Id, Host_Type and " + "Point_Number are missing."; tx.RollBack(); return Result.Failed; } first = false; } // Transform insertion point by applying // base point offset, scaling from feet, // and rotating to project north. //XYZ r1 = ( p + basePoint) * _feetToMm; // Transform insertion point by applying // project location transformation. XYZ r2 = projectLocationTransform.OfPoint( p ); fi.get_Parameter( _parameter_host_type ).Set( GetHostType( e ).ToString() ); fi.get_Parameter( _parameter_host_id ).Set( e.Id.IntegerValue ); fi.get_Parameter( _parameter_point_nr ).Set( _point_number.ToString() ); fi.get_Parameter( _parameter_x ).Set( r2.X ); fi.get_Parameter( _parameter_y ).Set( r2.Y ); fi.get_Parameter( _parameter_z ).Set( r2.Z ); } } tx.Commit(); } return Result.Succeeded; } } }
namespace Microsoft.Protocols.TestSuites.MS_ASCMD { using System; using System.Collections.Generic; using System.Text; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestSuites.Common.DataStructures; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using Request = Microsoft.Protocols.TestSuites.Common.Request; using Response = Microsoft.Protocols.TestSuites.Common.Response; /// <summary> /// This scenario is used to test the SmartForward command. /// </summary> [TestClass] public class S17_SmartForward : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanup() { TestClassBase.Cleanup(); } #endregion #region Test cases /// <summary> /// This test case is used to verify the server returns an empty response, when mail forward successfully. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC01_SmartForward_Success() { #region Call SendMail command to send plain text email messages to user2. string emailSubject = Common.GenerateResourceName(Site, "subject"); this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null); #endregion #region Call Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); SyncResponse syncChangeResponse = this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject); string originalServerID = TestSuiteBase.FindServerId(syncChangeResponse, "Subject", emailSubject); string originalContent = TestSuiteBase.GetDataFromResponseBodyElement(syncChangeResponse, originalServerID); #endregion #region Record user name, folder collectionId and item subject that are used in this case TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject); #endregion #region Call SmartForward command to forward messages without retrieving the full, original message from the server. string forwardSubject = string.Format("FW:{0}", emailSubject); SmartForwardRequest smartForwardRequest = this.CreateDefaultForwardRequest(originalServerID, forwardSubject, this.User2Information.InboxCollectionId); SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); #endregion #region Verify Requirements MS-ASCMD_R568, MS-ASCMD_R4407 // If the message was forwarded successfully, server returns an empty response without XML body, then MS-ASCMD_R568, MS-ASCMD_R4407 are verified. // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R568"); // Verify MS-ASCMD requirement: MS-ASCMD_R568 Site.CaptureRequirementIfAreEqual<string>( string.Empty, smartForwardResponse.ResponseDataXML, 568, @"[In SmartForward] If the message was forwarded successfully, the server returns an empty response."); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4407"); // Verify MS-ASCMD requirement: MS-ASCMD_R4407 Site.CaptureRequirementIfAreEqual<string>( string.Empty, smartForwardResponse.ResponseDataXML, 4407, @"[In Status(SmartForward and SmartReply)] If the SmartForward command request [or SmartReply command request] succeeds, no XML body is returned in the response."); #endregion #region After user2 forwarded email to user3, sync user3 mailbox changes this.SwitchUser(this.User3Information); SyncResponse syncForwardResult = this.GetMailItem(this.User3Information.InboxCollectionId, forwardSubject); string forwardItemServerID = TestSuiteBase.FindServerId(syncForwardResult, "Subject", forwardSubject); string forwardItemContent = TestSuiteBase.GetDataFromResponseBodyElement(syncForwardResult, forwardItemServerID); #endregion #region Record user name, folder collectionId and item subject that are used in this case TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User3Information.InboxCollectionId, forwardSubject); #endregion // Compare original content with forward content bool isContained = forwardItemContent.Contains(originalContent); #region Verify Requirements MS-ASCMD_R532 // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R532"); // Verify MS-ASCMD requirement: MS-ASCMD_R532 Site.CaptureRequirementIfIsNotNull( forwardItemServerID, 532, @"[In SmartForward] The SmartForward command is used by clients to forward messages without retrieving the full, original message from the server."); #endregion } /// <summary> /// This test case is used to verify server returns status code, when SmartForward is failed. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC02_SmartForward_Fail() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The AccountID element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The AccountID element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Call SendMail command to send one plain text email messages to user2. string emailSubject = Common.GenerateResourceName(Site, "subject"); this.SendPlainTextEmail(null, emailSubject, this.User1Information.UserName, this.User2Information.UserName, null); #endregion #region Call Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); SyncResponse syncChangeResponse = this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject); string originalServerId = TestSuiteBase.FindServerId(syncChangeResponse, "Subject", emailSubject); #endregion #region Record user name, folder collectionId and item subject that are used in this case TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject); #endregion #region Call SmartForward command to forward messages without retrieving the full, original message from the server // Create invalid SmartForward request SmartForwardRequest smartForwardRequest = new SmartForwardRequest { RequestData = new Request.SmartForward { ClientId = System.Guid.NewGuid().ToString(), Source = new Request.Source { FolderId = this.User2Information.InboxCollectionId, ItemId = originalServerId }, Mime = string.Empty, AccountId = "InvalidValueAccountID" } }; smartForwardRequest.SetCommandParameters(new Dictionary<CmdParameterName, object> { { CmdParameterName.CollectionId, this.User2Information.InboxCollectionId }, { CmdParameterName.ItemId, "5:" + originalServerId } }); SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R4408"); // Verify MS-ASCMD requirement: MS-ASCMD_R4408 // If SmartForward operation failed, server will return Status element in response, then MS-ASCMD_4408 is verified. Site.CaptureRequirementIfIsNotNull( smartForwardResponse.ResponseData.Status, 4408, @"[In Status(SmartForward and SmartReply)] If the SmartForward command request [or SmartReply command request] fails, the Status element contains a code that indicates the type of failure."); } /// <summary> /// This test case is used to verify when the SmartForward command is used for an appointment, the original message is included as an attachment in the outgoing message. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC03_SmartForwardAppointment() { #region User1 calls Sync command uploading one calendar item to create one appointment string meetingRequestSubject = Common.GenerateResourceName(Site, "subject"); Calendar calendar = new Calendar { OrganizerEmail = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), OrganizerName = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain), UID = Guid.NewGuid().ToString(), Subject = meetingRequestSubject }; this.SyncAddCalendar(calendar); // Calls Sync command to sync user1's calendar folder SyncResponse syncUser1CalendarFolder = this.GetMailItem(this.User1Information.CalendarCollectionId, meetingRequestSubject); string calendarItemId = TestSuiteBase.FindServerId(syncUser1CalendarFolder, "Subject", meetingRequestSubject); // Record items need to be cleaned up. TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.CalendarCollectionId, meetingRequestSubject); #endregion #region User1 calls smartForward command to forward mail to user2 string forwardFromUser = Common.GetMailAddress(this.User1Information.UserName, this.User1Information.UserDomain); string forwardToUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); string forwardSubject = string.Format("FW:{0}", meetingRequestSubject); string forwardContent = Common.GenerateResourceName(Site, "forward:Appointment body"); SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(this.User1Information.CalendarCollectionId, calendarItemId, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent); SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); Site.Assert.AreEqual(string.Empty, smartForwardResponse.ResponseDataXML, "If SmartForward command executes successfully, server should return empty xml data"); #endregion #region User2 calls Sync command to get the forward mail sent by user1 this.SwitchUser(this.User2Information); SyncResponse user2MailboxChange = this.GetMailItem(this.User2Information.InboxCollectionId, forwardSubject); // Record items need to be cleaned up. TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, forwardSubject); string mailItemServerId = TestSuiteBase.FindServerId(user2MailboxChange, "Subject", forwardSubject); Response.Attachments attachments = (Response.Attachments)TestSuiteBase.GetElementValueFromSyncResponse(user2MailboxChange, mailItemServerId, Response.ItemsChoiceType8.Attachments); Site.Assert.AreEqual<int>(1, attachments.Items.Length, "Server should return one attachment, if SmartForward one appointment executes successfully."); #endregion } /// <summary> /// This test case is used to verify if the value of the InstanceId element is invalid, the server returns status value 104. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC04_SmartForwardWithInvalidInstanceId() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The InstanceId element is not supported when the MS-ASProtocolVersion header is set to 12.1. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The InstanceId element is not supported when the MS-ASProtocolVersion header is set to 14.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.0"); Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.1"); #region User1 calls SendMail command to send one recurring meeting request to user2. string meetingRequestSubject = Common.GenerateResourceName(Site, "subject"); string attendeeEmailAddress = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); this.SendWeeklyRecurrenceMeetingRequest(meetingRequestSubject, attendeeEmailAddress); #endregion #region User2 calls Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); this.GetMailItem(this.User2Information.InboxCollectionId, meetingRequestSubject); SyncResponse syncCalendarResponse = this.GetMailItem(this.User2Information.CalendarCollectionId, meetingRequestSubject); string calendarItemID = TestSuiteBase.FindServerId(syncCalendarResponse, "Subject", meetingRequestSubject); TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, meetingRequestSubject); TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.CalendarCollectionId, meetingRequestSubject); #endregion #region User2 calls SmartForward command to forward the calendar item to user3 with invalid InstanceId value in SmartForward request string forwardFromUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); string forwardToUser = Common.GetMailAddress(this.User3Information.UserName, this.User3Information.UserDomain); string forwardSubject = string.Format("FW:{0}", meetingRequestSubject); string forwardContent = Common.GenerateResourceName(Site, "forward:Meeting Instance body"); SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(this.User2Information.CalendarCollectionId, calendarItemID, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent); // Set instanceID with format not the same as required format "2010-03-20T22:40:00.000Z". string instanceID = DateTime.Now.ToString(); smartForwardRequest.RequestData.Source.InstanceId = instanceID; SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R541"); // Verify MS-ASCMD requirement: MS-ASCMD_R541 Site.CaptureRequirementIfAreEqual<string>( "104", smartForwardResponse.ResponseData.Status, 541, @"[In SmartForward] If the value of the InstanceId element is invalid, the server responds with Status element (section 2.2.3.162.15) value 104, as specified in section 2.2.4."); } /// <summary> /// This test case is used to verify when SmartForward is applied to a recurring meeting, the InstanceId element specifies the ID of a particular occurrence in the recurring meeting. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC05_SmartForwardWithInstanceIdSuccess() { Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.0"); Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.1"); #region User1 calls SendMail command to send one recurring meeting request to user2. string meetingRequestSubject = Common.GenerateResourceName(Site, "subject"); string attendeeEmailAddress = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); this.SendWeeklyRecurrenceMeetingRequest(meetingRequestSubject, attendeeEmailAddress); #endregion #region User2 calls Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); SyncResponse syncMeetingMailResponse = this.GetMailItem(this.User2Information.InboxCollectionId, meetingRequestSubject); // Record relative items for clean up. TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, meetingRequestSubject); #endregion #region User2 calls MeetingResponse command to accept the meeting string serverIDForMeetingRequest = TestSuiteBase.FindServerId(syncMeetingMailResponse, "Subject", meetingRequestSubject); MeetingResponseRequest meetingResponseRequest = TestSuiteBase.CreateMeetingResponseRequest(1, this.User2Information.InboxCollectionId, serverIDForMeetingRequest, string.Empty); // If the user accepts the meeting request, the meeting request mail will be deleted and calendar item will be created. MeetingResponseResponse meetingResponseResponse = this.CMDAdapter.MeetingResponse(meetingResponseRequest); Site.Assert.IsNotNull(meetingResponseResponse.ResponseData.Result[0].CalendarId, "If the meeting was accepted, server should return calendarId in response"); TestSuiteBase.RemoveRecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, meetingRequestSubject); this.GetMailItem(this.User2Information.DeletedItemsCollectionId, meetingRequestSubject); TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.DeletedItemsCollectionId, meetingRequestSubject); #endregion #region User2 calls Sync command to sync user calendar changes SyncResponse syncCalendarResponse = this.GetMailItem(this.User2Information.CalendarCollectionId, meetingRequestSubject); string calendarItemID = TestSuiteBase.FindServerId(syncCalendarResponse, "Subject", meetingRequestSubject); string startTime = (string)TestSuiteBase.GetElementValueFromSyncResponse(syncCalendarResponse, calendarItemID, Response.ItemsChoiceType8.StartTime); Response.Recurrence recurrence = (Response.Recurrence)TestSuiteBase.GetElementValueFromSyncResponse(syncCalendarResponse, calendarItemID, Response.ItemsChoiceType8.Recurrence); Site.Assert.IsNotNull(recurrence, "If user2 received recurring meeting request, the calendar item should contain recurrence element"); // Record relative items for clean up. TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.CalendarCollectionId, meetingRequestSubject); #endregion #region User2 calls SmartForward command to forward the calendar item to user3 with correct InstanceId value in SmartForward request string forwardFromUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); string forwardToUser = Common.GetMailAddress(this.User3Information.UserName, this.User3Information.UserDomain); string forwardSubject = string.Format("FW:{0}", meetingRequestSubject); string forwardContent = Common.GenerateResourceName(Site, "forward:Meeting Instance body"); SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(this.User2Information.CalendarCollectionId, calendarItemID, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent); // Set instanceID with format the same as required format "2010-03-20T22:40:00.000Z". string instanceID = ConvertInstanceIdFormat(startTime); smartForwardRequest.RequestData.Source.InstanceId = instanceID; SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); Site.Assert.AreEqual(string.Empty, smartForwardResponse.ResponseDataXML, "If SmartForward command executes successfully, server should return empty xml data"); #endregion #region After user2 forwards email to user3, sync user3 mailbox changes this.SwitchUser(this.User3Information); SyncResponse syncForwardResult = this.GetMailItem(this.User3Information.InboxCollectionId, forwardSubject); string forwardItemServerID = TestSuiteBase.FindServerId(syncForwardResult, "Subject", forwardSubject); // Sync user3 Calendar folder SyncResponse syncUser3CalendarFolder = this.GetMailItem(this.User3Information.CalendarCollectionId, forwardSubject); string user3CalendarItemID = TestSuiteBase.FindServerId(syncUser3CalendarFolder, "Subject", forwardSubject); // Record email items for clean up TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User3Information.InboxCollectionId, forwardSubject); TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User3Information.CalendarCollectionId, forwardSubject); #endregion #region Record the meeting forward notification mail which sent from server to User1. this.SwitchUser(this.User1Information); string notificationSubject = "Meeting Forward Notification: " + forwardSubject; TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.DeletedItemsCollectionId, notificationSubject); this.GetMailItem(this.User1Information.DeletedItemsCollectionId, notificationSubject); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R538"); // Verify MS-ASCMD requirement: MS-ASCMD_R538 // If the calendar item with specified subject exists in user3 Calendar folder and email item exists in user3 Inbox folder which means user3 gets the forwarded mail. Site.CaptureRequirementIfIsTrue( user3CalendarItemID != null && forwardItemServerID != null, 538, @"[In SmartForward] When SmartForward is applied to a recurring meeting, the InstanceId element (section 2.2.3.83.2) specifies the ID of a particular occurrence in the recurring meeting."); } /// <summary> /// This test case is used to verify when SmartForward request without the InstanceId element, the implementation forward the entire recurring meeting. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC06_SmartForwardRecurringMeetingWithoutInstanceId() { Site.Assume.IsTrue(Common.IsRequirementEnabled(5834, this.Site), "[In Appendix A: Product Behavior] If SmartForward is applied to a recurring meeting and the InstanceId element is absent, the implementation does forward the entire recurring meeting. (Exchange 2007 and above follow this behavior.)"); Site.Assume.AreNotEqual<string>("16.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.0"); Site.Assume.AreNotEqual<string>("16.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "Recurrences cannot be added in protocol version 16.1"); #region User1 calls SendMail command to send one recurring meeting request to user2. string meetingRequestSubject = Common.GenerateResourceName(Site, "subject"); string attendeeEmailAddress = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); this.SendWeeklyRecurrenceMeetingRequest(meetingRequestSubject, attendeeEmailAddress); // Record relative items for clean up TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.InboxCollectionId, meetingRequestSubject); TestSuiteBase.RecordCaseRelativeItems(this.User1Information, this.User1Information.CalendarCollectionId, meetingRequestSubject); #endregion #region User2 calls Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); this.GetMailItem(this.User2Information.InboxCollectionId, meetingRequestSubject); SyncResponse syncCalendarResponse = this.GetMailItem(this.User2Information.CalendarCollectionId, meetingRequestSubject); string calendarItemID = TestSuiteBase.FindServerId(syncCalendarResponse, "Subject", meetingRequestSubject); Response.Recurrence recurrence = (Response.Recurrence)TestSuiteBase.GetElementValueFromSyncResponse(syncCalendarResponse, calendarItemID, Response.ItemsChoiceType8.Recurrence); Site.Assert.IsNotNull(recurrence, "If user2 received recurring meeting request, the calendar item should contain recurrence element"); // Record relative items for clean up TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, meetingRequestSubject); TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.CalendarCollectionId, meetingRequestSubject); #endregion #region User2 calls SmartForward command to forward the calendar item to user3 without InstanceId element in SmartForward request string forwardFromUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); string forwardToUser = Common.GetMailAddress(this.User3Information.UserName, this.User3Information.UserDomain); string forwardSubject = string.Format("FW:{0}", meetingRequestSubject); string forwardContent = Common.GenerateResourceName(Site, "forward:Meeting Instance body"); SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(this.User2Information.CalendarCollectionId, calendarItemID, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent); smartForwardRequest.RequestData.Source.InstanceId = null; SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); Site.Assert.AreEqual(string.Empty, smartForwardResponse.ResponseDataXML, "If SmartForward command executes successfully, server should return empty xml data"); #endregion #region After user2 forwards email to user3, sync user3 mailbox changes this.SwitchUser(this.User3Information); SyncResponse syncForwardResult = this.GetMailItem(this.User3Information.InboxCollectionId, forwardSubject); string forwardItemServerID = TestSuiteBase.FindServerId(syncForwardResult, "Subject", forwardSubject); Response.MeetingRequest user3Meeting = (Response.MeetingRequest)TestSuiteBase.GetElementValueFromSyncResponse(syncForwardResult, forwardItemServerID, Response.ItemsChoiceType8.MeetingRequest); // Record email items for clean up TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User2Information.InboxCollectionId, forwardSubject); TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User2Information.CalendarCollectionId, forwardSubject); #endregion #region Check the meeting forward notification mail which is sent from server to User1. this.SwitchUser(this.User1Information); string notificationSubject = "Meeting Forward Notification: " + forwardSubject; this.CheckMeetingForwardNotification(this.User1Information, notificationSubject); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R5834"); // Verify MS-ASCMD requirement: MS-ASCMD_R5834 // If the calendar item with specified subject contains Recurrence element, which indicates user3 received the entire meeting request. Site.CaptureRequirementIfIsTrue( user3Meeting.Recurrences != null && forwardItemServerID != null, 5834, @"[In Appendix A: Product Behavior] If SmartForward is applied to a recurring meeting and the InstanceId element is absent, the implementation does forward the entire recurring meeting. (Exchange 2007 and above follow this behavior.)"); } /// <summary> /// This test case is used to verify when ReplaceMime is present in the request, the body or attachment is not included. /// </summary> [TestCategory("MSASCMD"), TestMethod()] public void MSASCMD_S17_TC07_SmartForward_ReplaceMime() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "ReplaceMime is not support when MS-ASProtocolVersion header is set to 12.1.MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Call SendMail command to send plain text email messages to user2. string emailSubject = Common.GenerateResourceName(Site, "subject"); string emailBody = Common.GenerateResourceName(Site, "NormalAttachment_Body"); this.SendEmailWithAttachment(emailSubject, emailBody); #endregion #region Call Sync command to sync user2 mailbox changes this.SwitchUser(this.User2Information); SyncResponse syncChangeResponse = this.GetMailItem(this.User2Information.InboxCollectionId, emailSubject); string originalServerID = TestSuiteBase.FindServerId(syncChangeResponse, "Subject", emailSubject); string originalContent = TestSuiteBase.GetDataFromResponseBodyElement(syncChangeResponse, originalServerID); Response.AttachmentsAttachment[] originalAttachments = this.GetEmailAttachments(syncChangeResponse, emailSubject); Site.Assert.IsTrue(originalAttachments != null && originalAttachments.Length == 1, "The email should contain a single attachment."); #endregion #region Record user name, folder collectionId and item subject that are used in this case TestSuiteBase.RecordCaseRelativeItems(this.User2Information, this.User2Information.InboxCollectionId, emailSubject); #endregion #region Call SmartForward command to forward messages with ReplaceMime. string forwardSubject = string.Format("FW:{0}", emailSubject); SmartForwardRequest smartForwardRequest = this.CreateDefaultForwardRequest(originalServerID, forwardSubject, this.User2Information.InboxCollectionId); smartForwardRequest.RequestData.ReplaceMime = string.Empty; SmartForwardResponse smartForwardResponse = this.CMDAdapter.SmartForward(smartForwardRequest); #endregion #region After user2 forwarded email to user3, sync user3 mailbox changes this.SwitchUser(this.User3Information); SyncResponse syncForwardResult = this.GetMailItem(this.User3Information.InboxCollectionId, forwardSubject); string forwardItemServerID = TestSuiteBase.FindServerId(syncForwardResult, "Subject", forwardSubject); string forwardItemContent = TestSuiteBase.GetDataFromResponseBodyElement(syncForwardResult, forwardItemServerID); Response.AttachmentsAttachment[] forwardAttachments = this.GetEmailAttachments(syncForwardResult, forwardSubject); #endregion #region Record user name, folder collectionId and item subject that are used in this case TestSuiteBase.RecordCaseRelativeItems(this.User3Information, this.User3Information.InboxCollectionId, forwardSubject); #endregion // Compare original content with forward content bool isContained = forwardItemContent.Contains(originalContent); // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASCMD_R3775"); Site.Assert.IsNull( forwardAttachments, @"The attachment should not be returned"); Site.CaptureRequirementIfIsFalse( isContained, 3775, @"[In ReplaceMime] When the ReplaceMime element is present, the server MUST not include the body or attachments of the original message being forwarded."); } #endregion #region Private methods /// <summary> /// Try to parse the no separator time string to DateTime /// </summary> /// <param name="time">The specified DateTime string</param> /// <returns>Return the DateTime with instanceId specified format</returns> private static string ConvertInstanceIdFormat(string time) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(time.Substring(0, 4)); stringBuilder.Append("-"); stringBuilder.Append(time.Substring(4, 2)); stringBuilder.Append("-"); stringBuilder.Append(time.Substring(6, 5)); stringBuilder.Append(":"); stringBuilder.Append(time.Substring(11, 2)); stringBuilder.Append(":"); stringBuilder.Append(time.Substring(13, 2)); stringBuilder.Append(".000"); stringBuilder.Append(time.Substring(15)); return stringBuilder.ToString(); } /// <summary> /// Set sync request application data with calendar value /// </summary> /// <param name="calendar">The calendar instance</param> /// <returns>The application data for sync request</returns> private static Request.SyncCollectionAddApplicationData SetApplicationDataFromCalendar(Calendar calendar) { Request.SyncCollectionAddApplicationData applicationData = new Request.SyncCollectionAddApplicationData(); List<Request.ItemsChoiceType8> elementName = new List<Request.ItemsChoiceType8>(); List<object> elementValue = new List<object>(); // Set application data elementName.Add(Request.ItemsChoiceType8.Timezone); elementValue.Add(calendar.Timezone); elementName.Add(Request.ItemsChoiceType8.Subject); elementValue.Add(calendar.Subject); elementName.Add(Request.ItemsChoiceType8.Sensitivity); elementValue.Add(calendar.Sensitivity); elementName.Add(Request.ItemsChoiceType8.BusyStatus); elementValue.Add(calendar.BusyStatus); elementName.Add(Request.ItemsChoiceType8.AllDayEvent); elementValue.Add(calendar.AllDayEvent); applicationData.ItemsElementName = elementName.ToArray(); applicationData.Items = elementValue.ToArray(); return applicationData; } /// <summary> /// Create default SmartForward request to forward an item from user 2 to user 3. /// </summary> /// <param name="originalServerID">The item serverID</param> /// <param name="forwardSubject">The forward mail subject</param> /// <param name="senderCollectionId">The sender inbox collectionId</param> /// <returns>The SmartForward request</returns> private SmartForwardRequest CreateDefaultForwardRequest(string originalServerID, string forwardSubject, string senderCollectionId) { string forwardFromUser = Common.GetMailAddress(this.User2Information.UserName, this.User2Information.UserDomain); string forwardToUser = Common.GetMailAddress(this.User3Information.UserName, this.User3Information.UserDomain); string forwardContent = Common.GenerateResourceName(Site, "forward:body"); SmartForwardRequest smartForwardRequest = this.CreateSmartForwardRequest(senderCollectionId, originalServerID, forwardFromUser, forwardToUser, string.Empty, string.Empty, forwardSubject, forwardContent); return smartForwardRequest; } /// <summary> /// Add a meeting or appointment to server /// </summary> /// <param name="calendar">the calendar item</param> private void SyncAddCalendar(Calendar calendar) { Request.SyncCollectionAddApplicationData applicationData = SetApplicationDataFromCalendar(calendar); this.GetInitialSyncResponse(this.User1Information.CalendarCollectionId); Request.SyncCollectionAdd addCalendar = new Request.SyncCollectionAdd { ClientId = TestSuiteBase.ClientId, ApplicationData = applicationData }; SyncRequest syncAddCalendarRequest = TestSuiteBase.CreateSyncAddRequest(this.LastSyncKey, this.User1Information.CalendarCollectionId, addCalendar); SyncResponse syncAddCalendarResponse = this.CMDAdapter.Sync(syncAddCalendarRequest); // Get data from response Response.SyncCollections syncCollections = (Response.SyncCollections)syncAddCalendarResponse.ResponseData.Item; Response.SyncCollectionsCollectionResponses syncResponses = null; for (int index = 0; index < syncCollections.Collection[0].ItemsElementName.Length; index++) { if (syncCollections.Collection[0].ItemsElementName[index] == Response.ItemsChoiceType10.Responses) { syncResponses = (Response.SyncCollectionsCollectionResponses)syncCollections.Collection[0].Items[index]; break; } } Site.Assert.AreEqual(1, syncResponses.Add.Length, "User only upload one calendar item"); int statusCode = int.Parse(syncResponses.Add[0].Status); Site.Assert.AreEqual(1, statusCode, "If upload calendar item successful, server should return status 1"); } #endregion } }